Skip to content

Commit

Permalink
upd
Browse files Browse the repository at this point in the history
  • Loading branch information
m5l14i11 committed Sep 8, 2024
1 parent a960e72 commit 571d825
Showing 1 changed file with 18 additions and 6 deletions.
24 changes: 18 additions & 6 deletions sor/_twap.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,18 @@
class TWAP:
def __init__(self, config_service: AbstractConfig):
self.config = config_service.get("position")
self.duration = self.config["twap_duration"]

async def next_value(self, symbol: Symbol, exchange: AbstractExchange):
current_time = 0
timepoints = []
twap_duration = self.config["twap_duration"]

while current_time < twap_duration:
while current_time < self.duration:
bids, ask = self._fetch_book(symbol, exchange)

timepoints.append((bids[:, 0], ask[:, 0], bids[:, 1], ask[:, 1]))

time_interval = self._volatility_time_interval(timepoints)
time_interval = TWAP._volatility_time_interval(timepoints)
current_time += time_interval

yield self._twap(timepoints)
Expand All @@ -44,10 +44,11 @@ def _twap(order_book):
bid_weighted_average = np.sum(bid_prices * bid_volume) / total_bid_volume
ask_weighted_average = np.sum(ask_prices * ask_volume) / total_ask_volume

diff = ask_prices - bid_prices

mid_price = (bid_weighted_average + ask_weighted_average) / 2.0
spread, volatility = np.mean(diff), np.std(diff)

spread, volatility = TWAP._calculate_volatility_spread(
bid_prices, ask_prices, bid_volume, ask_volume
)

adj_spread = spread * volatility

Expand All @@ -56,6 +57,17 @@ def _twap(order_book):

return bid_price, ask_price

@staticmethod
def _calculate_volatility_spread(bid_prices, ask_prices, bid_volume, ask_volume):
diff = ask_prices - bid_prices
spread = np.mean(diff)

total_volume = bid_volume + ask_volume
vol_weighted = np.sum(diff**2 * total_volume) / np.sum(total_volume)
volatility = np.sqrt(vol_weighted)

return spread, volatility

@staticmethod
def _volatility_time_interval(timepoints):
high_prices = np.concatenate([ask_prices for _, ask_prices, _, _ in timepoints])
Expand Down

0 comments on commit 571d825

Please sign in to comment.