Search…
Strategy
The Strategy class is the basis for all backtesting in the SigTech platform. Functionality embedded within the Strategy class is also accessible via the classes inheriting from it.
Since all building blocks inherit from Strategy, using the full functionality of the SigTech platform’s building blocks requires a familiarity with the base class.
This page is relevant to all users of the SigTech platform—learn how to:
  • Build and backtest a strategy: Plot the value of a strategy through time.
  • Name a strategy: Specify a name for a strategy via the ticker parameter.
  • Retrieve a strategy: Fetch strategy objects from your cache via the sig.obj.get API.
  • Clone a strategy: Create a copy of a strategy and change its parameters.
  • Fix the parameters of a strategy: Set the initial cash held by a strategy, determine if that cash accrues interest, and decide whether or not transaction costs are included in the backtest.

Agenda

Environment

Set up your environment using the following three steps:
  • Import the relevant internal and external libraries
  • Configure the environment parameters
  • Initialise the environment
1
import pandas as pd
2
import datetime as dtm
3
from uuid import uuid4
4
import seaborn as sns
5
sns.set(rc={'figure.figsize': (18, 6)})
6
7
import sigtech.framework as sig
8
9
currency = 'USD'
10
start_date = dtm.date(2020, 1, 2)
11
end_date = dtm.date(2021, 11, 30)
12
13
sig.init(env_date=end_date)
Copied!

Backtesting

Backtests are conducted by creating an instance of an object that inherits from the Strategy class and calling build on it.
The following code block cycles through some commonly used building blocks and checks that they inherit from Strategy:
Input
Output
1
example_building_blocks = [
2
sig.RollingFutureStrategy,
3
sig.RollingFXForwardStrategy,
4
sig.DynamicOptionsStrategy,
5
sig.RollingSwapStrategy,
6
sig.ReinvestmentStrategy,
7
sig.RollingBondStrategy,
8
sig.BasketStrategy,
9
sig.SignalStrategy,
10
]
11
for building_block in example_building_blocks:
12
print(f'{building_block.__name__}: {issubclass(building_block, sig.Strategy)}')
Copied!
1
RollingFutureStrategy: True
2
RollingFXForwardStrategy: True
3
DynamicOptionsStrategy: True
4
RollingSwapStrategy: True
5
ReinvestmentStrategy: True
6
RollingBondStrategy: True
7
BasketStrategy: True
8
SignalStrategy: True
Copied!
Once a strategy has been built, the details of the backtest are stored within it and are accessible for further analysis. This includes the value of the strategy and holdings through time, and lower level details, such as the generation and execution of orders.
Note: calling build on a strategy that has already been built has no additional effect.
The following instance of a RollingFutureStrategy object is an example:
Note: strategies generally require a currency and start_date. If an end_date isn't used, the asofdate for the configured environment is used.
1
rfs = sig.RollingFutureStrategy(
2
currency=currency,
3
start_date=start_date,
4
contract_code='ES',
5
contract_sector='INDEX',
6
)
Copied!
Working through the build cycle:
Input
Output
1
rfs.built
Copied!
1
False
Copied!
1
rfs.build()
Copied!
Input
Output
1
rfs.built
Copied!
1
True
Copied!
Once a strategy has been built, calling history retrieves a pd.Series of its values or prices:
Note: this is the equivalent of calling history on an instrument to return its value through time.
Input
Output
1
rfs.history().head()
Copied!
1
2020-01-02 1000.000000
2
2020-01-03 999.992522
3
2020-01-06 1002.576428
4
2020-01-07 1000.088143
5
2020-01-08 1007.802267
6
Name: (LastPrice, EOD, USD ES INDEX LONG NONE 4C2AE1C5 RFS STRATEGY), dtype: float64
Copied!
Tip: it is unnecessary to call build and history separately. Calling history on an unbuilt strategy calls build automatically.

Strategy tickers

When a strategy object is constructed you can assign a name to it, using the ticker parameter. Once constructed, it is added to the cache of the environment.
If a ticker is not provided on construction, the strategy name is determined using the strategy details:
  • Strategy type: such as S for Strategy or BS for BasketStrategy.
  • Currency.
  • A random, eight-digit, alphanumeric combination.
To create a Strategy and display its automatically generated name:
Input
Output
1
s = sig.Strategy(
2
currency=currency,
3
start_date=start_date,
4
end_date=end_date
5
)
6
s.name
Copied!
1
'USD 16454872 S STRATEGY'
Copied!
To create a Strategy called TEST STRATEGY:
Input
Output
1
t = sig.Strategy(
2
currency=currency,
3
start_date=start_date,
4
end_date=end_date,
5
ticker='test'
6
)
7
t.name
Copied!
1
'TEST STRATEGY'
Copied!
Note: strategy names are always written in upper case, withSTRATEGYadded to the end.
In Backtesting, we built a RollingFutureStrategy called rfs. But we did not assign a ticker value. To display the automatically generated name of rfs:
Input
Output
1
rfs.name
Copied!
1
'USD ES INDEX LONG NONE 4C2AE1C5 RFS STRATEGY'
Copied!

Cache

When a strategy object is created, its name is added to the cache. You can access the cache directly via the configured environment:
1
env_cache = sig.env().object.cache
Copied!
Any object that has been accessed is also added to the cache. We can check the size of the cache with the following call:
Input
Output
1
print(len(env_cache))
Copied!
1
135
Copied!
You can filter the objects in the cache for those whose name ends with STRATEGY:
Input
Output
1
sorted([o for o in env_cache.keys() if o.endswith('STRATEGY')])
Copied!
1
['TEST STRATEGY',
2
'USD 16454872 S STRATEGY',
3
'USD CASH STRATEGY',
4
'USD ES INDEX LONG NONE 4C2AE1C5 RFS STRATEGY']
Copied!
Note: The results of the previous two cells will vary at different points as you progress through the notebook and add more items to the cache.
Any object listed in the cache is retrieved using the sig.obj.get API. This includes strategies created by users:
Input
Output
1
test_strategy = sig.obj.get('TEST STRATEGY')
2
test_strategy
Copied!
1
TEST STRATEGY <class 'sigtech.framework.strategies.strategy.Strategy'>[139995990091088]
Copied!
Check this with the original version:
Input
Output
1
test_strategy == t
Copied!
1
True
Copied!

Examples

To rebuild rfs and specify a ticker:
Input
Output
1
rfs_ticker = sig.RollingFutureStrategy(
2
currency=currency,
3
start_date=start_date,
4
contract_code='ES',
5
contract_sector='INDEX',
6
7
# specify ticker upon construction
8
ticker='ES RFS'
9
)
10
rfs_ticker.name
Copied!
1
'ES RFS STRATEGY'
Copied!
Object name clashes result in an ObjectError, unless the new strategy has identical characteristics to the existing strategy.
In the following code block, despite rfs_duplicate having the same ticker as rfs_ticker, there is no ObjectError as the characteristics of both strategies are identical:
Input
Output
1
rfs_duplicate = sig.RollingFutureStrategy(
2
currency=currency,
3
start_date=start_date,
4
contract_code='ES',
5
contract_sector='INDEX',
6
ticker='ES RFS'
7
)
8
rfs_duplicate.name
Copied!
1
'ES RFS STRATEGY'
Copied!
In contrast, the following example displays an error being produced due to rfs_error and rfs_ticker sharing the same ticker, but not the same start_date:
Input
Output
1
from sigtech.framework.internal.infra.utils.exceptions import ObjectError
2
3
try:
4
rfs_error = sig.RollingFutureStrategy(
5
currency=currency,
6
# start date is altered
7
start_date=start_date + dtm.timedelta(days=1),
8
contract_code='ES',
9
contract_sector='INDEX',
10
ticker='ES RFS'
11
)
12
except ObjectError as e:
13
print(e)
Copied!
1
Creating new object contradicting existing one!
2
ES RFS STRATEGY <class 'sigtech.framework.strategies.rolling_future_strategy.RollingFutureStrategy'>[139995990168784]
3
ES RFS STRATEGY <class 'sigtech.framework.strategies.rolling_future_strategy.RollingFutureStrategy'>[139995990128336]
Copied!

Cloning strategies

The clone_strategy method allows you to create a copy of an existing strategy and vary some of its parameters.
A dictionary of {parameter: new_value} pairs should be supplied. The following example creates a version of rfs in 'EUR' with an updated ticker:
Input
Output
1
eur_rfs = rfs.clone_strategy({'currency': 'EUR', 'ticker': 'EUR RFS'})
2
eur_rfs
Copied!
1
EUR RFS STRATEGY <class 'sigtech.framework.strategies.rolling_future_strategy.RollingFutureStrategy'>[139995990170832]
Copied!
Input
Output
1
print(f'Currency: {eur_rfs.currency}')
2
print(f'Name: {eur_rfs.name}')
Copied!
1
Currency: EUR
2
Name: EUR RFS STRATEGY
Copied!

Strategy details & parameters

Initial cash holdings

A strategy begins by holding a number of cash units, denominated in the currency of the strategy. The number of units is determined by the initial_cash parameter, with a default value of 1000.
Using the RollingFutureStrategy in Backtesting, plotting the history of rfs results in an initial value of 1000:
1
rfs.history().plot();
Copied!
The portfolio table also records an initial 1000 units of USD CASH:
1
rfs.plot.portfolio_table(
2
dts='TOP_ORDER_PTS',
3
end_dt=dtm.date(2020, 1, 3)
4
)
Copied!
To create a variant of rfs whose initial_cash level is 100:
Input
Output
1
rfs_initial_cash = rfs.clone_strategy({'ticker':'ES RFS $100', 'initial_cash': 100})
2
rfs_initial_cash.name
Copied!
1
'ES RFS $100 STRATEGY'
Copied!
As expected, the history series begins at 100:
Input
Output
1
rfs_initial_cash.history().head()
Copied!
1
2020-01-02 100.000000
2
2020-01-03 99.999252
3
2020-01-06 100.257643
4
2020-01-07 100.008814
5
2020-01-08 100.780227
6
Name: (LastPrice, EOD, ES RFS $100 STRATEGY), dtype: float64
Copied!
Assuming that the transaction cost model is AUM independent, varying initial_cash in this way is purely a matter of scaling and will not impact performance characteristics:
Input
Output
1
from sigtech.framework.analytics.performance.metrics import annualised_return
2
3
rfs_perf = annualised_return(rfs.history().dropna())
4
rfs_ic_perf = annualised_return(rfs_initial_cash.history().dropna())
5
6
print(f'{round(100 * rfs_perf, 3)}%')
7
print(f'{round(100 * rfs_ic_perf, 3)}%')
Copied!
1
22.723%
2
22.723%
Copied!
An exception to this rule is when initial_cash is set to zero. In this case no positions are opened. It is not possible to compute common metrics, such as return, for such a strategy.
Input
Output
1
rfs_zero_cash = rfs.clone_strategy({'ticker':'ES RFS ZERO', 'initial_cash': 0})
2
rfs_zero_cash.name
Copied!
1
'ES RFS ZERO STRATEGY'
Copied!
1
rfs_zero_cash.history().plot();
Copied!
There are multiple ways to remove cash from a strategy whilst still investing in underlyings. In the case of the RollingFutureStrategy, you will need to provide a fixed_contracts parameter and set the initial_cash to zero.
Similar functionality is available for ReinvestmentStrategy objects, using the initial_shares parameter.
Learn more: examples of these cases are provided in Further examples.

Total return

Accruing interest on the cash held within a strategy is optional and can be controlled with the boolean input total_return.
To create a variant of rfs that does not accrue interest on cash held:
1
rfs_er = rfs.clone_strategy({'ticker':'ES RFS ER', 'total_return': False})
2
rfs_er.build()
3
4
df = pd.DataFrame({'TotalReturn': rfs.history(),
5
'ExcessReturn': rfs_er.history()}).dropna()
6
df.plot();
Copied!
The difference in annualised return between the TotalReturn version of the strategy and the ExcessReturn version is approximately 32 basis points:
Input
Output
1
round(10000 * (rfs_perf - annualised_return(df['ExcessReturn'])))
Copied!
1
32.0
Copied!
As a further example, a custom strategy that simply holds its initial cash is created:
Learn more: Custom strategies.
1
class ExampleStrategy(sig.Strategy):
2
def strategy_initialization(self, dt):
3
pass
4
5
example_strategy = ExampleStrategy(
6
currency=currency,
7
start_date=dtm.date(2000, 1, 4),
8
initial_cash=100
9
)
Copied!
To create an alternative version with total_return set to False and plot the performance of both versions of the strategy:
1
er_example_strategy = example_strategy.clone_strategy({
2
'total_return': False
3
})
4
5
pd.DataFrame({
6
'TR': example_strategy.history(),
7
'ER': er_example_strategy.history()
8
}).plot();
Copied!
To switch off total_return at the global level when configuring the environment, use the command: sig.env()[sig.config.EXCESS_RETURN_ONLY] = True.

Transaction costs

The inclusion of transaction costs in a backtest can be controlled with the include_trading_costs parameter.
You can create a variant of rfs that does not assume any trading costs:
1
rfs_no_tc = rfs.clone_strategy({
2
'ticker': 'RFS NO TRADING COSTS',
3
'include_trading_costs': False
4
})
Copied!
To compute the impact of the transaction cost assumptions, you can compare the performance of the two strategy variants:
1
rfs_no_tc_perf = annualised_return(rfs_no_tc.history().dropna())
Copied!
The impact here is 2bp annualised. This can vary considerably, depending on the underlying and the transaction cost model.
Input
Output
1
round(10000 * (rfs_no_tc_perf - rfs_perf))
Copied!
1
2.0
Copied!
To switch off transaction costs at the global level when configuring the environment, use the following command: sig.env()[sig.config.IGNORE_T_COSTS] = True.

Not reinvesting P&L

You can fix the amount of cash used to determine the position of a strategy at its inception.
Example: signify a fixed capital allocation for a PM regardless of performance.
1
rfs_initial = sig.RollingFutureStrategy(
2
currency=currency,
3
start_date=dtm.date(2016, 1, 4),
4
contract_code='ES',
5
contract_sector='INDEX',
6
7
# relevant parameters
8
initial_cash=1e6,
9
set_weight_from_initial_cash=True,
10
ticker='ES RFS FIXED INITIAL CASH'
11
)
12
rfs_initial.build()
13
14
rfs_varying = rfs_initial.clone_strategy({
15
'set_weight_from_initial_cash': False
16
})
17
18
pd.DataFrame({
19
'VARYING CASH': rfs_varying.history(),
20
'FIXED CASH': rfs_initial.history()
21
}).plot();
Copied!
The following portfolio table displays a position of USD 1MM targeted at rebalance, despite the strategy holding close to USD 2MM in cash:
1
rfs_initial.plot.portfolio_table(
2
dts='TOP_ORDER_PTS',
3
start_dt=dtm.date(2021, 3, 1),
4
end_dt=dtm.date(2021, 4, 1)
5
)
Copied!

Long & short positions

Short versions of strategies are created by passing the direction parameter with a value of 'short', as opposed to its default of 'long':
1
rfs_short = sig.RollingFutureStrategy(
2
currency=currency,
3
start_date=start_date,
4
contract_code='ES',
5
contract_sector='INDEX',
6
7
# specify 'short' version
8
direction='short'
9
)
10
rfs_short.build()
Copied!
In the case of a RollingFutureStrategy, the 'short' version coincides with the negative of the long version:
1
pd.DataFrame({
2
'LONG': rfs.history(),
3
'SHORT': -rfs_short.history()
4
}).plot();
Copied!
Going short on the long version of the RollingFutureStrategy through a basket delivers the same result as going long on the short version of the RollingFutureStrategy through a basket:
1
basket_short_long_rfs = sig.BasketStrategy(
2
currency=currency,
3
start_date=start_date,
4
end_date=end_date,
5
weights=[-1.0],
6
constituent_names=[rfs.name],
7
rebalance_frequency='EOM'
8
)
9
basket_short_long_rfs.build()
10
11
basket_long_short_rfs = sig.BasketStrategy(
12
currency=currency,
13
start_date=start_date,
14
end_date=end_date,
15
weights=[1.0],
16
constituent_names=[rfs_short.name],
17
rebalance_frequency='EOM'
18
)
19
basket_long_short_rfs.build()
20
21
pd.DataFrame({
22
'LONG SHORT-RFS': basket_long_short_rfs.history(),
23
'SHORT LONG-RFS': basket_short_long_rfs.history(),
24
}).plot();
Copied!
For certain assets there are expected differences caused by market realities. An example is the treatment of dividends when creating a ReinvestmentStrategy:
1
rs_long = sig.ReinvestmentStrategy(
2
currency=currency,
3
start_date=start_date,
4
end_date=end_date,
5
underlyer='1000045.SINGLE_STOCK.TRADABLE',
6
ticker='AAPL RS LONG'
7
)
8
rs_long.build()
9
10
rs_short = rs_long.clone_strategy({'direction': 'short'})
11
12
pd.DataFrame({
13
'RS LONG': rs_long.history(),
14
'RS SHORT': -rs_short.history()
15
}).plot();
Copied!

Further examples

Note: These examples illustrate how to specify a specific number of units of underlying to trade whilst using a Building Block wrapper. The precise syntax can vary by asset class.

Rolling Future Strategy

By default the number of contracts held by a RollingFutureStrategy will be determined by the strategy's value and the value of each futures contract. It is possible to specify that a fixed number of contracts be traded by using the fixed_contracts parameter.
Input
Output
1
rfs_ticker = sig.RollingFutureStrategy(
2
currency=currency,
3
start_date=start_date,
4
contract_code='ES',
5
contract_sector='INDEX',
6
ticker='ES RFS'
7
)
8
rfs_ticker.name
Copied!
1
'ES RFS STRATEGY'
Copied!
1
rfs_contract_only = sig.RollingFutureStrategy(
2
currency=currency,
3
start_date=start_date,
4
end_date=end_date,
5
contract_code='ES',
6
contract_sector='INDEX',
7
8
# specific parameters
9
initial_cash=0,
10
include_trading_costs=False,
11
fixed_contracts=1,
12
ticker='ES RFS CONTRACT ONLY'
13
)
14
rfs_contract_only.build()
15
16
rfs_contract_only.history().plot();
Copied!
1
rfs_contract_only.plot.portfolio_table(
2
dts='VALUATION_PTS',
3
start_dt=start_date,
4
end_dt=dtm.date(2020, 1, 14),
5
unit_type='TRADE'
6
)
Copied!

Reinvestment Strategy

To create a ReinvestmentStrategy that holds precisely one unit of the underlying stock the initial_shares parameter can be used. You can also choose whether to include an initial cash balance on the strategy.
1
rs = sig.ReinvestmentStrategy(
2
currency=currency,
3
start_date=start_date,
4
end_date=end_date,
5
underlyer='1000045.SINGLE_STOCK.TRADABLE',
6
7
# specific parameters
8
initial_cash=0,
9
include_trading_costs=False,
10
initial_shares=1,
11
ticker='AAPL RS STOCK ONLY'
12
)
13
rs.build()
14
15
rs.history().plot();
Copied!
1
rs.plot.portfolio_table(
2
dts='VALUATION_PTS',
3
start_dt=start_date,
4
end_dt=dtm.date(2020, 1, 14),
5
unit_type='TRADE'
6
)
Copied!