forked from robcarver17/pysystemtrade
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdynamic_optimised_positions.py
676 lines (537 loc) · 21.8 KB
/
dynamic_optimised_positions.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
"""
Strategy specific execution code
For dynamic optimised position we
These are 'virtual' orders, because they are per instrument. We translate that to actual contracts downstream
Desired virtual orders have to be labelled with the desired type: limit, market,best-execution
"""
from dataclasses import dataclass
from syscore.objects import missing_data
from sysdata.data_blob import dataBlob
from sysexecution.orders.instrument_orders import instrumentOrder, best_order_type
from sysexecution.orders.list_of_orders import listOfOrders
from sysexecution.strategies.strategy_order_handling import orderGeneratorForStrategy
from sysobjects.production.tradeable_object import instrumentStrategy
from sysobjects.production.optimal_positions import (
optimalPositionWithDynamicCalculations,
)
from sysobjects.production.override import (
Override,
CLOSE_OVERRIDE,
NO_TRADE_OVERRIDE,
REDUCE_ONLY_OVERRIDE,
)
from sysproduction.data.controls import dataPositionLimits
from sysproduction.data.positions import dataOptimalPositions
from sysproduction.data.controls import diagOverrides
from sysproduction.reporting.data.risk_metrics import (
get_perc_of_strategy_capital_for_instrument_per_contract,
capital_for_strategy,
get_covariance_matrix_for_instrument_returns,
)
from sysproduction.reporting.data.costs import get_cash_cost_in_base_for_instrument
from sysquant.estimators.covariance import covarianceEstimate
from sysquant.estimators.mean_estimator import meanEstimates
from sysquant.optimisation.weights import portfolioWeights
from systems.provided.dynamic_small_system_optimise.optimisation import (
objectiveFunctionForGreedy,
constraintsForDynamicOpt,
)
from systems.provided.dynamic_small_system_optimise.buffering import (
speedControlForDynamicOpt,
)
class orderGeneratorForDynamicPositions(orderGeneratorForStrategy):
def get_required_orders(self) -> listOfOrders:
strategy_name = self.strategy_name
optimised_positions_data = (
self.calculate_write_and_return_optimised_positions_data()
)
current_positions = self.get_actual_positions_for_strategy()
list_of_trades = list_of_trades_given_optimised_and_actual_positions(
self.data,
strategy_name=strategy_name,
optimised_positions_data=optimised_positions_data,
current_positions=current_positions,
)
return list_of_trades
def calculate_write_and_return_optimised_positions_data(self) -> dict:
## We bring in
previous_positions = self.get_actual_positions_for_strategy()
raw_optimal_position_data = self.get_raw_optimal_position_data()
data = self.data
strategy_name = self.strategy_name
optimised_positions_data = calculate_optimised_positions_data(
data,
strategy_name=strategy_name,
previous_positions=previous_positions,
raw_optimal_position_data=raw_optimal_position_data,
)
self.write_optimised_positions_data(optimised_positions_data)
return optimised_positions_data
def get_raw_optimal_position_data(self) -> dict:
# This is the 'raw' data, positions pre-optimisation
# dict of optimalPositionWithReference
data = self.data
strategy_name = self.strategy_name
optimal_position_data = dataOptimalPositions(data)
list_of_instruments = optimal_position_data.get_list_of_instruments_for_strategy_with_optimal_position(
strategy_name, raw_positions=True
)
list_of_instrument_strategies = [
instrumentStrategy(
strategy_name=strategy_name, instrument_code=instrument_code
)
for instrument_code in list_of_instruments
]
raw_optimal_positions = dict(
[
(
instrument_strategy.instrument_code,
optimal_position_data.get_current_optimal_position_for_instrument_strategy(
instrument_strategy, raw_positions=True
),
)
for instrument_strategy in list_of_instrument_strategies
]
)
return raw_optimal_positions
def write_optimised_positions_data(self, optimised_positions_data: dict):
write_optimised_positions_data(
self.data,
strategy_name=self.strategy_name,
optimised_positions_data=optimised_positions_data,
)
def calculate_optimised_positions_data(
data: dataBlob,
previous_positions: dict,
strategy_name: str,
raw_optimal_position_data: dict,
) -> dict:
data_for_objective = get_data_for_objective_instance(
data,
strategy_name=strategy_name,
previous_positions=previous_positions,
raw_optimal_position_data=raw_optimal_position_data,
)
objective_function = get_objective_instance(
data=data, data_for_objective=data_for_objective
)
optimised_positions_data = get_optimised_positions_data_dict_given_optimisation(
data_for_objective=data_for_objective, objective_function=objective_function
)
return optimised_positions_data
@dataclass
class dataForObjectiveInstance:
positions_optimal: portfolioWeights
covariance_matrix: covarianceEstimate
per_contract_value: portfolioWeights
costs: meanEstimates
reference_prices: dict
reference_contracts: dict
reference_dates: dict
previous_positions: portfolioWeights
maximum_position_contracts: portfolioWeights
constraints: constraintsForDynamicOpt
speed_control: speedControlForDynamicOpt
constraints: constraintsForDynamicOpt
@property
def weights_prior(self) -> portfolioWeights:
return get_weights_given_positions(
self.previous_positions, self.per_contract_value
)
@property
def maximum_position_weights(self) -> portfolioWeights:
return get_weights_given_positions(
self.previous_positions, self.per_contract_value
)
@property
def weights_optimal(self) -> portfolioWeights:
return get_weights_given_positions(
self.positions_optimal, self.per_contract_value
)
def get_data_for_objective_instance(
data: dataBlob,
strategy_name: str,
previous_positions: dict,
raw_optimal_position_data: dict,
) -> dataForObjectiveInstance:
list_of_instruments = list(raw_optimal_position_data.keys())
data.log.msg("Getting data for optimisation")
previous_positions_as_weights_object = portfolioWeights(previous_positions)
previous_positions_as_weights_object = (
previous_positions_as_weights_object.with_zero_weights_for_missing_keys(
list_of_instruments
)
)
positions_optimal = portfolioWeights(
[
(instrument_code, raw_position_entry.optimal_position)
for instrument_code, raw_position_entry in raw_optimal_position_data.items()
]
)
reference_prices = dict(
[
(instrument_code, raw_position_entry.reference_price)
for instrument_code, raw_position_entry in raw_optimal_position_data.items()
]
)
reference_contracts = dict(
[
(instrument_code, raw_position_entry.reference_contract)
for instrument_code, raw_position_entry in raw_optimal_position_data.items()
]
)
reference_dates = dict(
[
(instrument_code, raw_position_entry.reference_date)
for instrument_code, raw_position_entry in raw_optimal_position_data.items()
]
)
data.log.msg("Getting maximum positions")
maximum_position_contracts = get_maximum_position_contracts(
data,
strategy_name=strategy_name,
previous_positions=previous_positions_as_weights_object,
list_of_instruments=list_of_instruments,
)
data.log.msg("Getting covariance matrix")
covariance_matrix = get_covariance_matrix_for_instrument_returns(
data, list_of_instruments=list_of_instruments
)
data.log.msg("Getting per contract values")
per_contract_value = get_per_contract_values(
data, strategy_name=strategy_name, list_of_instruments=list_of_instruments
)
data.log.msg("Getting costs")
costs = calculate_costs_per_portfolio_weight(
data, strategy_name=strategy_name, list_of_instruments=list_of_instruments
)
constraints = get_constraints(
data, strategy_name=strategy_name, list_of_instruments=list_of_instruments
)
speed_control = get_speed_control(data)
data_for_objective = dataForObjectiveInstance(
positions_optimal=positions_optimal,
per_contract_value=per_contract_value,
covariance_matrix=covariance_matrix,
costs=costs,
reference_dates=reference_dates,
reference_prices=reference_prices,
reference_contracts=reference_contracts,
previous_positions=previous_positions_as_weights_object,
maximum_position_contracts=maximum_position_contracts,
constraints=constraints,
speed_control=speed_control,
)
return data_for_objective
def get_maximum_position_contracts(
data, strategy_name: str, previous_positions: dict, list_of_instruments: list
) -> portfolioWeights:
maximum_position_contracts = dict(
[
(
instrument_code,
get_maximum_position_contracts_for_instrument_strategy(
data,
instrument_strategy=instrumentStrategy(
strategy_name=strategy_name, instrument_code=instrument_code
),
previous_position=previous_positions.get(instrument_code, 0),
),
)
for instrument_code in list_of_instruments
]
)
return portfolioWeights(maximum_position_contracts)
def get_maximum_position_contracts_for_instrument_strategy(
data: dataBlob, instrument_strategy: instrumentStrategy, previous_position: int = 0
) -> int:
override = get_override_for_instrument_strategy(data, instrument_strategy)
if override == CLOSE_OVERRIDE:
return 0
position_limit_data = dataPositionLimits(data)
spare = int(
position_limit_data.get_spare_checking_all_position_limits(instrument_strategy)
)
maximum = int(spare) + abs(previous_position)
return maximum
def get_per_contract_values(
data: dataBlob, strategy_name: str, list_of_instruments: list
) -> portfolioWeights:
per_contract_values = portfolioWeights(
[
(
instrument_code,
get_perc_of_strategy_capital_for_instrument_per_contract(
data, strategy_name=strategy_name, instrument_code=instrument_code
),
)
for instrument_code in list_of_instruments
]
)
return per_contract_values
def calculate_costs_per_portfolio_weight(
data: dataBlob, strategy_name: str, list_of_instruments: list
) -> meanEstimates:
capital = capital_for_strategy(data, strategy_name=strategy_name)
costs = meanEstimates(
[
(
instrument_code,
get_cash_cost_in_base_for_instrument(data, instrument_code) / capital,
)
for instrument_code in list_of_instruments
]
)
return costs
def get_constraints(data, strategy_name: str, list_of_instruments: list):
no_trade_keys = get_no_trade_keys(
data, strategy_name=strategy_name, list_of_instruments=list_of_instruments
)
reduce_only_keys = get_reduce_only_keys(
data, strategy_name=strategy_name, list_of_instruments=list_of_instruments
)
constraints = constraintsForDynamicOpt(
no_trade_keys=no_trade_keys, reduce_only_keys=reduce_only_keys
)
return constraints
def get_no_trade_keys(
data: dataBlob, strategy_name: str, list_of_instruments: list
) -> list:
no_trade_keys = [
instrument_code
for instrument_code in list_of_instruments
if get_override_for_instrument_strategy(
data,
instrument_strategy=instrumentStrategy(
instrument_code=instrument_code, strategy_name=strategy_name
),
)
== NO_TRADE_OVERRIDE
]
return no_trade_keys
def get_reduce_only_keys(
data: dataBlob, strategy_name: str, list_of_instruments: list
) -> list:
no_trade_keys = [
instrument_code
for instrument_code in list_of_instruments
if get_override_for_instrument_strategy(
data,
instrument_strategy=instrumentStrategy(
instrument_code=instrument_code, strategy_name=strategy_name
),
)
== REDUCE_ONLY_OVERRIDE
]
return no_trade_keys
def get_override_for_instrument_strategy(
data: dataBlob, instrument_strategy: instrumentStrategy
) -> Override:
diag_overrides = diagOverrides(data)
override = diag_overrides.get_cumulative_override_for_instrument_strategy(
instrument_strategy
)
return override
def get_speed_control(data):
system_config = get_config_parameters(data)
trade_shadow_cost = system_config.get("shadow_cost", missing_data)
tracking_error_buffer = system_config.get("tracking_error_buffer", missing_data)
if (tracking_error_buffer is missing_data) or (trade_shadow_cost is missing_data):
raise Exception(
"config.small_system doesn't include buffer or shadow cost: you've probably messed up your private_config"
)
data.log.msg("Shadow cost %f" % trade_shadow_cost)
data.log.msg("Tracking error buffer %f" % tracking_error_buffer)
speed_control = speedControlForDynamicOpt(
trade_shadow_cost=trade_shadow_cost, tracking_error_buffer=tracking_error_buffer
)
return speed_control
def get_config_parameters(data: dataBlob) -> dict:
config = data.config
system_config = config.get_element_or_missing_data("small_system")
if system_config is missing_data:
raise Exception(
"Config doesn't include 'small_system' which should be in defaults.yaml"
)
return system_config
def get_objective_instance(
data: dataBlob, data_for_objective: dataForObjectiveInstance
) -> objectiveFunctionForGreedy:
objective_function = objectiveFunctionForGreedy(
log=data.log,
contracts_optimal=data_for_objective.positions_optimal,
covariance_matrix=data_for_objective.covariance_matrix,
costs=data_for_objective.costs,
speed_control=data_for_objective.speed_control,
previous_positions=data_for_objective.previous_positions,
constraints=data_for_objective.constraints,
maximum_positions=data_for_objective.maximum_position_contracts,
per_contract_value=data_for_objective.per_contract_value,
)
return objective_function
def get_optimised_positions_data_dict_given_optimisation(
data_for_objective: dataForObjectiveInstance,
objective_function: objectiveFunctionForGreedy,
) -> dict:
optimised_positions = objective_function.optimise_positions()
optimised_positions = optimised_positions.replace_weights_with_ints()
optimised_position_weights = get_weights_given_positions(
optimised_positions, per_contract_value=data_for_objective.per_contract_value
)
instrument_list = list(optimised_position_weights.keys())
minima_weights = portfolioWeights.from_weights_and_keys(
list_of_keys=instrument_list,
list_of_weights=list(objective_function.minima_as_np),
)
maxima_weights = portfolioWeights.from_weights_and_keys(
list_of_keys=instrument_list,
list_of_weights=list(objective_function.maxima_as_np),
)
starting_weights = portfolioWeights.from_weights_and_keys(
list_of_keys=instrument_list,
list_of_weights=list(objective_function.starting_weights_as_np),
)
data_dict = dict(
[
(
instrument_code,
get_optimal_position_entry_with_calcs_for_code(
instrument_code=instrument_code,
data_for_objective=data_for_objective,
optimised_position_weights=optimised_position_weights,
optimised_positions=optimised_positions,
maxima_weights=maxima_weights,
starting_weights=starting_weights,
minima_weights=minima_weights,
),
)
for instrument_code in instrument_list
]
)
return data_dict
def get_positions_given_weights(
weights: portfolioWeights, per_contract_value: portfolioWeights
) -> portfolioWeights:
positions = weights / per_contract_value
positions = positions.replace_weights_with_ints()
return positions
def get_weights_given_positions(
positions: portfolioWeights, per_contract_value: portfolioWeights
) -> portfolioWeights:
weights = positions * per_contract_value
return weights
def get_optimal_position_entry_with_calcs_for_code(
instrument_code: str,
data_for_objective: dataForObjectiveInstance,
optimised_position_weights: portfolioWeights,
optimised_positions: portfolioWeights,
minima_weights: portfolioWeights,
maxima_weights: portfolioWeights,
starting_weights: portfolioWeights,
) -> optimalPositionWithDynamicCalculations:
return optimalPositionWithDynamicCalculations(
dict(
reference_price=data_for_objective.reference_prices[instrument_code],
reference_contract=data_for_objective.reference_contracts[instrument_code],
reference_date=data_for_objective.reference_dates[instrument_code],
optimal_position=data_for_objective.positions_optimal[instrument_code],
weight_per_contract=data_for_objective.per_contract_value[instrument_code],
previous_position=data_for_objective.previous_positions[instrument_code],
previous_weight=data_for_objective.weights_prior[instrument_code],
reduce_only=instrument_code
in data_for_objective.constraints.reduce_only_keys,
dont_trade=instrument_code in data_for_objective.constraints.no_trade_keys,
position_limit_contracts=data_for_objective.maximum_position_contracts[
instrument_code
],
position_limit_weight=data_for_objective.maximum_position_weights[
instrument_code
],
optimum_weight=data_for_objective.weights_optimal[instrument_code],
minimum_weight=minima_weights[instrument_code],
maximum_weight=maxima_weights[instrument_code],
start_weight=starting_weights[instrument_code],
optimised_weight=optimised_position_weights[instrument_code],
optimised_position=optimised_positions[instrument_code],
)
)
def write_optimised_positions_data(
data: dataBlob, strategy_name: str, optimised_positions_data: dict
):
for instrument_code, optimised_position_entry in optimised_positions_data.items():
write_optimised_positions_data_for_code(
data,
strategy_name=strategy_name,
instrument_code=instrument_code,
optimised_position_entry=optimised_position_entry,
)
def write_optimised_positions_data_for_code(
data: dataBlob,
strategy_name: str,
instrument_code: str,
optimised_position_entry: optimalPositionWithDynamicCalculations,
):
data_optimal_positions = dataOptimalPositions(data)
instrument_strategy = instrumentStrategy(
instrument_code=instrument_code, strategy_name=strategy_name
)
data.log.msg(
"Adding optimal position for %s: %s"
% (str(instrument_strategy), optimised_position_entry.verbose_repr())
)
data_optimal_positions.update_optimal_position_for_instrument_strategy(
instrument_strategy=instrument_strategy, position_entry=optimised_position_entry
)
def list_of_trades_given_optimised_and_actual_positions(
data: dataBlob,
strategy_name: str,
optimised_positions_data: dict,
current_positions: dict,
) -> listOfOrders:
list_of_instruments = optimised_positions_data.keys()
trade_list = [
trade_given_optimal_and_actual_positions(
data,
strategy_name=strategy_name,
instrument_code=instrument_code,
optimised_position_entry=optimised_positions_data[instrument_code],
current_position=current_positions.get(instrument_code, 0),
)
for instrument_code in list_of_instruments
]
trade_list = listOfOrders(trade_list)
return trade_list
def trade_given_optimal_and_actual_positions(
data: dataBlob,
strategy_name: str,
instrument_code: str,
optimised_position_entry: optimalPositionWithDynamicCalculations,
current_position: int,
) -> instrumentOrder:
optimised_position = optimised_position_entry.optimised_position
trade_required = optimised_position - current_position
reference_contract = optimised_position_entry.reference_contract
reference_price = optimised_position_entry.reference_price
reference_date = optimised_position_entry.reference_date
# No limit orders, just best execution
order_required = instrumentOrder(
strategy_name,
instrument_code,
trade_required,
order_type=best_order_type,
reference_price=reference_price,
reference_contract=reference_contract,
reference_datetime=reference_date,
)
log = order_required.log_with_attributes(data.log)
log.msg(
"Current %d Required position %d Required trade %d Reference price %f for contract %s"
% (
current_position,
optimised_position,
trade_required,
reference_price,
reference_contract,
)
)
return order_required