Strategy extension

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:

class DemoExtendedStrategy(sig.Strategy):
    data = AnyType(default=None)
    
    def strategy_initialization(self, dt):
        for d in self.data.index:
            self.add_method(d, self.rebalance, d)
            
    def rebalance(self, dt, d):
        for instrument_name, quantity in self.data.loc[d].items():
            self.add_position_target(dt, instrument_name, quantity, unit_type='WEIGHT')
    
    def strategy_extension(self, from_dt, to_dt):
        self.end_dt = self.strategy_timeline.end_dt = \
            self.strategy_timeline.target_calculation_dt = to_dt
        self.end_date = self.end_dt.date()
        self.clear_caches()
        for d in self.data.index:
            if from_dt.date() <= d <= to_dt.date():
                self.add_method(d, self.rebalance, d)

strategy = DemoExtendedStrategy(
    currency='USD',
    start_date=dtm.datetime(2021, 4, 7),
    end_date=dtm.datetime(2021, 4, 12),
    initial_cash=10000,
    total_return=False,
    data=pd.Series({
        dtm.date(2021, 4, 8): 0.25,
        dtm.date(2021, 4, 10): 0.5,
        dtm.date(2021, 4, 12): 1.00,
        dtm.date(2021, 4, 13): 0.,
        dtm.date(2021, 4, 17): 0.25,
        dtm.date(2021, 4, 20): -1
    }).to_frame('ESM21 INDEX')
)
strategy.history()

Output:

2021-04-07    10000.000000
2021-04-08     9999.898839
2021-04-09    10018.633483
2021-04-12    10018.794806
Name: (LastPrice, EOD, USD 9E6BD401 DES STRATEGY), dtype: float64

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:

from_dt = strategy.end_dt
to_dt = strategy.valuation_dt(dtm.date(2021, 4, 20))
strategy.strategy_extension(from_dt, to_dt)
strategy.history()