forked from robcarver17/pysystemtrade
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathforecast_combine.py
executable file
·1537 lines (1219 loc) · 53.3 KB
/
forecast_combine.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 copy import copy
import pandas as pd
from syscore.exceptions import missingData
from systems.forecast_mapping import map_forecast_value
from syscore.genutils import str2Bool, list_difference
from syscore.objects import resolve_function
from syscore.pandas.pdutils import (
dataframe_pad,
from_dict_of_values_to_df,
from_scalar_values_to_ts,
)
from syscore.pandas.frequency import reindex_last_monthly_include_first_date
from syscore.pandas.strategy_functions import (
weights_sum_to_one,
fix_weights_vs_position_or_forecast,
)
from syscore.pandas.list_of_df import listOfDataFrames
from sysdata.config.configdata import Config
from sysquant.estimators.correlations import CorrelationList
from sysquant.optimisation.pre_processing import returnsPreProcessor
from sysquant.returns import (
dictOfReturnsForOptimisationWithCosts,
returnsForOptimisationWithCosts,
)
from sysquant.estimators.turnover import (
turnoverDataAcrossTradingRules,
turnoverDataForTradingRule,
)
from systems.stage import SystemStage
from systems.system_cache import diagnostic, dont_cache, input, output
from systems.forecasting import Rules
from systems.forecast_scale_cap import ForecastScaleCap
from systems.tools.autogroup import (
calculate_autogroup_weights_given_parameters,
config_is_auto_group,
resolve_config_into_parameters_and_weights_for_autogrouping,
)
class ForecastCombine(SystemStage):
"""
Stage for combining forecasts (already capped and scaled)
"""
@property
def name(self):
return "combForecast"
@output()
def get_combined_forecast(self, instrument_code: str) -> pd.Series:
"""
Get a combined forecast, linear combination of individual forecasts
with FDM applied
We forward fill all forecasts. We then adjust forecast weights so that
they are 1.0 in every period; after setting to zero when no forecast
is available. Finally we multiply up, and apply the FDM. Then we cap.
:param instrument_code:
:type str:
:returns: Tx1 pd.DataFrame
KEY OUTPUT
>>> from systems.tests.testdata import get_test_object_futures_with_rules_and_capping
>>> from systems.basesystem import System
>>> (fcs, rules, rawdata, data, config)=get_test_object_futures_with_rules_and_capping()
>>> system=System([rawdata, rules, fcs, ForecastCombineFixed()], data, config)
>>>
>>> system.combForecast.get_combined_forecast("EDOLLAR").tail(2)
comb_forecast
2015-12-10 1.619134
2015-12-11 2.462610
>>>
>>> config.forecast_div_multiplier=1000.0
>>> system2=System([rawdata, rules, fcs, ForecastCombineFixed()], data, config)
>>> system2.combForecast.get_combined_forecast("EDOLLAR").tail(2)
comb_forecast
2015-12-10 21
2015-12-11 21
"""
self.log.debug(
"Calculating combined forecast for %s" % (instrument_code),
instrument_code=instrument_code,
)
raw_multiplied_combined_forecast = (
self.get_raw_combined_forecast_before_mapping(instrument_code)
)
# apply cap and /or any non linear mapping
(
mapping_and_capping_function,
mapping_and_capping_kwargs,
) = self._get_forecast_mapping_function(instrument_code)
combined_forecast = mapping_and_capping_function(
raw_multiplied_combined_forecast, **mapping_and_capping_kwargs
)
return combined_forecast
# FORECAST = AGGREGATE SUM OF FORECASTS * IDM
@diagnostic()
def get_raw_combined_forecast_before_mapping(
self, instrument_code: str
) -> pd.Series:
# sum
raw_combined_forecast = self.get_combined_forecast_without_multiplier(
instrument_code
)
# probably daily frequency
forecast_div_multiplier = self.get_forecast_diversification_multiplier(
instrument_code
)
forecast_div_multiplier = forecast_div_multiplier.reindex(
raw_combined_forecast.index
).ffill()
# apply fdm
raw_multiplied_combined_forecast = (
raw_combined_forecast * forecast_div_multiplier.ffill()
)
return raw_multiplied_combined_forecast
@diagnostic()
def get_combined_forecast_without_multiplier(
self, instrument_code: str
) -> pd.Series:
# We take our list of rule variations from the forecasts, since it
# might be that some rules were omitted in the weight calculation
weighted_forecasts = self.get_weighted_forecasts_without_multiplier(
instrument_code
)
# sum
raw_combined_forecast = weighted_forecasts.sum(axis=1)
return raw_combined_forecast
@diagnostic()
def get_weighted_forecasts_without_multiplier(
self, instrument_code: str
) -> pd.DataFrame:
# We take our list of rule variations from the forecasts, since it
# might be that some rules were omitted in the weight calculation
rule_variation_list = self.get_trading_rule_list(instrument_code)
forecasts = self.get_all_forecasts(instrument_code, rule_variation_list)
smoothed_daily_forecast_weights = self.get_forecast_weights(instrument_code)
smoothed_forecast_weights = smoothed_daily_forecast_weights.reindex(
forecasts.index, method="ffill"
)
weighted_forecasts = smoothed_forecast_weights * forecasts
return weighted_forecasts
# GET FORECAST WEIGHTS ALIGNED TO FORECASTS AND SMOOTHED
@diagnostic()
def get_forecast_weights(self, instrument_code: str) -> pd.DataFrame:
# These will be in daily frequency
daily_forecast_weights_fixed_to_forecasts_unsmoothed = (
self.get_unsmoothed_forecast_weights(instrument_code)
)
# smooth out weights
forecast_smoothing_ewma_span = self.config.forecast_weight_ewma_span
smoothed_daily_forecast_weights = (
daily_forecast_weights_fixed_to_forecasts_unsmoothed.ewm(
span=forecast_smoothing_ewma_span
).mean()
)
# change rows so weights add to one (except for special case where all zeros)
smoothed_normalised_daily_weights = weights_sum_to_one(
smoothed_daily_forecast_weights
)
# still daily
return smoothed_normalised_daily_weights
@diagnostic()
def get_unsmoothed_forecast_weights(self, instrument_code: str):
"""
Get the forecast weights
We forward fill all forecasts. We then adjust forecast weights so that
they are 1.0 in every period; after setting to zero when no forecast
is available.
:param instrument_code:
:type str:
:returns: TxK pd.DataFrame containing weights, columns are trading rule variation names, T covers all
KEY OUTPUT
>>> from systems.tests.testdata import get_test_object_futures_with_rules_and_capping
>>> from systems.basesystem import System
>>> (fcs, rules, rawdata, data, config)=get_test_object_futures_with_rules_and_capping()
>>> system=System([rawdata, rules, fcs, ForecastCombineFixed()], data, config)
>>>
>>> ## from config
>>> system.combForecast.get_forecast_weights("EDOLLAR").tail(2)
ewmac16 ewmac8
2015-12-10 0.5 0.5
2015-12-11 0.5 0.5
>>>
>>> config.forecast_weights=dict(EDOLLAR=dict(ewmac8=0.9, ewmac16=0.1))
>>> system2=System([rawdata, rules, fcs, ForecastCombineFixed()], data, config)
>>> system2.combForecast.get_forecast_weights("EDOLLAR").tail(2)
ewmac16 ewmac8
2015-12-10 0.1 0.9
2015-12-11 0.1 0.9
>>>
>>> del(config.forecast_weights)
>>> system3=System([rawdata, rules, fcs, ForecastCombineFixed()], data, config)
>>> system3.combForecast.get_forecast_weights("EDOLLAR").tail(2)
WARNING: No forecast weights - using equal weights of 0.5000 over all 2 trading rules in system
ewmac16 ewmac8
2015-12-10 0.5 0.5
2015-12-11 0.5 0.5
"""
self.log.debug(
"Calculating forecast weights for %s" % (instrument_code),
instrument_code=instrument_code,
)
# note these might include missing weights, eg too expensive, or absent
# from fixed weights
# These are monthly to save space, or possibly even only 2 rows long
monthly_forecast_weights = self.get_raw_monthly_forecast_weights(
instrument_code
)
# fix to forecast time series
forecast_weights_fixed_to_forecasts = self._fix_weights_to_forecasts(
instrument_code=instrument_code,
monthly_forecast_weights=monthly_forecast_weights,
)
# Remap to business day frequency so the smoothing makes sense also space saver
daily_forecast_weights_fixed_to_forecasts_unsmoothed = (
forecast_weights_fixed_to_forecasts.resample("1B").mean()
)
return daily_forecast_weights_fixed_to_forecasts_unsmoothed
@dont_cache
def _fix_weights_to_forecasts(
self, instrument_code: str, monthly_forecast_weights: pd.DataFrame
) -> pd.DataFrame:
# we get the rule variations from forecast_weight columns, as if we've dropped
# expensive rules (when estimating) then get_trading_rules will give
# the wrong answer
rule_variation_list = list(monthly_forecast_weights.columns)
# time series may vary
forecasts = self.get_all_forecasts(instrument_code, rule_variation_list)
# adjust weights for missing data
# also aligns them together with forecasts
forecast_weights_fixed_to_forecasts = fix_weights_vs_position_or_forecast(
monthly_forecast_weights, forecasts
)
return forecast_weights_fixed_to_forecasts
# GET FORECASTS
@input
def get_all_forecasts(
self, instrument_code: str, rule_variation_list: list = None
) -> pd.DataFrame:
"""
Returns a data frame of forecasts for a particular instrument
KEY INPUT
:param instrument_code:
:type str:
:param rule_variation_list:
:type list: list of str to get forecasts for, if None uses get_trading_rule_list
:returns: TxN pd.DataFrames; columns rule_variation_name
>>> from systems.tests.testdata import get_test_object_futures_with_rules_and_capping
>>> from systems.basesystem import System
>>> (fcs, rules, rawdata, data, config)=get_test_object_futures_with_rules_and_capping()
>>> system1=System([rawdata, rules, fcs, ForecastCombineFixed()], data, config)
>>> system1.combForecast.get_all_forecasts("EDOLLAR",["ewmac8"]).tail(2)
ewmac8
2015-12-10 -0.190583
2015-12-11 0.871231
>>>
>>> system2=System([rawdata, rules, fcs, ForecastCombineFixed()], data, config)
>>> system2.combForecast.get_all_forecasts("EDOLLAR").tail(2)
ewmac16 ewmac8
2015-12-10 3.134462 -0.190583
2015-12-11 3.606243 0.871231
"""
if rule_variation_list is None:
rule_variation_list = self.get_trading_rule_list(instrument_code)
forecasts = self.get_forecasts_given_rule_list(
instrument_code, rule_variation_list
)
return forecasts
@dont_cache
def get_trading_rule_list(self, instrument_code: str) -> list:
"""
Get list of trading rules
We remove any rules with a constant zero or nan forecast
:param instrument_code:
:return: list of str
"""
if self._use_estimated_weights():
# Note for estimated weights we apply the 'is this cheap enough'
# rule, but not here
trial_rule_list = self.get_trading_rule_list_for_estimated_weights(
instrument_code
)
else:
trial_rule_list = self._get_trading_rule_list_with_fixed_weights(
instrument_code
)
return trial_rule_list
@diagnostic()
def _get_trading_rule_list_with_fixed_weights(self, instrument_code: str) -> list:
"""
Get list of all trading rule names when weights are fixed
If we have fixed weights use those; otherwise get from trading rules
>>> from systems.tests.testdata import get_test_object_futures_with_rules_and_capping
>>> from systems.basesystem import System
>>> (fcs, rules, rawdata, data, config)=get_test_object_futures_with_rules_and_capping()
>>> system=System([rawdata, rules, fcs, ForecastCombineFixed()], data, config)
>>>
>>> system.combForecast.get_trading_rule_list("EDOLLAR")
['ewmac16', 'ewmac8']
"""
# Let's try the config
config = self.config
rules = _get_list_of_rules_from_config_for_instrument(
config=config, instrument_code=instrument_code, forecast_combine_stage=self
)
rules = sorted(rules)
return rules
@property
def config(self) -> Config:
return self.parent.config
@input
def _get_list_of_all_trading_rules_from_forecasting_stage(self) -> list:
return list(self.rules_stage.trading_rules().keys())
@property
def rules_stage(self) -> Rules:
return self.parent.rules
@diagnostic()
def get_trading_rule_list_for_estimated_weights(self, instrument_code: str) -> list:
"""
Get list of all trading rule names when weights are estimated
If rule_variations is specified in config use that, otherwise use all available rules
:param instrument_code:
:type str:
:returns: list of str
KEY INPUT
>>> from systems.tests.testdata import get_test_object_futures_with_rules_and_capping_estimate
>>> from systems.basesystem import System
>>> (accounts, fcs, rules, rawdata, data, config)=get_test_object_futures_with_rules_and_capping_estimate()
>>> system=System([accounts, rawdata, rules, fcs, ForecastCombineEstimated()], data, config)
>>> system.combForecast.get_trading_rule_list("EDOLLAR")
['carry', 'ewmac16', 'ewmac8']
>>> system.config.rule_variations=dict(EDOLLAR=["ewmac8"])
>>> system.combForecast.get_trading_rule_list("EDOLLAR")
['ewmac8']
"""
# Let's try the config
config = self.config
if hasattr(config, "rule_variations"):
###
if instrument_code in config.rule_variations:
# nested dict of lists
rules = config.rule_variations[instrument_code]
else:
# assume it's a non nested list
# this will break if you have put an incomplete list of
# instruments into a nested dict
rules = config.rule_variations
else:
## not supplied in config
rules = self._get_list_of_all_trading_rules_from_forecasting_stage()
rules = sorted(rules)
return rules
@diagnostic()
def get_forecasts_given_rule_list(
self, instrument_code: str, rule_variation_list: list
) -> pd.Series:
"""
Convenience function to get a list of forecasts
:param instrument_code: str
:param rule_variation_list: list of str
:return: pd.DataFrame
"""
forecasts = [
self._get_capped_individual_forecast(instrument_code, rule_variation_name)
for rule_variation_name in rule_variation_list
]
forecasts = pd.concat(forecasts, axis=1)
forecasts.columns = rule_variation_list
forecasts = forecasts.ffill()
return forecasts
@property
def raw_data_stage(self):
return self.parent.rawdata
@input
def _get_capped_individual_forecast(
self, instrument_code: str, rule_variation_name: str
) -> pd.Series:
"""
Get the capped forecast from the previous module
KEY INPUT
:param instrument_code:
:type str:
:param rule_variation_name:
:type str: name of the trading rule variation
:returns: dict of Tx1 pd.DataFrames; keynames rule_variation_name
>>> from systems.tests.testdata import get_test_object_futures_with_rules_and_capping
>>> from systems.basesystem import System
>>> (fcs, rules, rawdata, data, config)=get_test_object_futures_with_rules_and_capping()
>>> system=System([rawdata, rules, fcs, ForecastCombineFixed()], data, config)
>>> system.combForecast._get_capped_individual_forecast("EDOLLAR","ewmac8").tail(2)
ewmac8
2015-12-10 -0.190583
2015-12-11 0.871231
"""
return self.forecast_scale_cap_stage.get_capped_forecast(
instrument_code, rule_variation_name
)
@property
def forecast_scale_cap_stage(self) -> ForecastScaleCap:
return self.parent.forecastScaleCap
# FORECAST WEIGHT CALCULATIONS
@dont_cache
def get_raw_monthly_forecast_weights(self, instrument_code: str) -> pd.DataFrame:
"""
Get forecast weights depending on whether we are estimating these or
not
:param instrument_code: str
:return: forecast weights
"""
# get estimated weights, will probably come back as annual data frame
if self._use_estimated_weights():
forecast_weights = self.get_monthly_raw_forecast_weights_estimated(
instrument_code
)
else:
## will come back as 2*N data frame
forecast_weights = self.get_raw_fixed_forecast_weights(instrument_code)
## FIXME NEED THIS TO APPLY TO GROUPINGS
forecast_weights_cheap_rules_only = self._remove_expensive_rules_from_weights(
instrument_code, forecast_weights
)
return forecast_weights_cheap_rules_only
@dont_cache
def _remove_expensive_rules_from_weights(
self, instrument_code, monthly_forecast_weights: pd.DataFrame
) -> pd.DataFrame:
cheap_rules = self.cheap_trading_rules_post_processing(instrument_code)
if len(cheap_rules) == 0:
## special case all zeros
monthly_forecast_weights_cheap_rules_only = copy(monthly_forecast_weights)
monthly_forecast_weights_cheap_rules_only[:] = 0.0
return monthly_forecast_weights_cheap_rules_only
original_rules = list(monthly_forecast_weights.columns)
cheap_rules_in_weights = list(set(original_rules).intersection(cheap_rules))
monthly_forecast_weights_cheap_rules_only = monthly_forecast_weights[
cheap_rules_in_weights
]
return monthly_forecast_weights_cheap_rules_only
@dont_cache
def _use_estimated_weights(self):
return str2Bool(self.config.use_forecast_weight_estimates)
def get_monthly_raw_forecast_weights_estimated(
self, instrument_code: str
) -> pd.DataFrame:
"""
Estimate the forecast weights for this instrument
:param instrument_code:
:type str:
:returns: TxK pd.DataFrame containing weights, columns are trading rule variation names, T covers all
>>> from systems.tests.testdata import get_test_object_futures_with_rules_and_capping_estimate
>>> from systems.basesystem import System
>>> (accounts, fcs, rules, rawdata, data, config)=get_test_object_futures_with_rules_and_capping_estimate()
>>> system=System([accounts, rawdata, rules, fcs, ForecastCombineEstimated()], data, config)
>>> system.config.forecast_weight_estimate['method']="shrinkage"
>>> system.combForecast.get_raw_monthly_forecast_weights("EDOLLAR").tail(3)
carry ewmac16 ewmac8
2015-05-30 0.437915 0.258300 0.303785
2015-06-01 0.442438 0.256319 0.301243
2015-12-12 0.442438 0.256319 0.301243
>>> system.delete_all_items(True)
>>> system.config.forecast_weight_estimate['method']="one_period"
>>> system.combForecast.get_raw_monthly_forecast_weights("EDOLLAR").tail(3)
2015-05-30 0.484279 8.867313e-17 0.515721
2015-06-01 0.515626 7.408912e-17 0.484374
2015-12-12 0.515626 7.408912e-17 0.484374
>>> system.delete_all_items(True)
>>> system.config.forecast_weight_estimate['method']="bootstrap"
>>> system.config.forecast_weight_estimate['monte_runs']=50
>>> system.combForecast.get_raw_monthly_forecast_weights("EDOLLAR").tail(3)
carry ewmac16 ewmac8
2015-05-30 0.446446 0.222678 0.330876
2015-06-01 0.464240 0.192962 0.342798
2015-12-12 0.464240 0.192962 0.342798
"""
optimiser = self.calculation_of_raw_estimated_monthly_forecast_weights(
instrument_code
)
forecast_weights = optimiser.weights()
return forecast_weights
@diagnostic(not_pickable=True, protected=True)
def calculation_of_raw_estimated_monthly_forecast_weights(self, instrument_code):
"""
Does an optimisation for a single instrument
We do this if we can't do the special case of a fully pooled
optimisation (both costs and returns pooled)
Estimate the forecast weights for this instrument
We store this intermediate step to expose the calculation object
:param instrument_code:
:type str:
:returns: TxK pd.DataFrame containing weights, columns are trading rule variation names, T covers all
"""
self.log.info("Calculating raw forecast weights for %s" % instrument_code)
config = self.config
# Get some useful stuff from the config
weighting_params = copy(config.forecast_weight_estimate)
# which function to use for calculation
weighting_func = resolve_function(weighting_params.pop("func"))
returns_pre_processor = self.returns_pre_processor_for_code(instrument_code)
weight_func = weighting_func(
returns_pre_processor,
asset_name=instrument_code,
log=self.log,
**weighting_params,
)
return weight_func
@diagnostic(not_pickable=True)
def returns_pre_processor_for_code(self, instrument_code) -> returnsPreProcessor:
# Because we might be pooling, we get a stack of p&l data
codes_to_use = self.has_same_cheap_rules_as_code(instrument_code)
trading_rule_list = self.cheap_trading_rules(instrument_code)
returns_pre_processor = self.returns_pre_processing(
codes_to_use, trading_rule_list=trading_rule_list
)
return returns_pre_processor
@diagnostic(not_pickable=True)
def returns_pre_processing(
self, codes_to_use: list, trading_rule_list: list
) -> returnsPreProcessor:
pandl_forecasts = self.get_pandl_forecasts(codes_to_use, trading_rule_list)
turnovers = self.get_turnover_for_list_of_rules(codes_to_use, trading_rule_list)
config = self.config
weighting_params = copy(config.forecast_weight_estimate)
cost_params = copy(config.forecast_cost_estimates)
weighting_params = {**weighting_params, **cost_params}
returns_pre_processor = returnsPreProcessor(
pandl_forecasts, turnovers=turnovers, log=self.log, **weighting_params
)
return returns_pre_processor
@dont_cache
def get_turnover_for_list_of_rules(
self, codes_to_use: list, list_of_rules: list
) -> turnoverDataAcrossTradingRules:
turnover_dict = dict(
[
(rule_name, self.get_turnover_for_forecast(codes_to_use, rule_name))
for rule_name in list_of_rules
]
)
turnover_data = turnoverDataAcrossTradingRules(turnover_dict)
## dict of lists
return turnover_data
@input
def get_turnover_for_forecast(
self, codes_to_use: list, rule_variation_name: str
) -> turnoverDataForTradingRule:
return self.accounts_stage.get_turnover_for_forecast_combination(
codes_to_use=codes_to_use, rule_variation_name=rule_variation_name
)
@dont_cache
def get_pandl_forecasts(
self, codes_to_use: list, trading_rule_list: list
) -> dictOfReturnsForOptimisationWithCosts:
# returns a dict of accountCurveGroups
pandl_forecasts = dict(
[
(code, self.get_returns_for_optimisation(code, trading_rule_list))
for code in codes_to_use
]
)
pandl_forecasts = dictOfReturnsForOptimisationWithCosts(pandl_forecasts)
return pandl_forecasts
@dont_cache
def has_same_cheap_rules_as_code(self, instrument_code: str) -> list:
"""
Returns all instruments with same set of trading rules as this one, after max cost applied
:param instrument_code:
:type str:
:returns: list of str
"""
my_rules = self.cheap_trading_rules(instrument_code)
instrument_list = self.parent.get_instrument_list()
def _rule_list_matches(list_of_rules, other_list_of_rules):
list_of_rules.sort()
other_list_of_rules.sort()
return list_of_rules == other_list_of_rules
matching_instruments = [
other_code
for other_code in instrument_list
if _rule_list_matches(my_rules, self.cheap_trading_rules(other_code))
]
matching_instruments.sort()
return matching_instruments
def expensive_trading_rules_post_processing(self, instrument_code: str) -> list:
all_rule_names = self.get_trading_rule_list(instrument_code)
cheap_rule_names = self.cheap_trading_rules_post_processing(instrument_code)
expensive_rules = list_difference(all_rule_names, cheap_rule_names)
return expensive_rules
@diagnostic()
def cheap_trading_rules_post_processing(self, instrument_code: str) -> list:
"""
Returns a list of trading rules which are cheap enough to trade, given a max tolerable
annualised SR cost
:param instrument_code:
:type str:
:returns: list of str
"""
ceiling_cost_SR = self.config.forecast_post_ceiling_cost_SR
cheap_rule_list = self._cheap_trading_rules_generic(
instrument_code, ceiling_cost_SR=ceiling_cost_SR
)
return cheap_rule_list
@diagnostic()
def cheap_trading_rules(self, instrument_code: str) -> list:
"""
Returns a list of trading rules which are cheap enough to trade, given a max tolerable
annualised SR cost
:param instrument_code:
:type str:
:returns: list of str
"""
ceiling_cost_SR = self.config.forecast_weight_estimate["ceiling_cost_SR"]
cheap_rule_list = self._cheap_trading_rules_generic(
instrument_code, ceiling_cost_SR=ceiling_cost_SR
)
return cheap_rule_list
@dont_cache
def _cheap_trading_rules_generic(
self, instrument_code: str, ceiling_cost_SR: float
) -> list:
"""
Returns a list of trading rules which are cheap enough to trade, given a max tolerable
annualised SR cost
:param instrument_code:
:type str:
:returns: list of str
"""
rule_list = self.get_trading_rule_list(instrument_code)
SR_cost_list = [
self.get_SR_cost_for_instrument_forecast(
instrument_code, rule_variation_name
)
for rule_variation_name in rule_list
]
cheap_rule_list = [
rule_name
for (rule_name, rule_cost) in zip(rule_list, SR_cost_list)
if rule_cost <= ceiling_cost_SR
]
if len(cheap_rule_list) == 0:
error_msg = (
"No rules are cheap enough for %s with threshold %.3f SR units! Raise threshold (system.config.forecast_weight_estimate['ceiling_cost_SR']), add rules, or drop instrument."
% (instrument_code, ceiling_cost_SR)
)
self.log.warning(error_msg)
else:
self.log.debug(
"Only this set of rules %s is cheap enough to trade for %s"
% (str(cheap_rule_list), instrument_code),
instrument_code=instrument_code,
)
return cheap_rule_list
@input
def get_SR_cost_for_instrument_forecast(
self, instrument_code: str, rule_variation_name: str
) -> float:
"""
Get the cost in SR units per year of trading this instrument / rule
:param instrument_code:
:type str:
:param rule_variation_name:
:type str:
:returns: float
KEY INPUT
"""
try:
accounts = self.accounts_stage
except missingData:
warn_msg = (
"You need an accounts stage in the system to estimate forecast costs for %s %s. Using costs of zero"
% (instrument_code, rule_variation_name)
)
self.log.warning(warn_msg)
return 0.0
return accounts.get_SR_cost_for_instrument_forecast(
instrument_code, rule_variation_name
)
@property
def accounts_stage(self):
if not hasattr(self.parent, "accounts"):
raise missingData
# no -> to avoid circular imports
return self.parent.accounts
@input
def get_returns_for_optimisation(
self, instrument_code: str, trading_rule_list: list
) -> returnsForOptimisationWithCosts:
"""
Get pandl for forecasts for a given rule
THese will include both gross and net returns, in case we do any pooling
KEY INPUT
:param instrument_code:
:type str:
:returns: accountCurveGroup object
"""
try:
accounts = self.accounts_stage
except missingData:
error_msg = (
"You need an accounts stage in the system to estimate forecast weights"
)
self.log.critical(error_msg)
raise Exception(error_msg)
pandl = accounts.pandl_for_instrument_rules_unweighted(
instrument_code, trading_rule_list=trading_rule_list
)
pandl = returnsForOptimisationWithCosts(pandl)
return pandl
# FIXED FORECAST WEIGHTS
def get_raw_fixed_forecast_weights(self, instrument_code: str) -> pd.DataFrame:
"""
Get the forecast weights for this instrument
From: (a) passed into subsystem when created
(b) ... if not found then: in system.config.instrument_weights
:param instrument_code:
:type str:
:returns: TxK pd.DataFrame containing weights, columns are trading rule variation names, T covers all
>>> from systems.tests.testdata import get_test_object_futures_with_rules_and_capping
>>> from systems.basesystem import System
>>> (fcs, rules, rawdata, data, config)=get_test_object_futures_with_rules_and_capping()
>>> system=System([rawdata, rules, fcs, ForecastCombineFixed()], data, config)
>>>
>>> ## from config
>>> system.combForecast.get_raw_monthly_forecast_weights("EDOLLAR").tail(2)
ewmac16 ewmac8
2015-12-10 0.5 0.5
2015-12-11 0.5 0.5
>>>
>>> config.forecast_weights=dict(EDOLLAR=dict(ewmac8=0.9, ewmac16=0.1))
>>> system2=System([rawdata, rules, fcs, ForecastCombineFixed()], data, config)
>>> system2.combForecast.get_raw_monthly_forecast_weights("EDOLLAR").tail(2)
ewmac16 ewmac8
2015-12-10 0.1 0.9
2015-12-11 0.1 0.9
>>>
>>> del(config.forecast_weights)
>>> system3=System([rawdata, rules, fcs, ForecastCombineFixed()], data, config)
>>> system3.combForecast.get_raw_monthly_forecast_weights("EDOLLAR").tail(2)
WARNING: No forecast weights - using equal weights of 0.5000 over all 2 trading rules in system
ewmac16 ewmac8
2015-12-10 0.5 0.5
2015-12-11 0.5 0.5
"""
# Now we have a dict, fixed_weights.
# Need to turn into a timeseries covering the range of forecast
# dates
fixed_weights = self._get_fixed_forecast_weights_as_dict(instrument_code)
rule_variation_list = sorted(fixed_weights.keys())
forecasts = self.get_all_forecasts(instrument_code, rule_variation_list)
forecasts_time_index = forecasts.index
forecast_columns_to_align = forecasts.columns
# Turn into a 2 row data frame aligned to forecast names
forecast_weights = from_dict_of_values_to_df(
fixed_weights, forecasts_time_index, columns=forecast_columns_to_align
)
## Should be monthly for consistency, but span all data
monthly_forecast_weights = reindex_last_monthly_include_first_date(
forecast_weights
)
return monthly_forecast_weights
@diagnostic()
def _get_fixed_forecast_weights_as_dict(self, instrument_code: str) -> dict:
config = self.parent.config
# Let's try the config
try:
forecast_weights_config = config.get_element("forecast_weights")
except missingData:
fixed_weights = self._get_one_over_n_weights(instrument_code)
else:
expensive_trading_rules_post_processing = (
self.expensive_trading_rules_post_processing(instrument_code)
)
fixed_weights = _get_fixed_weights_from_config(
forecast_weights_config=forecast_weights_config,
instrument_code=instrument_code,
log=self.log,
expensive_trading_rules_post_processing=expensive_trading_rules_post_processing,
)
return fixed_weights
def _get_one_over_n_weights(self, instrument_code: str) -> dict:
rules = self.get_trading_rule_list(instrument_code)
equal_weight = 1.0 / len(rules)
warn_msg = (
"WARNING: No forecast weights - using equal weights of %.3f over all %d trading rules in system"
% (equal_weight, len(rules))
)
self.log.warning(warn_msg, instrument_code=instrument_code)
fixed_weights = dict([(rule_name, equal_weight) for rule_name in rules])
return fixed_weights
# DIVERSIFICATION MULTIPLIER