-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathround_3.py
1521 lines (1183 loc) · 59.2 KB
/
round_3.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from datamodel import OrderDepth, TradingState, Order, Symbol, ProsperityEncoder, Listing, Trade, Observation
from typing import List, Any, Tuple
import json
import numpy as np
import collections
class Strategy:
def __init__(self, name: str, max_position: int):
self.name: str = name
self.cached_prices: list = []
self.cached_means: list = []
self.max_pos: int = max_position
self.trade_count: int = 1
self.prod_position: int = 0
self.new_buy_orders: int = 0
self.new_sell_orders: int = 0
self.order_depth: OrderDepth = OrderDepth()
def reset_from_state(self, state: TradingState):
self.prod_position = state.position[self.name] if self.name in state.position.keys() else 0
self.order_depth: OrderDepth = state.order_depths[self.name]
self.new_buy_orders = 0
self.new_sell_orders = 0
def sell_product(self, best_bids, i, order_depth, orders):
# Sell product at best bid
best_bid_volume = order_depth.buy_orders[best_bids[i]]
if self.prod_position - best_bid_volume >= -self.max_pos:
orders.append(Order(self.name, best_bids[i], -best_bid_volume))
self.prod_position += -best_bid_volume
self.new_sell_orders += best_bid_volume
else:
# Sell as much as we can without exceeding the self.max_pos[product]
vol = self.prod_position + self.max_pos
orders.append(Order(self.name, best_bids[i], -vol))
self.prod_position += -vol
self.new_sell_orders += vol
def buy_product(self, best_asks, i, order_depth, orders):
# Buy product at best ask
best_ask_volume = order_depth.sell_orders[best_asks[i]]
if self.prod_position - best_ask_volume <= self.max_pos:
orders.append(Order(self.name, best_asks[i], -best_ask_volume))
self.prod_position += -best_ask_volume
self.new_buy_orders += -best_ask_volume
else:
# Buy as much as we can without exceeding the self.max_pos[product]
vol = self.max_pos - self.prod_position
orders.append(Order(self.name, best_asks[i], vol))
self.prod_position += vol
self.new_buy_orders += vol
def continuous_buy(self, order_depth: OrderDepth, orders: list):
if len(order_depth.sell_orders) != 0:
best_asks = sorted(order_depth.sell_orders.keys())
i = 0
while i < self.trade_count and len(best_asks) > i:
if self.prod_position == self.max_pos:
break
self.buy_product(best_asks, i, order_depth, orders)
i += 1
def continuous_sell(self, order_depth: OrderDepth, orders: list):
if len(order_depth.buy_orders) != 0:
best_bids = sorted(order_depth.buy_orders.keys(), reverse=True)
i = 0
while i < self.trade_count and len(best_bids) > i:
if self.prod_position == -self.max_pos:
break
self.sell_product(best_bids, i, order_depth, orders)
i += 1
class CrossStrategy(Strategy):
def __init__(self, name: str, min_req_price_difference: int, max_position: int):
super().__init__(name, max_position)
self.strategy_start_day = 2
self.old_asks = []
self.old_bids = []
self.min_req_price_difference = min_req_price_difference
# try the imbalance indicator: (total_bid_vol - total_ask_vol)/ (total_bid_vol + total_ask_vol), pos if bid vol is higher
self.imbalance = 0
self.direction = 0
# Stoikov Model
self.mm = StoikovMarketMaker(0.2, 5.4, 0, 20)
def trade(self, trading_state: TradingState, orders: list):
order_depth: OrderDepth = trading_state.order_depths[self.name]
self.cache_prices(order_depth)
if len(self.old_asks) < self.strategy_start_day or len(self.old_bids) < self.strategy_start_day:
return
avg_bid, avg_ask = self.calculate_prices(self.strategy_start_day)
# imbalance is not useful, stop using it
curr_imbalance = 0 # self.calculate_imbalance(self.strategy_start_day)
if curr_imbalance > self.imbalance:
# we may track the changes of the imbalance
pass
if curr_imbalance > 0.5:
self.direction = 1
elif curr_imbalance < -0.5:
self.direction = -1
else:
self.direction = 0
# update imbalance
self.imbalance = curr_imbalance
bid_volume = self.max_pos - self.prod_position
ask_volume = -self.max_pos - self.prod_position
#buy order
# orders.append(Order(self.name, int(avg_bid + self.min_req_price_difference + self.direction), bid_volume))
# #sell order
# orders.append(Order(self.name, int(avg_ask - self.min_req_price_difference + self.direction), ask_volume))
self.mm.update_inventory(self.prod_position)
bid_quote, ask_quote = self.mm.calculate_quotes(avg_bid,avg_ask)
if len(order_depth.sell_orders) != 0:
best_asks = sorted(order_depth.sell_orders.keys())
i = 0
while i < self.trade_count and len(best_asks) > i and best_asks[i] - bid_quote <= self.min_req_price_difference + self.direction:
if self.prod_position == self.max_pos:
break
self.buy_product(best_asks, i, order_depth, orders)
i += 1
if len(order_depth.buy_orders) != 0:
# Sort all the available buy orders by their price
best_bids = sorted(order_depth.buy_orders.keys(), reverse=True)
i = 0
# Check if the lowest bid (buy order) is lower than the above defined fair value
while i < self.trade_count and len(best_bids) > i and ask_quote - best_bids[i] <= self.min_req_price_difference - self.direction:
if self.prod_position == -self.max_pos:
break
self.sell_product(best_bids, i, order_depth, orders)
i += 1
def calculate_prices(self, days: int) -> Tuple[int, int]:
# Calculate the average bid and ask price for the last days
relevant_bids = []
for bids in self.old_bids[-days:]:
relevant_bids.extend([(value, bids[value]) for value in bids])
relevant_asks = []
for asks in self.old_asks[-days:]:
relevant_asks.extend([(value, asks[value]) for value in asks])
avg_bid = np.average([x[0] for x in relevant_bids], weights=[x[1] for x in relevant_bids])
avg_ask = np.average([x[0] for x in relevant_asks], weights=[x[1] for x in relevant_asks])
return avg_bid, avg_ask
def calculate_imbalance(self, days: int) -> float:
# Calculate the imbalance for the last days
relevant_bids = []
for bids in self.old_bids[-days:]:
relevant_bids.extend([(value, bids[value]) for value in bids])
relevant_asks = []
for asks in self.old_asks[-days:]:
relevant_asks.extend([(value, asks[value]) for value in asks])
bid_vol = sum([x[1] for x in relevant_bids])
ask_vol = sum([x[1] for x in relevant_asks])
if bid_vol + ask_vol == 0:
return 0
imbalance = (bid_vol - ask_vol)/ (bid_vol + ask_vol)
return imbalance
def cache_prices(self, order_depth: OrderDepth):
sell_orders = order_depth.sell_orders
buy_orders = order_depth.buy_orders
self.old_asks.append(sell_orders)
self.old_bids.append(buy_orders)
class DiffStrategy(Strategy):
def __init__(self, name: str, max_position: int, derivative_resolution: int, diff_thresh: int):
super().__init__(name, max_position)
self.derivative_resolution: int = derivative_resolution
self.diff_thresh: int = diff_thresh
def trade(self, trading_state: TradingState, orders: list):
order_depth: OrderDepth = trading_state.order_depths[self.name]
self.cache_purchased_prices(trading_state)
self.calculate_means()
diff = self.get_price_difference()
if diff < -self.diff_thresh and len(order_depth.sell_orders) != 0:
self.continuous_buy(order_depth, orders)
if diff > self.diff_thresh and len(order_depth.buy_orders) != 0:
self.continuous_sell(order_depth, orders)
def get_price_difference(self) -> float:
# Calculate the difference between the current mean and the mean from
# self.derivative_resolution days ago
if len(self.cached_means) < self.derivative_resolution + 1:
old_mean = self.cached_means[0]
else:
old_mean = self.cached_means[-self.derivative_resolution]
diff = self.cached_means[-1] - old_mean
return diff
def calculate_means(self):
#
if len(self.cached_prices) == 0:
self.cached_means.append(0)
else:
relevant_prices = []
for day_prices in self.cached_prices[max(-len(self.cached_prices), -1):]:
for price in day_prices:
relevant_prices.append(price)
prices = np.array([x[1] for x in relevant_prices])
quantities = np.abs(np.array([x[0] for x in relevant_prices]))
self.cached_means.append(np.average(prices, weights=quantities))
def cache_purchased_prices(self, state: TradingState) -> None:
# Caches prices of bought and sold products
market_trades = state.market_trades
own_trades = state.own_trades
prod_trades: List[Trade] = own_trades.get(self.name, []) + market_trades.get(self.name, [])
if len(prod_trades) > 0:
prices = [(trade.quantity, trade.price) for trade in prod_trades]
self.cached_prices.append(prices)
class FixedStrategy(Strategy):
def __init__(self, name: str, max_pos: int):
super().__init__(name, max_pos)
self.pearls_price = 10000
self.pearls_diff = 4
def trade(self, trading_state: TradingState, orders: list):
order_depth: OrderDepth = trading_state.order_depths[self.name]
# Check if there are any SELL orders
if len(order_depth.sell_orders) > 0:
#
# self.cache_prices(order_depth)
# Sort all the available sell orders by their price
best_asks = sorted(order_depth.sell_orders.keys())
# Check if the lowest ask (sell order) is lower than the above defined fair value
i = 0
while i < self.trade_count and best_asks[i] < self.pearls_price:
# Fill ith ask order if it's below the acceptable
if self.prod_position == self.max_pos:
break
self.buy_product(best_asks, i, order_depth, orders)
i += 1
if len(order_depth.buy_orders) != 0:
best_bids = sorted(order_depth.buy_orders.keys(), reverse=True)
i = 0
while i < self.trade_count and best_bids[i] > self.pearls_price:
if self.prod_position == -self.max_pos:
break
self.sell_product(best_bids, i, order_depth, orders)
i += 1
class FixedStrategy2(Strategy):
def __init__(self, name: str, max_pos: int):
super().__init__(name, max_pos)
self.amethysts_price = 10000
def trade(self, trading_state: TradingState, orders: list):
order_depth: OrderDepth = trading_state.order_depths[self.name]
# Check if there are any SELL orders
bid_volume = self.max_pos - self.prod_position
ask_volume = -self.max_pos - self.prod_position
orders.append(Order(self.name, self.amethysts_price - 1, bid_volume))
orders.append(Order(self.name, self.amethysts_price + 1, ask_volume))
class ObservationStrategy(Strategy):
def __init__(self, name: str, max_position: int):
super().__init__(name, max_position)
self.cost = 0
self.gear_timestamp_diff = 70000
self.max_pos = max_position
self.bidPrice = None
self.askPrice = None
self.transportFees = None
self.exportTariff = None
self.importTariff = None
self.sunlight = None
self.humidity = None
self.sunlight_average = 2100
self.ema_param = 0.5
self.humidity_out = None
self.sunlight_out = None
def handle_observations(self, trading_state: TradingState):
obs = trading_state.observations.conversionObservations[self.name]
self.bidPrice = obs.bidPrice
self.askPrice = obs.askPrice
self.transportFees = obs.transportFees
self.exportTariff = obs.exportTariff
self.importTariff = obs.importTariff
self.sunlight = obs.sunlight
self.humidity = obs.humidity
self.humidity_effect_on_production = 0
self.humidity_out_timestamp = trading_state.timestamp
if self.humidity > 80 or self.humidity < 60:
self.humidity_out = True
else:
self.humidity_out = False
if self.sunlight < 2500:
self.sunlight_out = True
else:
self.sunlight_out = False
if self.humidity < 60 or self.humidity > 80:
self.humidity_out = True
if self.humidity > 80:
self.humidity_effect_on_production = int((80 - self.humidity) /5)
elif self.humidity < 60:
self.humidity_effect_on_production = int((self.humidity - 80) /5)
# calculate ema of sunlight
if self.sunlight_average == 0:
self.sunlight_average = self.sunlight
self.sunlight = self.sunlight * self.ema_param + self.sunlight_average * (1 - self.ema_param)
def trade(self, trading_state: TradingState, orders: list):
order_list =[]
self.handle_observations(trading_state)
self.update_cost(trading_state)
order_depth: OrderDepth = trading_state.order_depths[self.name]
if self.askPrice == self.bidPrice:
return
remote_bid = round(self.bidPrice)
remote_ask = round(self.askPrice)
# Using the remote bid and remote ask, we can arbitrage between the two markets without having to exhange between the two
# If any local bid is higher than remote market, sell in local
for i, local_bid in enumerate(order_depth.buy_orders):
if local_bid >= remote_bid:
order_list.append(Order(self.name, local_bid, -order_depth.buy_orders[local_bid]))
# If the local ask is lower than the remote market, buy in local
for i, local_ask in enumerate(order_depth.sell_orders):
if local_ask <= remote_ask:
order_list.append(Order(self.name, local_ask, order_depth.sell_orders[local_ask]))
orders.extend(order_list)
def conversion(self, trading_state, position) -> int:
'''
get the number of conversion for this round
'''
remote_bid = round(self.bidPrice - self.importTariff - self.transportFees)
remote_ask = round(self.askPrice + self.exportTariff + self.transportFees)
order_depth = trading_state.order_depths[self.name]
buy_sell=0
# conversions only allow us to sell in remote
# if the local bid is lower than the remote market, buy in remote
for i, local_bid in enumerate(order_depth.buy_orders):
if local_bid >= remote_bid:
buy_sell -= order_depth.buy_orders[local_bid]
# If the local ask is higher than the remote market, sell in remote
for i, local_ask in enumerate(order_depth.sell_orders):
if local_ask <= remote_ask:
buy_sell += order_depth.sell_orders[local_ask]
# if any remote ask is lower than local bid, sell in remote
for i, local_bid in enumerate(order_depth.buy_orders):
if local_bid >= remote_bid:
buy_sell += order_depth.buy_orders[local_bid]
# if any remote bid is higher than local ask, buy in remote
for i, local_ask in enumerate(order_depth.sell_orders):
if local_ask <= remote_ask:
buy_sell -= order_depth.sell_orders[local_ask]
# if there is remote ask that is higher than local ask, sell in remote
for i, local_ask in enumerate(order_depth.sell_orders):
if local_ask <= remote_ask:
buy_sell += order_depth.sell_orders[local_ask]
# finally, if there is remote bid that is lower than local bid, buy in remote
for i, local_bid in enumerate(order_depth.buy_orders):
if local_bid >= remote_bid:
buy_sell -= order_depth.buy_orders[local_bid]
return buy_sell
def update_cost(self, trading_state: TradingState):
'''
update the cost of the current
'''
if self.name not in trading_state.market_trades:
return
market_trades = trading_state.market_trades[self.name]
for trade in market_trades:
if trade.buyer == "SUBMISSION":
self.cost += trade.price * trade.quantity + 0.1 * trade.quantity
else:
self.cost -= trade.price * trade.quantity
class TimeBasedStrategy(CrossStrategy):
def __init__(self, name, min_req_price_difference, max_position):
super().__init__(name, min_req_price_difference, max_position)
self.berries_ripe_timestamp = 350000
self.berries_peak_timestamp = 500000
self.berries_sour_timestamp = 650000
def trade(self, trading_state: TradingState, orders: list):
order_depth = trading_state.order_depths[self.name]
if 0 < trading_state.timestamp - self.berries_ripe_timestamp < 5000:
# print("BERRIES ALMOST RIPE")
# start buying berries if they start being ripe
if len(order_depth.sell_orders) != 0:
best_asks = sorted(order_depth.sell_orders.keys())
i = 0
while i < self.trade_count and len(best_asks) > i:
if self.prod_position == -self.max_pos:
break
self.buy_product(best_asks, i, order_depth, orders)
i += 1
elif 0 < trading_state.timestamp - self.berries_peak_timestamp < 5000:
# print("BERRIES READY TO SELL")
self.continuous_sell(order_depth, orders)
else:
super().trade(trading_state, orders)
class ArbitrageStrategy(Strategy):
def __init__(self, name, min_req_price_difference: int, max_position: dict, zscore_threshold: float):
super().__init__(name, max_position)
self.min_price_diff = min_req_price_difference
self.max_pos = max_position
self.orders = []
self.products = ["CHOCOLATE", "STRAWBERRIES", "ROSES", "GIFT_BASKET"]
self.coeffs = {}
self.coeffs["GIFT_BASKET"] = [ 0.99637084, 8.54381396, -0.161608, 0.02234559, -0.03371232, 0.21668808, -0.21632859, 0.04613577, -0.02076174, 0.03116055, -0.03263618, 0.04016784, -0.02797431]
self.coeffs["CHOCOLATE"] = [-0.00437733, 0.00308218, 0.01752576, 0.98360442, -0.90183322, -2.79369535, 0.02711808, -0.00315843, 0.11274011, -0.11258077]
self.coeffs["ROSES"] = [-0.00981411, 0.00393729, 0.01444269, 0.99055514, -0.0615577, -0.3335764, 0.03956394, -0.04242976, -0.07749774, 0.07836905]
self.coeffs["STRAWBERRIES"] = [-0.01862957, 0.0360459 , 0.11510304, 0.86723537, -0.04803083, -1.15100102, -0.00741988, -0.02239479, -0.00789983, 0.0081571 ]
self.fair_market_prices = {}
for product in self.products:
self.fair_market_prices[product] = 0
self.midprices = {}
for product in self.products:
self.midprices[product] = []
self.estimated_values = {}
for product in self.products:
self.estimated_values[product] = []
self.intercepts = {}
for product in self.products:
self.intercepts[product] = 0
self.imbalances = {}
for product in self.products:
self.imbalances[product] = []
self.vwaps = {}
for product in self.products:
self.vwaps[product] = []
self.spreads = {}
for product in self.products:
self.spreads[product] = []
self.buy_volume = {}
for product in self.products:
self.buy_volume[product] = 0
self.sell_volume = {}
for product in self.products:
self.sell_volume[product] = 0
self.timestamp = 0
self.midprice_diff = []
self.z_score = []
self.zscore_threshold = zscore_threshold
def trade(self, trading_state: TradingState, orders: list):
self.timestamp = trading_state.timestamp
self.prod_position = trading_state.position.get(self.name, 0)
# calculate the estimated value of each product, including basket
for product in self.products:
order_depth = trading_state.order_depths[product]
# calculate the variables needed for our linear regression
# 'mid_price_3','mid_price_2','mid_price_1','mid_price','imbalance_1','imbalance','spread_1','spread','vwap_1','vwap'
self.midprices[product].append(self.calculate_mid_price(order_depth))
if len(self.midprices[product]) > 4:
self.midprices[product].pop(0)
self.imbalances[product].append(self.calculate_imbalance(order_depth, product))
if len(self.imbalances[product]) > 2:
self.imbalances[product].pop(0)
self.spreads[product].append(self.calculate_spread(order_depth))
if len(self.spreads[product]) > 2:
self.spreads[product].pop(0)
self.vwaps[product].append(self.calculate_vwap(trading_state, product))
if len(self.vwaps[product]) > 2:
self.vwaps[product].pop(0)
if product != "GIFT_BASKET":
self.estimated_values[product].append(self.calculate_fair_market_price(product))
if len(self.estimated_values[product]) > 2:
self.estimated_values[product].pop(0)
if self.timestamp < 200:
return
# first we find out the underlying value of the securities
underlying_value = self.calculate_basket_underlying_price()
fair_value_of_basket = self.calculate_fair_market_price_basket()
self.midprice_diff.append(underlying_value - fair_value_of_basket)
current_z_score = (self.midprice_diff[-1] - np.mean(self.midprice_diff)) / np.std(self.midprice_diff)
if len(self.midprice_diff) > 25:
self.midprice_diff.pop(0)
self.z_score.append(current_z_score)
if len(self.z_score) < 2:
return
if len(self.z_score) > 2:
self.z_score.pop(0)
long_signal = (current_z_score < -self.zscore_threshold) and (self.z_score[-2] > -self.zscore_threshold)
long_exit = (current_z_score > -self.zscore_threshold) and (self.z_score[-2] < -self.zscore_threshold)
short_signal = (current_z_score > self.zscore_threshold) and (self.z_score[-2] < self.zscore_threshold)
short_exit = (current_z_score < self.zscore_threshold) and (self.z_score[-2] > self.zscore_threshold)
for product in self.products:
if long_signal:
if product == "GIFT_BASKET":
for price, vol in order_depth.sell_orders.items():
if price < fair_value_of_basket + self.min_price_diff:
self.buy_volume["GIFT_BASKET"] += vol
if self.buy_volume["GIFT_BASKET"] > self.max_pos["GIFT_BASKET"]:
vol = self.buy_volume["GIFT_BASKET"] - self.max_pos["GIFT_BASKET"]
self.orders.append(Order(self.name, price, vol))
break
self.orders.append(Order(self.name, price, vol))
else:
order_depth = trading_state.order_depths[product]
for price, vol in order_depth.buy_orders.items():
if price < self.estimated_values[product][-1] + self.min_price_diff:
self.sell_volume[product] += vol
if self.sell_volume[product] > self.max_pos[product]:
vol = self.sell_volume[product] - self.max_pos[product]
self.orders.append(Order(self.name, price, -vol))
break
self.orders.append(Order(self.name, price, -vol))
elif short_signal:
if product == "GIFT_BASKET":
for price, vol in order_depth.buy_orders.items():
if price > fair_value_of_basket - self.min_price_diff:
self.sell_volume["GIFT_BASKET"] += vol
if self.sell_volume["GIFT_BASKET"] > self.max_pos["GIFT_BASKET"]:
vol = self.sell_volume["GIFT_BASKET"] - self.max_pos["GIFT_BASKET"]
self.orders.append(Order(self.name, price, -vol))
break
self.orders.append(Order(self.name, price, -vol))
else:
order_depth = trading_state.order_depths[product]
for price, vol in order_depth.sell_orders.items():
if price > self.estimated_values[product][-1] - self.min_price_diff:
self.buy_volume[product] += vol
if self.buy_volume[product] > self.max_pos[product]:
vol = self.buy_volume[product] - self.max_pos[product]
self.orders.append(Order(self.name, price, vol))
break
self.orders.append(Order(self.name, price, vol))
elif long_exit:
if product == "GIFT_BASKET":
for price, vol in order_depth.sell_orders.items():
if price < fair_value_of_basket + self.min_price_diff:
self.buy_volume["GIFT_BASKET"] -= vol
self.orders.append(Order(self.name, price, -vol))
else:
order_depth = trading_state.order_depths[product]
for price, vol in order_depth.buy_orders.items():
if price < self.estimated_values[product][-1] + self.min_price_diff:
self.sell_volume[product] -= vol
self.orders.append(Order(self.name, price, vol))
elif short_exit:
if product == "GIFT_BASKET":
for price, vol in order_depth.buy_orders.items():
if price > fair_value_of_basket - self.min_price_diff:
self.sell_volume["GIFT_BASKET"] -= vol
self.orders.append(Order(self.name, price, vol))
else:
order_depth = trading_state.order_depths[product]
for price, vol in order_depth.sell_orders.items():
if price > self.estimated_values[product][-1] - self.min_price_diff:
self.buy_volume[product] -= vol
self.orders.append(Order(self.name, price, -vol))
def tradersData(self, trading_state: TradingState):
'''
This function will return the traders data
'''
return self.z_score
def orders(self):
return self.orders
def calculate_fair_market_price(self, product: str):
'''
This is where we will do the linear regression for the baskets.
For now, it just returns the midpoint
'''
if self.timestamp < 200:
return self.midprices[product][-1]
intercept = self.intercepts[product]
coeff = self.coeffs[product]
if len(self.midprices[product]) != 4 or len(self.imbalances[product]) != 2 or len(self.spreads[product]) != 2 or len(self.vwaps[product]) != 2:
return self.midprices[product][-1]
features = []
# ['mid_price_3','mid_price_2','mid_price_1','mid_price','imbalance_1','imbalance','spread_1','spread','vwap_1','vwap']
for midprice in self.midprices[product][-4:]:
features.append(midprice)
for imbalance in self.imbalances[product][-2:]:
features.append(imbalance)
for spread in self.spreads[product][-2:]:
features.append(spread)
for vwap in self.vwaps[product][-2:]:
features.append(vwap)
# Calculate fair price
fair_price = sum(np.multiply(features,coeff)) + intercept
return int(fair_price)
def calculate_fair_market_price_basket(self) -> int:
# if we don't have enough data, just return midprice
if self.timestamp < 200:
return self.midprices["GIFT_BASKET"][-1]
coeff = self.coeffs["GIFT_BASKET"]
intercept = 0
features = []
# ['mid_price', 'imbalance', 'imbalance_1','spread', 'spread_1', 'vwap', 'vwap_1', 'chocolate_predicted_price', 'chocolate_predicted_price_1', 'strawberry_predicted_price', 'strawberry_predicted_price_1', 'roses_predicted_price_1', 'roses_predicted_price', ]
features = [self.midprices["GIFT_BASKET"][-1]]
for imbalance in self.imbalances["GIFT_BASKET"][-2:]:
features.append(imbalance)
for spread in self.spreads["GIFT_BASKET"][-2:]:
features.append(spread)
for vwap in self.vwaps["GIFT_BASKET"][-2:]:
features.append(vwap)
for estimated_value in self.estimated_values["CHOCOLATE"][-2:]:
features.append(estimated_value)
for estimated_value in self.estimated_values["STRAWBERRIES"][-2:]:
features.append(estimated_value)
for estimated_value in self.estimated_values["ROSES"][-2:]:
features.append(estimated_value)
# Calculate fair price
fair_price = sum(np.multiply(features,coeff)) + intercept
return int(fair_price)
def calculate_mid_price(self, order_depth: OrderDepth) -> float:
market_bids = order_depth.buy_orders
market_asks = order_depth.sell_orders
best_bid = max(market_bids)
best_ask = min(market_asks)
return (best_bid + best_ask)/2
def calculate_imbalance(self, order_depth: OrderDepth, product: str) -> float:
# Calculate the imbalance for the last days
bid_vol = sum(order_depth.buy_orders.values())
ask_vol = sum(order_depth.sell_orders.values())
if bid_vol + ask_vol == 0:
return 0
imbalance = (bid_vol + ask_vol)/ (bid_vol - ask_vol)
return imbalance
def calculate_vwap(self, state : TradingState, product: str):
"""
Volume-Weighted Average Price
calculate from all the trades happened from last iteration
"""
total_value = 0
total_volume = 0
# when there is not trad in the beginning
if product not in state.market_trades:
if self.vwaps[product] == []:
return self.midprices[product][-1]
else:
return self.vwaps[product][-1]
market_trades = state.market_trades[product]
for trade in market_trades:
total_value += trade.price * trade.quantity
total_volume += trade.quantity
# Ensure we don't divide by zero in case of no trades
if total_volume != 0:
vwap = total_value / total_volume
return vwap
else:
return self.vwaps[product][-1]
def calculate_spread(self, order_depth: OrderDepth) -> float:
market_bids = order_depth.buy_orders
market_asks = order_depth.sell_orders
best_bid = max(market_bids)
best_ask = min(market_asks)
return best_ask - best_bid
def calculate_basket_underlying_price(self):
'''
Calculate the real underlying price of the basket by calculating the value of the underlying assets:
4 chocolates, 6 strawberries & 1 rose
'''
strawberry_fair_price = self.estimated_values["STRAWBERRIES"][-1]
chocolate_fair_price = self.estimated_values["CHOCOLATE"][-1]
roses_fair_price = self.estimated_values["ROSES"][-1]
return 4 * chocolate_fair_price + 6 * strawberry_fair_price + roses_fair_price
##############################################################################################
### RegressionStrategy, using regression to find the best fair price
##############################################################################################
class RegressionStrategy(Strategy):
def __init__(self, name: str, min_req_price_difference: int, max_position: int, intercept, coef):
super().__init__(name, max_position)
self.prices = []
self.imbalances = []
self.vwaps = []
self.midprice_ema10 = []
self.spreads = []
self.strategy_start_day = 4
# New params
self.strategy_window = 10
# New strat
self.orderbook_imbalance_delta = []
self.retreat_parameter = 0.1
self.fair_price = None
self.old_asks = []
self.old_bids = []
self.min_req_price_difference = min_req_price_difference
self.intercept = intercept
self.coef = coef
self.mm = StoikovMarketMaker(0.23348603634235995, 1.966874725882954, 0, 20)
def trade(self, trading_state: TradingState, orders: list):
order_depth: OrderDepth = trading_state.order_depths[self.name]
self.cache_features(trading_state)
if len(self.prices) < self.strategy_start_day:
return
if len(self.prices) == self.strategy_start_day:
fair_price = self.calculate_fair_price()
avg_bid, avg_ask = fair_price - 2, fair_price + 2
else:
avg_bid, avg_ask = self.calculate_prices(self.strategy_start_day)
# self.mm.update_inventory(self.prod_position)
# avg_bid, avg_ask = self.mm.calculate_quotes(avg_bid,avg_ask)
orders.extend(self.compute_orders_regression(order_depth, avg_bid, avg_ask))
# if len(order_depth.sell_orders) != 0:
# best_asks = sorted(order_depth.sell_orders.keys())
# i = 0
# while i < self.trade_count and len(best_asks) > i and best_asks[i] - bid_quote <= self.min_req_price_difference:
# if self.prod_position == self.max_pos:
# break
# self.buy_product(best_asks, i, order_depth, orders)
# i += 1
# if len(order_depth.buy_orders) != 0:
# # Sort all the available buy orders by their price
# best_bids = sorted(order_depth.buy_orders.keys(), reverse=True)
# i = 0
# # Check if the lowest bid (buy order) is lower than the above defined fair value
# while i < self.trade_count and len(best_bids) > i and ask_quote - best_bids[i] <= self.min_req_price_difference:
# if self.prod_position == -self.max_pos:
# break
# self.sell_product(best_bids, i, order_depth, orders)
# i += 1
def cache_features(self, trading_state):
"""
update features for the regression
"""
order_depth: OrderDepth = trading_state.order_depths[self.name]
sell_orders = order_depth.sell_orders
buy_orders = order_depth.buy_orders
if len(self.old_asks) == self.strategy_start_day:
self.old_asks.pop(0)
if len(self.old_bids) == self.strategy_start_day:
self.old_bids.pop(0)
self.old_asks.append(sell_orders)
self.old_bids.append(buy_orders)
# mid_prices t-3 to t
if len(self.prices) == self.strategy_start_day:
self.prices.pop(0)
mid_price = self.calculate_mid_price(order_depth)
self.prices.append(mid_price)
# order imbalance t-1 to t
if len(self.imbalances) == 2:
self.imbalances.pop(0)
imbalance = self.calculate_imbalance(order_depth)
self.imbalances.append(imbalance)
# order spreads t-1 to t
if len(self.spreads) == 2:
self.spreads.pop(0)
spread = self.calculate_spread(order_depth)
self.spreads.append(spread)
# order vwaps t-1 to t
if len(self.vwaps) == 2:
self.vwaps.pop(0)
vwap = self.calculate_vwap(trading_state)
self.vwaps.append(vwap)
def calculate_fair_price(self) -> float:
"""
Calculate fair price using linear regression
"""
features = self.prices + self.imbalances + self.spreads + self.vwaps
# self.logger.log(features)
# ema_10 = np.mean(self.old_asks[-10:])
# Calculate fair price
fair_price = sum(np.multiply(features,self.coef)) + self.intercept
return round(fair_price)
def calculate_prices(self, days: int) -> Tuple[int, int]:
# Calculate the average bid and ask price for the last days
relevant_bids = []
for bids in self.old_bids[-days:]:
relevant_bids.extend([(value, bids[value]) for value in bids])
relevant_asks = []
for asks in self.old_asks[-days:]:
relevant_asks.extend([(value, asks[value]) for value in asks])
avg_bid = np.average([x[0] for x in relevant_bids], weights=[x[1] for x in relevant_bids])
avg_ask = np.average([x[0] for x in relevant_asks], weights=[x[1] for x in relevant_asks])
return avg_bid, avg_ask
def calculate_retreat(self, order_depth: OrderDepth, state: TradingState) -> float:
return min(max(state.position[self.name], self.max_pos), -self.min_pos) * self.retreat_parameter
def calculate_own_trades_imbalance(self, state: TradingState) -> float:
# Calculate our own trades' imbalance
own_trades = state.past_own_trades.get(self.name, [])
buy_volume = 0
sell_volume = 0
for trade in own_trades:
if trade.quantity > 0:
buy_volume += trade.quantity
else:
sell_volume += trade.quantity
return buy_volume - sell_volume
def calculate_orderbook_imbalance_delta(self, order_depth: OrderDepth) -> None:
# calculate the change in the orderbook imbalance
if len(self.orderbook_imbalance) < self.strategy_start_day:
return 0
current_orderbook_imbalance = self.calculate_current_orderbook_imbalance(order_depth)
oi_delta = current_orderbook_imbalance - self.orderbook_imbalance[-1]