Search…
Strategy extension
The incremental construction of timelines allows for a strategy to be built up to a specified point in time and extended once more data becomes available. Storing the strategy allows for its continuous loading, extension, and resaving, thus avoiding the effort and cost of running the entire strategy from scratch each time. Extending a strategy is facilitated by the strategy_extension method.
In the example below the default method is used to run a strategy until the 12th April 2021.
Python
Output
1
class DemoExtendedStrategy(sig.Strategy):
2
data = AnyType(default=None)
3
4
def strategy_initialization(self, dt):
5
for d in self.data.index:
6
self.add_method(d, self.rebalance, d)
7
8
def rebalance(self, dt, d):
9
for instrument_name, quantity in self.data.loc[d].items():
10
self.add_position_target(dt, instrument_name, quantity, unit_type='WEIGHT')
11
12
def strategy_extension(self, from_dt, to_dt):
13
self.end_dt = self.strategy_timeline.end_dt = \
14
self.strategy_timeline.target_calculation_dt = to_dt
15
self.end_date = self.end_dt.date()
16
self.clear_caches()
17
for d in self.data.index:
18
if from_dt.date() <= d <= to_dt.date():
19
self.add_method(d, self.rebalance, d)
20
21
strategy = DemoExtendedStrategy(
22
currency='USD',
23
start_date=dtm.datetime(2021, 4, 7),
24
end_date=dtm.datetime(2021, 4, 12),
25
initial_cash=10000,
26
total_return=False,
27
data=pd.Series({
28
dtm.date(2021, 4, 8): 0.25,
29
dtm.date(2021, 4, 10): 0.5,
30
dtm.date(2021, 4, 12): 1.00,
31
dtm.date(2021, 4, 13): 0.,
32
dtm.date(2021, 4, 17): 0.25,
33
dtm.date(2021, 4, 20): -1
34
}).to_frame('ESM21 INDEX')
35
)
36
strategy.history()
Copied!
1
2021-04-07 10000.000000
2
2021-04-08 9999.898839
3
2021-04-09 10018.633483
4
2021-04-12 10018.794806
5
Name: (LastPrice, EOD, USD 9E6BD401 DES STRATEGY), dtype: float64
Copied!
The strategy_extension method checks for additional actions to take between two dates. In the example below, this method is used to extend the strategy to consider signals generated between the 12th of April and the 20th of April.
Python
1
from_dt = strategy.end_dt
2
to_dt = strategy.valuation_dt(dtm.date(2021, 4, 20))
3
strategy.strategy_extension(from_dt, to_dt)
4
strategy.history()
Copied!
Export as PDF
Copy link