|
| 1 | +--- |
| 2 | +sidebar_position: 3 |
| 3 | +--- |
| 4 | + |
| 5 | +# Recording Custom Variables |
| 6 | + |
| 7 | +During backtesting you often want to track custom indicators, metrics, or signals alongside your trades — for example an RSI value, a moving average, or a custom score. The `record()` API lets you store **any** key-value pair at each backtest iteration so you can analyse it after the run completes. |
| 8 | + |
| 9 | +Recorded values are stored on the `BacktestRun` object and fully support serialization (save & load). |
| 10 | + |
| 11 | +## Event-Driven Backtests |
| 12 | + |
| 13 | +In an event-driven backtest your strategy's `on_run` method receives a `context` object. Call `context.record()` with arbitrary keyword arguments: |
| 14 | + |
| 15 | +```python |
| 16 | +from investing_algorithm_framework import TradingStrategy, TimeUnit |
| 17 | + |
| 18 | +class MyStrategy(TradingStrategy): |
| 19 | + time_unit = TimeUnit.DAY |
| 20 | + interval = 1 |
| 21 | + symbols = ["BTC"] |
| 22 | + |
| 23 | + def on_run(self, context, data): |
| 24 | + ohlcv = data["BTC/EUR_1d"] |
| 25 | + close = ohlcv["Close"] |
| 26 | + |
| 27 | + # Compute any indicator you like |
| 28 | + sma_20 = close.rolling(20).mean().iloc[-1] |
| 29 | + rsi = compute_rsi(close).iloc[-1] |
| 30 | + |
| 31 | + # Record them — keys can be anything |
| 32 | + context.record( |
| 33 | + sma_20=sma_20, |
| 34 | + rsi=rsi, |
| 35 | + signal_strength=0.85, |
| 36 | + ) |
| 37 | +``` |
| 38 | + |
| 39 | +Each call stores the values together with the current backtest timestamp. You can call `record()` multiple times per iteration — values are appended. |
| 40 | + |
| 41 | +:::tip |
| 42 | +`context.record()` is a **no-op** in live mode, so you can leave the calls in your production strategy without any overhead. |
| 43 | +::: |
| 44 | + |
| 45 | +## Vectorized Backtests |
| 46 | + |
| 47 | +Vectorized backtests don't use a `context` object. Instead, override `generate_recorded_values()` on your strategy and return a dictionary of `pandas.Series`: |
| 48 | + |
| 49 | +```python |
| 50 | +import pandas as pd |
| 51 | +from investing_algorithm_framework import TradingStrategy |
| 52 | + |
| 53 | +class MyVectorStrategy(TradingStrategy): |
| 54 | + symbols = ["BTC"] |
| 55 | + |
| 56 | + def generate_buy_signals(self, data): |
| 57 | + # ... your buy logic ... |
| 58 | + pass |
| 59 | + |
| 60 | + def generate_sell_signals(self, data): |
| 61 | + # ... your sell logic ... |
| 62 | + pass |
| 63 | + |
| 64 | + def generate_recorded_values(self, data): |
| 65 | + ohlcv = data["BTC/EUR_1d"] |
| 66 | + close = ohlcv["Close"] |
| 67 | + |
| 68 | + return { |
| 69 | + "sma_20": close.rolling(20).mean(), |
| 70 | + "rsi": compute_rsi(close), |
| 71 | + } |
| 72 | +``` |
| 73 | + |
| 74 | +Each key becomes a recorded variable with the Series index as timestamps. |
| 75 | + |
| 76 | +## Accessing Recorded Values |
| 77 | + |
| 78 | +After a backtest completes the recorded values are available on the `BacktestRun`: |
| 79 | + |
| 80 | +```python |
| 81 | +from investing_algorithm_framework import create_app |
| 82 | + |
| 83 | +app = create_app() |
| 84 | +# ... configure app, add strategy, data sources ... |
| 85 | + |
| 86 | +backtest = app.run_backtest() |
| 87 | +run = backtest.backtest_runs[0] |
| 88 | + |
| 89 | +# Dict[str, List[Tuple[datetime, Any]]] |
| 90 | +print(run.recorded_values) |
| 91 | + |
| 92 | +# Example: extract RSI time series |
| 93 | +for dt, value in run.recorded_values["rsi"]: |
| 94 | + print(f"{dt}: RSI = {value}") |
| 95 | +``` |
| 96 | + |
| 97 | +### Converting to a DataFrame |
| 98 | + |
| 99 | +You can easily convert recorded values into a pandas DataFrame for plotting or further analysis: |
| 100 | + |
| 101 | +```python |
| 102 | +import pandas as pd |
| 103 | + |
| 104 | +rsi_series = pd.Series( |
| 105 | + {dt: val for dt, val in run.recorded_values["rsi"]} |
| 106 | +) |
| 107 | +sma_series = pd.Series( |
| 108 | + {dt: val for dt, val in run.recorded_values["sma_20"]} |
| 109 | +) |
| 110 | + |
| 111 | +df = pd.DataFrame({"rsi": rsi_series, "sma_20": sma_series}) |
| 112 | +print(df) |
| 113 | +``` |
| 114 | + |
| 115 | +## Serialization |
| 116 | + |
| 117 | +Recorded values are included when you save and load a `BacktestRun`: |
| 118 | + |
| 119 | +```python |
| 120 | +# Save |
| 121 | +run.save("/path/to/output") |
| 122 | + |
| 123 | +# Load |
| 124 | +from investing_algorithm_framework import BacktestRun |
| 125 | +loaded = BacktestRun.open("/path/to/output") |
| 126 | +print(loaded.recorded_values) |
| 127 | +``` |
| 128 | + |
| 129 | +The values are stored in the `run.json` file under the `recorded_values` key. |
| 130 | + |
| 131 | +## Supported Value Types |
| 132 | + |
| 133 | +You can record any JSON-serializable value: |
| 134 | + |
| 135 | +| Type | Example | |
| 136 | +|------|---------| |
| 137 | +| `float` | `context.record(rsi=70.5)` | |
| 138 | +| `int` | `context.record(signal=1)` | |
| 139 | +| `str` | `context.record(regime="bullish")` | |
| 140 | +| `dict` | `context.record(meta={"score": 0.9})` | |
| 141 | +| `list` | `context.record(weights=[0.3, 0.7])` | |
| 142 | +| `bool` | `context.record(is_trending=True)` | |
0 commit comments