AlphaModel#

tradeexecutor.strategy.alpha_model.AlphaModel Python class in Trading Strategy framework.

class AlphaModel[source]#

Bases: object

Capture alpha model state for one strategy cycle.

  • A helper class for portfolio construction models and such

  • Converts portfolio weightings to rebalancing trades

  • Supports stop loss and passing through other trade execution parameters

  • Each strategy cycle creates its own AlphaModel instance in decide_trades() function of the strategy

  • Stores the intermediate results of the calculationsn between raw weights and the final investment amount

  • We are serializable as JSON, so we can pass the calculations as data around in tradeexecutor.state.visualisation.Visualisation.calculations and then later visualise alph model progress over time with other analytic diagrams

__init__(timestamp=None, raw_signals=<factory>, signals=<factory>, investable_equity=0.0, close_position_weight_epsilon=0.005)#
Parameters:
Return type:

None

Methods

__init__([timestamp, raw_signals, signals, ...])

assign_weights([method])

Convert raw signals to their portfolio weight counterparts.

calculate_target_positions(position_manager, ...)

Calculate individual dollar amount for each position based on its normalised weight.

calculate_weight_diffs()

Calculate how much % asset weight has changed between strategy cycles.

from_dict(kvs, *[, infer_missing])

from_json(s, *[, parse_float, parse_int, ...])

generate_rebalance_trades_and_triggers(...)

Generate the trades that will rebalance the portfolio.

get_debug_print()

Present the alpha model in a format suitable for the console.

get_signal_by_pair(pair)

Get a trading pair signal instance for one pair.

get_signal_by_pair_id(pair_id)

Get a trading pair signal instance for one pair.

get_signals_sorted_by_weight()

Get the signals sorted by the weight.

iterate_signals()

Iterate over all recorded signals.

normalise_weights()

schema(*[, infer_missing, only, exclude, ...])

select_top_signals(count[, threshold])

Chooses top long signals.

set_old_weight(pair, old_weight, old_value)

Set the weights for the8 current portfolio trading positions before rebalance.

set_signal(pair, alpha[, stop_loss, ...])

Set trading pair alpha to a value.

to_dict([encode_json])

to_json(*[, skipkeys, ensure_ascii, ...])

update_old_weights(portfolio)

Update the old weights of the last strategy cycle to the alpha model.

Attributes

timestamp

Timestamp of the strategy cycle for which this alpha model was calculated

raw_signals

Calculated signals for all trading pairs.

signals

The chosen top signals.

investable_equity

How much we can afford to invest on this cycle

close_position_weight_epsilon

Determine the lower threshold for a position weight.

override_stop_loss

Allow set_signal() to override stop loss set for the position earlier

timestamp: Optional[datetime]#

Timestamp of the strategy cycle for which this alpha model was calculated

raw_signals: Dict[int, TradingPairSignal]#

Calculated signals for all trading pairs.

Pair internal id -> trading signal data.

For all trading pairs in the model.

Set by set_signal()

signals: Dict[int, TradingPairSignal]#

The chosen top signals.

Pair internal id -> trading signal data.

For signals chosen for the rebalance, e.g. top 5 long signals.

Set by select_top_signals()

investable_equity: Optional[float]#

How much we can afford to invest on this cycle

close_position_weight_epsilon: float#

Determine the lower threshold for a position weight.

Clean up “dust” by explicitly closing positions if they fall too small.

If position weight is less than 0.5% always close it

override_stop_loss = False#

Allow set_signal() to override stop loss set for the position earlier

iterate_signals()[source]#

Iterate over all recorded signals.

Return type:

Iterable[TradingPairSignal]

get_signal_by_pair_id(pair_id)[source]#

Get a trading pair signal instance for one pair.

Use integer id lookup.

Parameters:

pair_id (int) –

Return type:

Optional[TradingPairSignal]

get_signal_by_pair(pair)[source]#

Get a trading pair signal instance for one pair.

Use verbose TradingPairIdentifier lookup.

Parameters:

pair (TradingPairIdentifier) –

Return type:

Optional[TradingPairSignal]

get_signals_sorted_by_weight()[source]#

Get the signals sorted by the weight.

Return the highest weight first.

Return type:

Iterable[TradingPairSignal]

get_debug_print()[source]#

Present the alpha model in a format suitable for the console.

Return type:

str

set_signal(pair, alpha, stop_loss=None, take_profit=None, trailing_stop_loss=None)[source]#

Set trading pair alpha to a value.

If called repeatatle for the same trading pair, remember the last value.

Parameters:
  • pair (TradingPairIdentifier) – Trading pair

  • alpha (float | numpy.float32) –

    How much alpha signal this trading pair carries.

    Set to zero to have the pair excluded out after a risk assessment

  • stop_loss (Optional[float]) –

    Stop loss threshold for this pair.

    As the percentage of the position value.

    0.98 means 2% stop loss.

  • take_profit (Optional[float]) –

    Stop loss threshold for this pair.

    As the percentage of the position value.

    1.02 means 2% take profit.

  • trailing_stop_loss (Optional[float]) –

    Trailing stop loss threshold for this pair.

    As the percentage of the position value.

    0.98 means 2% trailing stop loss.

set_old_weight(pair, old_weight, old_value)[source]#

Set the weights for the8 current portfolio trading positions before rebalance.

Parameters:
select_top_signals(count, threshold=0.0)[source]#

Chooses top long signals.

Sets signals attribute of the model

Example:

alpha_model.select_top_signals(
    count=5,  # Pick top 5 trading pairs
    threshold=0.01,  # Need at least 1% signal certainty to be eligible
)
Parameters:
  • count (int) – How many signals to pick

  • threshold

    If the raw signal value is lower than this threshold then don’t pick the signal.

    Inclusive.

    0.01 = 1% signal strenght.

assign_weights(method=<function weight_by_1_slash_n>)[source]#

Convert raw signals to their portfolio weight counterparts.

Update TradingPairSignal.raw_weight attribute to our target trading pairs.

Parameters:

method – What method we use to convert a trading signal to a portfolio weights

update_old_weights(portfolio)[source]#

Update the old weights of the last strategy cycle to the alpha model.

  • Update % of portfolio weight of an asset

  • Update USD portfolio value of an asset

Parameters:

portfolio (Portfolio) –

calculate_weight_diffs()[source]#

Calculate how much % asset weight has changed between strategy cycles.

Returns:

Pair id, weight delta dict

Return type:

Dict[int, float]

calculate_target_positions(position_manager, investable_equity)[source]#

Calculate individual dollar amount for each position based on its normalised weight.

Parameters:
generate_rebalance_trades_and_triggers(position_manager, min_trade_threshold=10.0)[source]#

Generate the trades that will rebalance the portfolio.

This will generate

  • Sells for the existing assets

  • Buys for new assets or assets where we want to increase our position

  • Set up take profit/stop loss triggers for positions

Parameters:
  • position_manager (PositionManager) – Portfolio of our existing holdings

  • min_trade_threshold (float) –

    Threshold for too small trades.

    If the notional value of a rebalance trade is smaller than this USD amount don’t make a trade, but keep whatever position we currently we have.

    This is to prevent doing too small trades due to fuzziness in the valuations and calculations.

Returns:

List of trades we need to execute to reach the target portfolio. The sells are sorted always before buys.

Return type:

List[TradeExecution]

__init__(timestamp=None, raw_signals=<factory>, signals=<factory>, investable_equity=0.0, close_position_weight_epsilon=0.005)#
Parameters:
Return type:

None