Trade analysis¶
Analyze the trade performance of algorithm
Trade summary
Won and lost trades
Trade won/lost distribution graph
Trade timeline and analysis of individual trades made
- class tradingstrategy.analysis.tradeanalyzer.SpotTrade¶
Track spot trades to construct position performance.
For sells, quantity is negative.
- trade_id: tradingstrategy.types.PrimaryKey¶
Internal running counter to uniquely label all trades in trade analysis
- pair_id: tradingstrategy.types.PrimaryKey¶
Trading pair for this trade
- timestamp: pandas._libs.tslibs.timestamps.Timestamp¶
When this trade was made, the backtes simulation thick
- price: tradingstrategy.types.USDollarAmount¶
Asset price at buy in
- commission: tradingstrategy.types.USDollarAmount¶
How much fees we paid to the exchange
- slippage: tradingstrategy.types.USDollarAmount¶
How much we lost against the midprice due to the slippage
- hint: Optional[tradingstrategy.analysis.tradehint.TradeHint] = None¶
Any hints applied for this trade why it was performed
- state_details: Optional[Dict] = None¶
Internal state dump of the algorithm when this trade was made. This is mostly useful when doing the trade analysis try to understand why some trades were made. It also allows you to reconstruct the portfolio state over the time.
- __init__(trade_id: tradingstrategy.types.PrimaryKey, pair_id: tradingstrategy.types.PrimaryKey, timestamp: pandas._libs.tslibs.timestamps.Timestamp, price: tradingstrategy.types.USDollarAmount, quantity: float, commission: tradingstrategy.types.USDollarAmount, slippage: tradingstrategy.types.USDollarAmount, hint: Optional[tradingstrategy.analysis.tradehint.TradeHint] = None, state_details: Optional[Dict] = None) None ¶
- class tradingstrategy.analysis.tradeanalyzer.TradePosition¶
How a particular asset traded.
Each asset can have multiple entries (buys) and exits (sells)
For a simple strategies there can be only one or two trades per position.
Enter (buy)
Exit (sell optionally)
- trades: List[tradingstrategy.analysis.tradeanalyzer.SpotTrade]¶
List of all trades done for this position
- opened_at: Optional[pandas._libs.tslibs.timestamps.Timestamp] = None¶
Closing the position could be deducted from the trades themselves, but we cache it by hand to speed up processing
- closed_at: Optional[pandas._libs.tslibs.timestamps.Timestamp] = None¶
Closing the position could be deducted from the trades themselves, but we cache it by hand to speed up processing
- property position_id: tradingstrategy.types.PrimaryKey¶
Position id is the same as the opening trade id.
- property pair_id: tradingstrategy.types.PrimaryKey¶
Position id is the same as the opening trade id.
- property duration: Optional[datetime.timedelta]¶
How long this position was held.
- Returns
None if the position is still open
- property open_value: float¶
The current value of this open position, with the price at the time of opening.
- property open_price: float¶
At what price we opened this position.
Supports only simple enter/exit positions.
- get_first_entry_price() float ¶
What was the price when the first entry buy for this position was made.
- property close_price: float¶
At what price we exited this position.
Supports only simple enter/exit positions.
- property realised_profit: tradingstrategy.types.USDollarAmount¶
Calculated life-time profit over this position.
- is_win()¶
Did we win this trade.
- get_max_size() tradingstrategy.types.USDollarAmount ¶
Get the largest size of this position over the time
- class tradingstrategy.analysis.tradeanalyzer.AssetTradeHistory¶
How a particular asset traded.
Each position can have increments or decrements. When position is decreased to zero, it is considered closed, and a new buy open a new position.
- add_trade(t: tradingstrategy.analysis.tradeanalyzer.SpotTrade)¶
Adds a new trade to the asset history.
If there is an open position the trade is added against this, otherwise a new position is opened for tracking.
- class tradingstrategy.analysis.tradeanalyzer.TradeSummary¶
Some generic statistics over all the trades
- to_dataframe() pandas.core.frame.DataFrame ¶
Creates a human-readable Pandas dataframe table from the object.
- __init__(won: int, lost: int, zero_loss: int, stop_losses: int, undecided: int, realised_profit: tradingstrategy.types.USDollarAmount, open_value: tradingstrategy.types.USDollarAmount, uninvested_cash: tradingstrategy.types.USDollarAmount, initial_cash: tradingstrategy.types.USDollarAmount, extra_return: tradingstrategy.types.USDollarAmount) None ¶
- class tradingstrategy.analysis.tradeanalyzer.TradeAnalyzer¶
Analysis of trades in a portfolio.
- asset_histories: Dict[object, tradingstrategy.analysis.tradeanalyzer.AssetTradeHistory]¶
How a particular asset traded. Asset id -> Asset history mapping
- get_all_positions() Iterable[Tuple[tradingstrategy.types.PrimaryKey, tradingstrategy.analysis.tradeanalyzer.TradePosition]] ¶
Return open and closed positions over all traded assets.
- get_open_positions() Iterable[Tuple[tradingstrategy.types.PrimaryKey, tradingstrategy.analysis.tradeanalyzer.TradePosition]] ¶
Return open and closed positions over all traded assets.
- calculate_summary_statistics(initial_cash, uninvested_cash, extra_return=0) tradingstrategy.analysis.tradeanalyzer.TradeSummary ¶
Calculate some statistics how our trades went.
- create_timeline() pandas.core.frame.DataFrame ¶
Create a timeline feed how we traded over a course of time.
Note: We assume each position has only one enter and exit event, not position increases over the lifetime.
- Returns
DataFrame with timestamp and timeline_event columns
- tradingstrategy.analysis.tradeanalyzer.expand_timeline(exchange_universe: tradingstrategy.exchange.ExchangeUniverse, pair_universe: tradingstrategy.pair.PandasPairUniverse, timeline: pandas.core.frame.DataFrame, vmin=- 0.3, vmax=0.2, timestamp_format='%Y-%m-%d', hidden_columns=['Id', 'PnL % raw']) Tuple[pandas.core.frame.DataFrame, Callable] ¶
Expand trade history timeline to human readable table.
This will the outputting much easier in Python Notebooks.
Currently does not incrementing/decreasing positions gradually.
Instaqd of applying styles or returning a styled dataframe, we return a callable that applies the styles. This is because of Pandas issue https://github.com/pandas-dev/pandas/issues/40675 - hidden indexes, columns, etc. are not exported.
- Parameters
vmax – Trade success % to have the extreme green color.
vmin – The % of lost capital on the trade to have the extreme red color.
timestamp_format – How to format Opened at column, as passed to strftime()
hidden_columns – Hide columns in the output table
- Returns
DataFrame with human readable position win/loss information, having DF indexed by timestamps and a styler function