Strategy

Strategy#

class sigtech.framework.strategies.strategy.Strategy

Baseclasses: AfterBuildMixin, StrategyInstrument

Subclasses: DailyStrategy, PeriodicIntradayStrategy, VWAPStrategy, IntradayMomentum

Base strategy class. Does not define sizing or execution points - must be specified manually

Parameters are the same as in the base StrategyInstrument:

  • currency: Currency of the strategy.

  • ticker: Assign a name under which the strategy is saved. Optional, if None then the name will be generated using the strategy type and the currency. The strategy can be loaded from cache using sig.obj.get('my_strategy_name').

  • initial_cash: Initial cash amount of strategy. Optional, by default 1000.

  • strategy_sizing_quantity: Control position weighting when set_weight_from_sizing_quantity is set to True. Optional, None by default but must be superior to 0 if set_weight_from_sizing_quantity is True.

  • start_date: Start date of the strategy. Optional, None by default. If None, start_dt must not be None.

  • start_dt: Start datetime of the strategy. Optional, None by default. If None, start_date must not be None.

  • end_date: End date of the strategy. datetime.date.max by default.

  • end_dt: End datetime of the strategy. Optional, None by default.

  • description: Description of the strategy. Optional, None by default.

  • valuation_time_input: Time point used as for valuations in this strategy. Optional, 23:59:59 by default.

  • valuation_timezone_input: Timezone to use for the execution time. Optional, None by default. If valuation_timezone_input is not provided this is taken from the trading manager.

Additional attributes:

  • total_return: If True, interest is accrued on the cash held within a strategy. Optional, True by default.

  • include_trading_costs: If True, transaction costs are included in the backtest. Optional, False by default.

  • direction: Control if strategy is short or long, long by default.

  • order_type: Control if orders can be split or if it has to be fulfilled completely (group). Optional, split by default.

  • unit_type: The unit type refers to the type of quantity provided, with the options:

    • 'MODEL' - Use the internal model units. (Default value)

    • 'TRADE' - Trade size, the units types vary between instruments and given by their position_type property.

    • 'CUSTOM' - Target a custom metric. Requires sizing_method to be defined.

  • additional_initial_holdings: List of initial position at inception of portfolio. Optional, empty by default. It is defined as a list of tuples containing the (ticker, unit, unit_type). unit_type is optional and defaulted to 'MODEL' if left empty. Examples: additional_initial_holdings = [('holding_1', 1,),...] or additional_initial_holdings = [('holding_1', 1, 'MODEL'),...]

  • set_weight_from_initial_cash: If True, target weight for allocation are defined from initial cash. Optional, False by default.

  • set_weight_from_sizing_quantity: If True, target weight for allocation are defined from strategy sizing quantity. Optional, False by default.

  • default_sizing_method: Defaulting of the sizing_method. Optional, None by default. The sizing method of an instrument or a strategy computes the size based on custom units, or a callable. The method should take the target custom risk quantity and datetime and return the units of the instrument or strategy.

  • record_fx_trades: If true, each FX spot trade will be added to the fx_trades property list as a tuple (ccy over, ccy under, notional, execution_dt). Optional, False by default.

  • trade_wrapper: Allow to add a wrapper to each position in the strategy. For now only StopTrigger wrapper is available. See also StopTrigger for more details.

Example:

import datetime as dtm

class ExampleStrategy(sig.Strategy):

    def strategy_initialization(self, dt):
        self.add_position_target(dt, 'EUR CASH', 1, unit_type='WEIGHT')

    def size_dt_from_decision_dt(self, decision_dt):
        return decision_dt - dtm.timedelta(days=1)

    def execution_dt_from_datetime(self, instrument, dt):
        if type(dt) == dtm.date:
            dt = dtm.datetime(dt.year, dt.month, dt.day)

        if instrument:
            calendar = instrument.history_schedule().approximate_holidays()
            time, tz = instrument.valuation_time, instrument.valuation_tzinfo
            date = instrument.calendar_schedule().current_next_data_date(dt.date()) or dt.date()
        else:
            calendar = 'None'
            time, tz = self.valuation_time, self.valuation_tzinfo
            date = dt.date()

        tm = sig.TradingManager.instance()
        return tm.datetime_from_date_and_time(date, time, tz, after=dt, use_trading_manager_calendar=True,
                                              calendar=calendar)

tst = ExampleStrategy(currency='USD', start_date=dtm.date(2020,1,2), end_date=dtm.date(2021,1,2))
tst.history()
additional_initial_holdings: Optional[list[Union[tuple[str, float], tuple[str, float, str]]]]
property analytics

Return an AnalyticsWrapper interface for strategy analytics.

property built

Check if this strategy has already been built.

default_sizing_method: Optional[Union[Callable, str]]
direction: Optional[Literal['long', 'short']]
property dynamic_config

Load an associated configuration object from the object register.

property first_entry_date

First date to use for trading.

include_trading_costs: Optional[bool]
property inspect

Return an InspectWrapper interface to inspect positions and actions of a strategy.

property intraday_history_fields

The intraday fields of history available for this strategy.

property order_transform

Retrieve timeline order transform - This sets the OrderTransform which manipulates placed orders.

order_type: Optional[Literal['group', 'split', 'auto']]
property plot

Return a PlotWrapper interface to produce plots for the strategy.

property positions

Return a PositionsWrapper interface for strategy position calculations.

property prime_intraday_history_field

The main intraday history field returned by default.

record_fx_trades: Optional[bool]
set_weight_from_initial_cash: Optional[bool]
set_weight_from_sizing_quantity: Optional[bool]
property strategy_timeline

Retrieve the strategy timeline and, if missing, create the strategy timeline.

property timeline_holdings

Build the strategy and return the holdings.

total_return: Optional[bool]
trade_wrapper: Optional[StopTrigger]
unit_type: Optional[str]
action_datetimes(start_dt=None, end_dt=None, include_all_valuations=False, exclude_internal_valuations=True)

Obtain a list of tz-aware datetimes for which an action on the strategy occurs in the range [start_dt, end_dt].

This includes all underlying strategy actions.

Parameters:
  • start_dt – Start datetime (optional).

  • end_dt – End datetime (optional).

  • include_all_valuations – All valuation points are included in the list (optional, default is False).

  • exclude_internal_valuations – Internal methods valuation points are excluded from the list. This is only applied when include_all_valuations is set to False. (optional, default is True).

Returns:

Datetime.

add_break_point(dt)

Add decision that stops all further processing.

Parameters:

dt – Stop datetime.

add_fx_spot_trade(dt: datetime, over: str, under: str, notional: float, use_trading_manager_calendar: bool = True, execution_dt: Optional[datetime] = None)

Do an FX spot trade - will pay notional in under currency minus strike amount in over currency on the same day.

Parameters:
  • dt – Reference datetime.

  • over – Over currency.

  • under – Under currency.

  • notional – Notional.

  • use_trading_manager_calendar – If true, the trading manager calendar is used.

  • execution_dt – Execution datetime (optional).

add_margin_cleanup(dt, instrument_class)

Add a process to clean up the margin at the specified datetime.

Parameters:
  • dt – Reference datetime.

  • instrument_class – Type of instrument.

See also MarginCleanupProcessor for more details.

Background

When taking on exposure to e.g. a Future, an additional Margin instrument is introduced which is always worth 1 in a given currency. It represents the cumulative strike on a future, i.e. a future bought at 95 would be represented as a buy of a Future instrument and a short position of 95 of Margin.

Example of Margin cleanup process

Day 1

Researcher seeks 50% exposure to CLZ15 COMDTY which currently trades at USD 100.00.

Order is generated which collapses into:
  • +5 units to CLZ15 COMDTY

  • -5 * 100 = USD -500.00 to USD Margin instrument

Strategy NAV: USD 1000.00

Day 2

Market for CLZ15 COMDTY moves to USD 105.00.

Position table before Margin cleanup:

Position table at start of Day 2#

Instrument

Units

Price in USD

Exposure

USD Cash

1000

1.00

1000.00

CLZ15 COMDTY

5

105.00

525.00

USD Margin

-500

1.00

-500.00

The Margin cleanup process does the following:
  • margin_real = future_units * future_price_T_2 + margin_units * price_margin_T_2 = USD 25.00

  • Add margin_real to the Cash instrument

  • Subtract margin_real from the USD Margin instrument

Position table after Margin cleanup:

Position table at start of Day 2#

Instrument

Units

Price in USD

Exposure

USD Cash

1025

1.00

1025.00

CLZ15 COMDTY

5

105.00

525.00

USD Margin

-525

1.00

-525.00

Strategy NAV: USD 1025.00

Day 3

Market for CLZ15 COMDTY moves down to USD 102.50. Researcher seeks to increase exposure to 80% based on price from Day 2.

Order is generated which collapses into:
  • +2.81 (1025 * 0.8 / 105 - 5) units to CLZ15 COMDTY

  • -2.81 * 102.5 = USD -288.03 to USD Margin instrument

Position table before Margin cleanup:

Position table at start of Day 2#

Instrument

Units

Price in USD

Exposure

USD Cash

1025

1.00

1025.00

CLZ15 COMDTY

7.81

102.50

800.53

USD Margin

-813.03

1.00

-813.03

The Margin cleanup process does the following (same as in Day 2):
  • margin_real = USD -12.50

  • Add margin_real to the Cash instrument

  • Subtract margin_real from the USD Margin instrument

Position table after Margin cleanup:

Position table at start of Day 2#

Instrument

Units

Price in USD

Exposure

USD Cash

1012.5

1.00

1012.50

CLZ15 COMDTY

7.81

102.50

800.53

USD Margin

-800.53

1.00

-800.53

Strategy NAV: USD 1012.50

add_method(dt: Union[date, datetime], method: object, *args: Any, use_trading_manager_calendar: Optional[bool] = True, priority: Optional[int] = None, **kwargs: Any) None

Add method processor.

Parameters:
  • dt – Reference datetime.

  • method – Method to add. This needs to have a time as a first input.

  • use_trading_manager_calendar – If true, the Trading manager calendar is used.

  • priority – Optional integer priority value. Lower values have a higher priority and are run first. These values should be between 41 and 89. The default method priority is 50.

add_position_directly(dt: Union[date, datetime], instrument_name: str, units: float, unit_type: Optional[str] = 'MODEL')

Add a position to the holdings directly.

Parameters:
  • dt – Reference date or datetime.

  • instrument_name – Instrument name string.

  • units – Additional relative units for allocation to instrument_name.

  • unit_type – Units used for quantity ('MODEL', 'TRADE'). Optional, if None, uses default unit type from the strategy: 'MODEL'. See Strategy for more details.

add_position_target(dt: Union[date, datetime], instrument_name: str, units: float, execution_dt: Optional[datetime] = None, size_date: Optional[Union[date, datetime]] = None, transaction_type: Optional[str] = 'outright', transaction_priority: Optional[int] = 20, payment_currency: Optional[str] = None, use_trading_manager_calendar: Optional[bool] = None, unit_type: Optional[str] = None, sizing_method: Optional[str] = None, incomplete_order_callback: Optional[Callable] = None, incomplete_order_callback_kwargs: Optional[dict] = None) None

Schedule a decision on the queue. Further downstream it triggers an order in the timeline at the decision datetime and a position entry/change at the execution datetime.

Parameters:
  • dt – decision datetime.

  • instrument_name – instrument name string.

  • units – target units for allocation to instrument_name.

  • execution_dt – desired execution datetime to achieve target weight - defaults to instrument’s valuation point - must be after decision datetime.

  • size_date – reference date used in model weight to unit calculation - always before decision datetime.

  • transaction_type – type of trade (for example outright, roll, etc.) - impacts transaction costs.

  • transaction_priority – determines priority in the decision queue if more than one decision is scheduled at the same time.

  • payment_currency – cash currency that is used to execute trade.

  • use_trading_manager_calendar – Include trading manager calendar in decision time. If not supplied, defaults to False if execution_dt is supplied as a datetime, otherwise True.

  • unit_type – Units used for quantity ('MODEL', 'TRADE', 'WEIGHT'). Optional, if None, then uses the default unit type 'MODEL'. See Strategy for more details.

  • sizing_method – Name of method of instrument or strategy to compute the size based on custom units, or a callable. Optional, None by default. See Strategy for more details.

  • incomplete_order_callback – function that will be called if the trade pricer is unable to execute the desired number of units

  • incomplete_order_callback_kwargs – additional arguments to be passed to the callback

add_trade(dt: Union[date, datetime], instrument_name: Union[str, type], units: float, execution_dt: Optional[datetime] = None, transaction_type: Optional[str] = 'outright', transaction_priority: Optional[int] = 20, payment_currency: Optional[str] = None, unit_type: Optional[str] = None, sizing_method: Optional[str] = None, use_trading_manager_calendar: Optional[bool] = None, incomplete_order_callback: Optional[Callable] = None, incomplete_order_callback_kwargs: Optional[dict] = None, **kwargs)

Schedule a decision on the queue. Further downstream it triggers an order in the timeline at the decision datetime and a position entry/change at the execution datetime.

For the keyword arguments specific to each type of OTC instrument, please call the print_add_trade_kwargs() method on the respective instrument class, e.g. FXForward.print_add_trade_kwargs().

Parameters:
  • dt – Decision datetime.

  • instrument_name – Instrument class (for OTC trading) or instrument name string.

  • units – Additional relative units for allocation to instrument_name.

  • execution_dt – Desired execution datetime to achieve target weight - defaults to instrument’s valuation point - must be after decision datetime.

  • transaction_type – Type of trade (for example outright, roll, etc.) - impacts transaction costs.

  • transaction_priority – Determines priority in the decision queue if more than one decision is scheduled at the same time.

  • payment_currency – Cash currency that is used to execute trade.

  • unit_type – Units used for quantity ('MODEL', 'TRADE', 'WEIGHT'). Optional, if None, then uses default unit type 'MODEL'. See Strategy for more details.

  • sizing_method – Name of method of instrument or strategy to compute the size based on custom units, or a callable. Optional, None by default. See Strategy for more details.

  • use_trading_manager_calendar – Include trading manager calendar in decision time. If not supplied, defaults to False if execution_dt is supplied as a datetime, otherwise True.

  • incomplete_order_callback – function that will be called if the trade pricer is unable to execute the desired number of units

  • incomplete_order_callback_kwargs – additional arguments to be passed to the callback

build(progress=False) None

Build the strategy timeline.

Parameters:

progress – Add a progress bar (default is False).

calculation_start_date()

Adjusted start date for any calculations.

calculation_start_dt()

Adjusted start dt for any calculations.

cash_weight_remaining(dt, positions)

Evaluate the remaining notional weight (assuming no leverage).

Parameters:
  • dt – Reference datetime.

  • positions – Strategy positions.

Returns:

Remaining notional weight.

clear_caches()

Clear the cached attributes and history for the strategy.

clone_object(params: dict = None)

Return a clone of the strategy with amended parameters.

Parameters:

params – New kwargs in dict format.

Returns:

Clone of the strategy with amended parameters.

clone_strategy(params: dict = None, allow_unregistered: bool = True) deprecated

Return a clone of the strategy with amended parameters (deprecated).

compare_inputs(other, keys_only=False)

Return the differences in initial settings between two strategies.

Parameters:
  • other – Strategy to compare with.

  • keys_only – Return only the keys of the different settings (optional, default is False).

Returns:

DictDiff.

direction_id_long()

String name for long direction in strategy name.

direction_id_short()

String name for short direction in strategy name.

earliest_start_date()

Earliest possible date where all dependencies can be computed.

execution_dt_from_date(instrument, d)

Return the valuation point of the instrument for the given input date. If needed, the date is adjusted forward to a valid business day for the instrument.

Parameters:
  • d – Input datetime.

  • instrument – Target instrument object to be traded.

Returns:

Datetime.

execution_dt_from_datetime(instrument, dt)

Return the earliest execution point of the instrument after the input decision datetime.

Parameters:
  • dt – Input datetime.

  • instrument – Target instrument object to be traded.

Returns:

Datetime.

expanded_section_slice(dt, section_level=1, flatten_level=100, scale_unit=1.0, separate=False)

Return a portfolio slice for a given datetime and section.

Parameters:
  • dt – Reference datetime.

  • section_level – Section level (optional, default is 1).

  • flatten_level – Flatten level (optional, default is STRATEGY_MAX_TREE_LEVEL).

  • scale_unit – Scale unit (optional, default is 1.0).

  • separate – Strategy orders can be split (optional, default is False).

Returns:

PortfolioTree.

expanded_slice(dt, level=100, order_only=False, scale_unit=1.0, separate=False)

Return an expanded portfolio slice for a given datetime and level.

Parameters:
  • dt – Reference datetime.

  • level – Reference level (optional, default is STRATEGY_MAX_TREE_LEVEL).

  • order_only – Include the orders only (optional, default is False).

  • scale_unit – Scale unit (optional, default is 1.0).

  • separate – Strategy orders can be split (optional, default is False).

Returns:

PortfolioTree.

expanded_slice_t(dt, timeline=None, level=100, order_only=False, scale_unit=1.0, separate=False)

Return an expanded portfolio slice for a given datetime, timeline and level.

Parameters:
  • dt – Reference datetime.

  • timeline – Reference timeline (optional).

  • level – Reference level (optional, default is STRATEGY_MAX_TREE_LEVEL).

  • order_only – Include the orders only (optional, default is False).

  • scale_unit – Scale unit (optional, default is 1.0).

  • separate – Strategy orders can be split (optional, default is False).

Returns:

PortfolioTree.

expanded_timeline(full_timeline=False)

Return strategy timeline - expanded.

Parameters:

full_timeline – Include the positions changes (not just the order execution points).

Returns:

Tree timeline.

get_exposure_weight(instrument, quantity, size_dt)

Evaluate the notional exposure for a specified instrument, quantity and date.

Parameters:
  • instrument – Input instrument.

  • quantity – Input quantity.

  • size_dt – Input date.

Returns:

Exposure weight.

get_weight(dt, instrument_name, positions, size_date=None, execution_dt=None)

Get the actual weight for the desired instrument.

Parameters:
  • dt – Reference datetime.

  • instrument_name – Instrument identifier.

  • positions – Strategy positions.

  • size_date – Size date for weight calculation (optional).

  • execution_dt – Execution date (optional).

Returns:

Actual weight.

history(field: str = None, adjust_for_delay: bool = False, date_index: bool = False, data_point: Optional[DataPoint] = None, datetime_index: bool = False) Series

Method to retrieve time series for objects overlaid by history schedule and publication delay (optional). If the given field does not exist, an empty series will be returned.

Parameters:
  • field – Optional - Returns time series for field - defaults to prime history field.

  • adjust_for_delay – Optional - Returns adjusted index if there is a publication delay.

  • date_index – Optional - Convert the timestamp index to dates.

  • data_point – data point to retrieve - from self.available_data_points

  • datetime_index – Optional - if True, populate the time and UTC timezone information in the index.

Returns:

pd.Series.

html_report()

Abstract method to add a custom html report to the strategy. This can be viewed when deployed.

The method should return a html string.

instrument_execution_dt_from_datetime(instrument, dt)

Return the earliest execution point of the instrument after the input decision datetime.

Parameters:
  • dt – Input datetime.

  • instrument – Target instrument object to be traded.

Returns:

Datetime.

is_total_return()

Check if this strategy is total return or excess return.

netted_trade_price(dt, trade_sign, include_trading_costs=True, transaction_type=None, currency=None)

Netted version of the trading price for this strategy on a given day.

Parameters:
  • dt – Reference datetime.

  • trade_sign – Integer/float to determine if it is a buy or sell.

  • include_trading_costs – If True will apply trading cost adjustment, otherwise ignores it.

  • transaction_type – String identifier to indicate the type of transaction, e.g. ‘outright’, ‘roll’.

  • currency – Currency string stub.

Returns:

Trade price.

push_process(process)

Add a given process to the strategy queue.

Parameters:

process – Input process.

rounded_units(units, dt, to_trade=True)

If rounding is enabled only whole strategy units can be traded.

This is to be sure that the expanded positions are all tradable regardless of later increases or closing of underlying positions.

For the instantaneous value we look at the possible rounded constituents and the maximum allowed contained position.

Note: This estimate is only an approximation since it may assume fractional holdings in positions.

For an example,

Consider a sub-strategy that holds 100 future contracts at time T. It then closes out one contract to have 99 at T+1.

A strategy wants to trade 0.01 units of this sub-strategy at T. For that instant the rounded_units can allow 0.01 units. However, if it were executed the position wouldn’t be valid at T+1.

To allow arbitrary sub-strategy behaviour only whole strategy units can be traded.

Parameters:
  • units – Number of units.

  • dt – Reference datetime.

  • to_trade – Cast the number of units to lower round (default is True).

Returns:

Rounded units.

schedule_information()

Return the schedule information for this strategy.

shaken_timeline(full_timeline=False)

Return strategy timeline - shaken.

Parameters:

full_timeline – Include the positions changes (not just the order execution points).

Returns:

Tree timeline.

short_version(use_db=True)

Short version of this strategy.

Parameters:

use_db – The strategy is loaded from a database (optional, default is True).

Returns:

Strategy.

size_dt_from_decision_dt(decision_dt)

Return the previous strategy data point to the valuation date where the decision datetime falls in.

Parameters:

decision_dt – Decision datetime.

Returns:

Datetime.

slice(dt)

Return a flat top-level slice for a given datetime.

Parameters:

dt – Reference datetime.

Returns:

Portfolio.

starting_currency()

The currency we start with in the wallet on the first day.

strategy_dt_list(dts, start_dt=None, end_dt=None, build=True, tzinfo=None, strict=False)

List of strategy datetimes.

Parameters:
  • dts – Valuation datetimes.

  • start_dt – Start datetime (optional).

  • end_dt – End datetime (optional).

  • build – Boolean flag to build the strategy first (optional, default is True).

  • tzinfo – Timezone for time display (optional, the default takes the environment’s display timezone).

  • strict – Boolean flag to raise an exception if there are no points returned (optional, default is False).

Returns:

list.

strategy_extension(from_dt: datetime, to_dt: datetime)

Update the strategy contents for an expanded history. It should be replaced if a short run’s process initialization is not equivalent to continuing the strategy.

Parameters:
  • from_dt – Start datetime for history expansion.

  • to_dt – End datetime for history expansion.

strategy_initialization(dt: datetime) None

Initial decision run on the start date of the strategy.

Parameters:

dt – Reference datetime.

strategy_order_execution_dt_from_datetime(strategy, dt)

Return the earliest execution point of the strategy after the input decision datetime.

Parameters:
  • dt – Input datetime.

  • strategy – Target strategy object to be traded.

Returns:

Datetime.

suggested_next_run_time(asof=None)

Suggested next time to run the strategy to capture the next actions.

This defaults to the next process datetime

Parameters:

asof – Input as-of-date.

Returns:

Datetime.

trade_price(trade_dt: datetime, trade_sign: float, include_trading_costs: Optional[bool] = True, transaction_type: Optional[str] = None, currency: Optional[str] = None, cache_trade_date: Optional[bool] = True) float

Traded price for a strategy.

Parameters:
  • trade_dt – Trading datetime.

  • trade_sign – Integer/float to determine if it is a buy or sell.

  • include_trading_costs – If True will apply trading cost adjustment, otherwise ignores it.

  • transaction_type – String identifier to indicate the type of transaction, e.g. ‘outright’, ‘roll’.

  • currency – Currency string stub.

  • cache_trade_date – Optional parameter to cache trading dates of instrument.

Returns:

Trade/fill price.

trade_price_override()

Mechanism to manually override trading price calculations.

tree(timeline, end_dt, full_timeline=False)

Return a tree timeline.

Parameters:
  • timeline – Input timeline.

  • end_dt – End datetime.

  • full_timeline – Include the positions changes (not just the order execution points).

Returns:

Tree timeline.

tree_slice(dt, separate=False)

Return a portfolio slice for a given datetime.

Parameters:
  • dt – Reference datetime.

  • separate – Strategy orders can be split (optional, default is False).

Returns:

PortfolioTree.

tree_timeline(full_timeline=False)

Return strategy timeline - tree.

Parameters:

full_timeline – Include the positions changes (not just the order execution points).

Returns:

Tree timeline.

valuation_price_base(dt: Union[datetime, date]) float

Return the price in base currency on a given valuation date.

Parameters:

dt – Input date/datetime.

Returns:

float.