forked from robcarver17/pysystemtrade
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreport_system_classic.py
556 lines (454 loc) · 16.4 KB
/
report_system_classic.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
import pandas as pd
import numpy as np
import datetime
from collections import namedtuple
from syscore.exceptions import missingData
from sysproduction.reporting.reporting_functions import table, header, body_text
from syscore.dateutils import ROOT_BDAYS_INYEAR, from_marker_string_to_datetime
from sysproduction.data.positions import diagPositions
from sysobjects.production.backtest_storage import interactiveBacktest
from sysobjects.production.tradeable_object import instrumentStrategy
def report_system_classic(data, backtest: interactiveBacktest) -> list:
"""
:param strategy_name: str
:param data: dataBlob
:param backtest: dataBacktest object populated with a specific backtest
:return: list of report format type objects
"""
strategy_name = backtest.strategy_name
timestamp = backtest.timestamp
format_output = []
report_header = header(
"Strategy report for %s backtest timestamp %s produced at %s"
% (strategy_name, timestamp, str(datetime.datetime.now()))
)
format_output.append(report_header)
format_output = report_system_classic_no_header_or_footer(
data, backtest=backtest, format_output=format_output
)
format_output.append(body_text("End of report for %s" % strategy_name))
return format_output
def report_system_classic_no_header_or_footer(
data, backtest: interactiveBacktest, format_output: list
) -> list:
"""
:param strategy_name: str
:param data: dataBlob
:param backtest: dataBacktest object populated with a specific backtest
:return: list of report format type objects
"""
risk_scaling_str = risk_scaling_string(backtest)
format_output.append(body_text(risk_scaling_str))
# Cash target
cash_target_dict = backtest.system.positionSize.get_vol_target_dict()
cash_target_text = body_text("\nVol target calculation %s\n" % cash_target_dict)
format_output.append(cash_target_text)
# Vol calc
vol_calc_df = get_stage_breakdown_over_codes(
backtest,
method_list=[daily_returns_vol, daily_denom_price, rawdata_daily_perc_vol],
)
vol_calc_df["annual % vol"] = vol_calc_df["Daily % vol"] * ROOT_BDAYS_INYEAR
vol_calc_df_rounded = vol_calc_df.round(4)
vol_calc_table = table("Vol calculation", vol_calc_df_rounded)
format_output.append(vol_calc_table)
# Subsystem position table
subystem_positions_df = get_stage_breakdown_over_codes(
backtest,
method_list=[
get_block_value,
get_price_volatility,
get_instrument_ccy_vol,
get_fx_rate,
get_instrument_value_vol,
get_daily_cash_vol_target,
get_vol_scalar,
get_combined_forecast,
get_subsystem_position,
],
)
subystem_positions_df_rounded = subystem_positions_df.round(2)
subystem_positions_table = table(
"Subsystem position", subystem_positions_df_rounded
)
format_output.append(subystem_positions_table)
# Portfolio position table: ss position, instr weight, IDM, position
# required
portfolio_positions_df = get_stage_breakdown_over_codes(
backtest,
method_list=[
get_subsystem_position,
get_instrument_weights,
get_idm,
get_required_portfolio_position,
],
)
portfolio_positions_df_rounded = portfolio_positions_df.round(3)
portfolio_positions_table = table(
"Portfolio positions", portfolio_positions_df_rounded
)
format_output.append(portfolio_positions_table)
# position diags
position_diags_df = calc_position_diags(
portfolio_positions_df, subystem_positions_df
)
position_diags_df_rounded = position_diags_df.round(2)
position_diags_table = table("Position diags", position_diags_df_rounded)
format_output.append(position_diags_table)
# Position vs buffer table: position required, buffers, actual position
versus_buffers_df = get_stage_breakdown_over_codes(
backtest,
method_list=[
get_required_portfolio_position,
get_lower_buffer,
get_upper_buffer,
],
)
instrument_code_list = versus_buffers_df.index
timestamp_positions = get_position_at_timestamp_df_for_instrument_code_list(
backtest, data, instrument_code_list
)
current_positions = get_current_position_df_for_instrument_code_list(
backtest, data, instrument_code_list
)
versus_buffers_and_positions_df = pd.concat(
[versus_buffers_df, timestamp_positions, current_positions], axis=1
)
versus_buffers_and_positions_df_rounded = versus_buffers_and_positions_df.round(1)
versus_buffers_and_positions_table = table(
"Positions vs buffers", versus_buffers_and_positions_df_rounded
)
format_output.append(versus_buffers_and_positions_table)
# Forecast weights
forecast_weights_df = get_forecast_matrix_over_code(
backtest, stage_name="combForecast", method_name="get_forecast_weights"
)
forecast_weights_df_as_perc = forecast_weights_df * 100
forecast_weights_df_as_perc_rounded = forecast_weights_df_as_perc.round(1)
forecast_weights_table = table(
"Forecast weights", forecast_weights_df_as_perc_rounded
)
format_output.append(forecast_weights_table)
unweighted_forecasts_df = get_forecast_matrix(
backtest, stage_name="forecastScaleCap", method_name="get_capped_forecast"
)
# Weighted forecast
weighted_forecasts_df = forecast_weights_df * unweighted_forecasts_df
weighted_forecast_rounded = weighted_forecasts_df.round(1)
weighted_forecast_table = table("Weighted forecasts", weighted_forecast_rounded)
format_output.append(weighted_forecast_table)
unweighted_forecasts_df_rounded = unweighted_forecasts_df.round(1)
unweighted_forecasts_table = table(
"Unweighted forecasts", unweighted_forecasts_df_rounded
)
format_output.append(unweighted_forecasts_table)
return format_output
def get_forecast_matrix(
data_backtest, stage_name="combForecast", method_name="get_capped_forecast"
):
instrument_codes = data_backtest.system.get_instrument_list()
trading_rules = data_backtest.system.rules.trading_rules()
trading_rule_names = list(trading_rules.keys())
datetime_cutoff = from_marker_string_to_datetime(data_backtest.timestamp)
value_dict = {}
for rule_name in trading_rule_names:
value_dict[rule_name] = []
for instrument_code in instrument_codes:
stage = getattr(data_backtest.system, stage_name)
method = getattr(stage, method_name)
value = method(instrument_code, rule_name).ffill()[:datetime_cutoff][-1]
value_dict[rule_name].append(value)
value_df = pd.DataFrame(value_dict, index=instrument_codes)
return value_df
def get_forecast_matrix_over_code(
data_backtest, stage_name="combForecast", method_name="get_forecast_weights"
):
instrument_codes = data_backtest.system.get_instrument_list()
trading_rules = data_backtest.system.rules.trading_rules()
trading_rule_names = list(trading_rules.keys())
datetime_cutoff = from_marker_string_to_datetime(data_backtest.timestamp)
value_dict = {}
for instrument_code in instrument_codes:
stage = getattr(data_backtest.system, stage_name)
method = getattr(stage, method_name)
value_row = method(instrument_code).ffill()[:datetime_cutoff].iloc[-1]
values_by_rule = [
value_row.get(rule_name, np.nan) for rule_name in trading_rule_names
]
value_dict[instrument_code] = values_by_rule
value_df = pd.DataFrame(value_dict, index=trading_rule_names)
value_df = value_df.transpose()
return value_df
# ss position, instr weight, IDM, position required
configForMethod = namedtuple(
"ConfigForMethod",
[
"stage_name",
"method_name",
"name",
"global_bool",
"requires_code_bool",
"col_selector",
"scalar_bool",
],
)
daily_returns_vol = configForMethod(
"rawdata", "daily_returns_volatility", "Daily return vol", False, True, None, False
)
daily_denom_price = configForMethod(
"rawdata", "daily_denominator_price", "Price", False, True, None, False
)
rawdata_daily_perc_vol = configForMethod(
"rawdata",
"get_daily_percentage_volatility",
"Daily % vol",
False,
True,
None,
False,
)
get_combined_forecast = configForMethod(
"positionSize",
"get_combined_forecast",
"Combined forecast",
False,
True,
None,
False,
)
get_block_value = configForMethod(
"positionSize", "get_block_value", "Block_Value", False, True, None, False
)
get_price_volatility = configForMethod(
"positionSize",
"get_price_volatility",
"Daily price % vol",
False,
True,
None,
False,
)
get_fx_rate = configForMethod(
"positionSize", "get_fx_rate", "FX", False, True, None, False
)
get_instrument_ccy_vol = configForMethod(
"positionSize", "get_instrument_currency_vol", "ICV", False, True, None, False
)
get_instrument_value_vol = configForMethod(
"positionSize", "get_instrument_value_vol", "IVV", False, True, None, False
)
get_daily_cash_vol_target = configForMethod(
"positionSize",
"get_daily_cash_vol_target",
"Daily Cash Vol Tgt",
False,
False,
None,
True,
)
get_vol_scalar = configForMethod(
"positionSize",
"get_average_position_at_subsystem_level",
"Vol Scalar",
False,
True,
None,
False,
)
get_subsystem_position = configForMethod(
"positionSize",
"get_subsystem_position",
"subsystem_position",
False,
True,
None,
False,
)
get_instrument_weights = configForMethod(
"portfolio", "get_instrument_weights", "instr weight", False, False, None, False
)
get_idm = configForMethod(
"portfolio",
"get_instrument_diversification_multiplier",
"IDM",
True,
False,
None,
False,
)
get_required_portfolio_position = configForMethod(
"portfolio", "get_notional_position", "Notional position", False, True, None, False
)
get_lower_buffer = configForMethod(
"portfolio",
"get_actual_buffers_for_position",
"Lower buffer",
False,
True,
"bot_pos",
False,
)
get_upper_buffer = configForMethod(
"portfolio",
"get_actual_buffers_for_position",
"Upper buffer",
False,
True,
"top_pos",
False,
)
def get_stage_breakdown_over_codes(backtest: interactiveBacktest, method_list: list):
value_dict = {}
for config_for_method in method_list:
value_dict[
config_for_method.name
] = get_list_of_values_by_instrument_for_config(backtest, config_for_method)
instrument_codes = backtest.system.get_instrument_list()
value_df = pd.DataFrame(value_dict, index=instrument_codes)
return value_df
def get_list_of_values_by_instrument_for_config(backtest, config_for_method):
instrument_codes = backtest.system.get_instrument_list()
datetime_cutoff = from_marker_string_to_datetime(backtest.timestamp)
stage = getattr(backtest.system, config_for_method.stage_name)
method = getattr(stage, config_for_method.method_name)
if config_for_method.global_bool:
# Same value regardless of instrument
value = method().ffill()[:datetime_cutoff].iloc[-1]
if config_for_method.col_selector is not None:
value = value[config_for_method.col_selector]
value_list = [value] * len(instrument_codes)
return value_list
if config_for_method.requires_code_bool:
# call for each code
if config_for_method.col_selector is not None:
value_list = [
method(instrument_code)
.ffill()[:datetime_cutoff]
.iloc[-1][config_for_method.col_selector]
for instrument_code in instrument_codes
]
else:
value_list = [
method(instrument_code).ffill()[:datetime_cutoff].iloc[-1]
for instrument_code in instrument_codes
]
return value_list
if config_for_method.scalar_bool:
value = method()
value_list = [value] * len(instrument_codes)
return value_list
# get dataframe
value_row = method().ffill()[:datetime_cutoff].iloc[-1]
value_list = [
value_row.get(instrument_code, np.nan) for instrument_code in instrument_codes
]
return value_list
def get_current_position_df_for_instrument_code_list(
data_backtest, data, instrument_code_list
):
position_list = [
get_current_position_for_instrument_code(data_backtest, data, instrument_code)
for instrument_code in instrument_code_list
]
position_df = pd.DataFrame(
position_list, index=instrument_code_list, columns=["Current position"]
)
return position_df
def get_position_at_timestamp_df_for_instrument_code_list(
data_backtest, data, instrument_code_list
):
position_list = [
get_position_for_instrument_code_at_timestamp(
data_backtest, data, instrument_code
)
for instrument_code in instrument_code_list
]
position_df = pd.DataFrame(
position_list, index=instrument_code_list, columns=["Position at timestamp"]
)
return position_df
def get_position_for_instrument_code_at_timestamp(data_backtest, data, instrument_code):
diag_positions = diagPositions(data)
strategy_name = data_backtest.strategy_name
instrument_strategy = instrumentStrategy(
strategy_name=strategy_name, instrument_code=instrument_code
)
try:
positions_over_time = (
diag_positions.get_position_series_for_instrument_strategy(
instrument_strategy
)
)
except missingData:
return np.nan
datetime_cutoff = from_marker_string_to_datetime(data_backtest.timestamp)
positions_over_time_ffill = positions_over_time.ffill()
positions_before_cutoff = positions_over_time_ffill[:datetime_cutoff]
if len(positions_before_cutoff) == 0:
return np.nan
final_position = positions_before_cutoff.iloc[-1]
return final_position
def get_current_position_for_instrument_code(data_backtest, data, instrument_code):
diag_positions = diagPositions(data)
strategy_name = data_backtest.strategy_name
instrument_strategy = instrumentStrategy(
strategy_name=strategy_name, instrument_code=instrument_code
)
current_position = diag_positions.get_current_position_for_instrument_strategy(
instrument_strategy
)
return current_position
def calc_position_diags(portfolio_positions_df, subystem_positions_df):
idm = portfolio_positions_df.IDM
instr_weight = portfolio_positions_df["instr weight"]
vol_scalar = subystem_positions_df["Vol Scalar"]
average_position = idm * instr_weight * vol_scalar
return average_position
def risk_scaling_string(backtest) -> str:
backtest_system_portfolio_stage = backtest.system.portfolio
normal_risk_final = (
backtest_system_portfolio_stage.get_portfolio_risk_for_original_positions().iloc[
-1
]
* 100.0
)
shocked_vol_risk_final = (
backtest_system_portfolio_stage.get_portfolio_risk_for_original_positions_with_shocked_vol().iloc[
-1
]
* 100.0
)
sum_abs_risk_final = (
backtest_system_portfolio_stage.get_sum_annualised_risk_for_original_positions().iloc[
-1
]
* 100.0
)
leverage_final = (
backtest_system_portfolio_stage.get_leverage_for_original_position().iloc[-1]
)
percentage_vol_target = backtest_system_portfolio_stage.get_percentage_vol_target()
try:
risk_scalar = backtest_system_portfolio_stage.get_risk_scalar()
except missingData:
risk_scalar_final = 1.0
else:
risk_scalar_final = risk_scalar.iloc[-1]
risk_overlay_config = (
backtest_system_portfolio_stage.config.get_element_or_arg_not_supplied(
"risk_overlay"
)
)
scaling_str = (
"Risk overlay \n Config %s \n Percentage vol target %.1f \n Normal risk %.1f Shocked risk %.1f \n Sum abs risk %.1f Leverage %.2f \n Risk scalar %.2f"
% (
str(risk_overlay_config),
percentage_vol_target,
normal_risk_final,
shocked_vol_risk_final,
sum_abs_risk_final,
leverage_final,
risk_scalar_final,
)
)
return scaling_str