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, signals=<factory>, investable_equity=0.0)#
Parameters:
Return type:

None

Methods

__init__([timestamp, signals, investable_equity])

assign_weights([method])

Convert raw signals to their portfolio weight counterparts.

calculate_target_positions(investable_equity)

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)

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, take_profit])

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

signals

Pair internal id -> trading signal data

investable_equity

How much we can afford to invest on this cycle

timestamp: Optional[datetime]#

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

signals: Dict[int, TradingPairSignal]#

Pair internal id -> trading signal data

investable_equity: Optional[float]#

How much we can afford to invest on this cycle

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=0, take_profit=0)[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 (float) –

    Stop loss threshold for this pair.

    As the percentage of the position value.

    0.98 means 2% stop loss.

  • take_profit (float) –

    Stop loss threshold for this pair.

    As the percentage of the position value.

    1.02 means 2% take profit.

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)[source]#

Chooses top long signals.

Modifies weights in-place.

Parameters:

count (int) –

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(investable_equity)[source]#

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

Parameters:

investable_equity (float) –

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, signals=<factory>, investable_equity=0.0)#
Parameters:
Return type:

None