Engine¶
Correlation-aware risk/cash position optimizer (the "Basanos" engine).
tinycta.engine
¶
Engine for correlation-aware risk position optimization.
This module is the Polars-facing orchestration layer: :class:Engine validates and holds
the aligned prices/mu frames, derives the volatility-adjusted returns and per-timestamp
EWMA correlation matrices, and hands the resulting NumPy arrays to the pure-numeric kernel in
:mod:tinycta._kernel for the forward walk.
Engine
dataclass
¶
Correlation-aware risk position optimizer (Basanos engine).
Source code in src/tinycta/engine.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 | |
assets
property
¶
List numeric asset column names, excluding the date column.
cash_position
property
¶
Correlation-shrinkage-optimized cash positions for each timestamp.
Walks forward through time, and at each timestamp t:
- Mask assets with a finite price at
tso the optimisation only sees currently-tradable instruments. - Shrink the EWMA correlation matrix towards the identity by
cfg.shrink(via :func:~tinycta.signal.shrink2id) for numerical stability, then restrict it to the masked assets. - Solve the shrunk system for the expected returns
muand normalise byinv_a_norm(mu, matrix)so the raw risk position has unit norm under the correlation metric (zeroed when the denominator is non-finite/degenerate ormuis all-zero). - Scale the risk position by a running EWMA estimate of realised
profit variance (decay
lamb=0.99), which down-weights positions after volatile P&L, then divide by per-asset EWMA volatility (self.vola) to convert the risk position into a cash position.
The per-timestamp walk itself is delegated to
:func:tinycta._kernel.forward_walk, which operates purely on NumPy arrays.
Returns:
| Type | Description |
|---|---|
DataFrame
|
pl.DataFrame: The input |
Example
import math import polars as pl from tinycta.config import Config from tinycta.engine import Engine dates = list(range(1, 11)) prices = pl.DataFrame( ... { ... "date": dates, ... "A": [100.0, 101.5, 100.8, 102.3, 103.1, 102.0, 104.5, 105.2, 104.1, 106.0], ... "B": [50.0, 49.2, 50.4, 49.8, 51.1, 50.3, 49.5, 50.8, 51.6, 50.9], ... } ... ) mu = pl.DataFrame({"date": dates, "A": [0.1] * 10, "B": [-0.05] * 10}) engine = Engine(prices=prices, mu=mu, cfg=Config(vola=3, corr=3, clip=4.2, shrink=0.5)) positions = engine.cash_position
The frame keeps its shape and its date column; only the asset
columns are replaced:
positions.shape (10, 3) positions.columns ['date', 'A', 'B']
The leading rows are warmup and come back NaN (here cfg.corr
observations of :attr:ret_adj, which itself starts on the third row):
sum(1 for v in positions["A"] if math.isnan(v)) 4
After warmup the position takes the sign of the expected return, so a
positive mu is held long and a negative one short:
[v > 0 for v in positions["A"][4:]][True, True, True, True, True, True] [v < 0 for v in positions["B"][4:]][True, True, True, True, True, True]
cor
property
¶
Per-timestamp EWMA correlation matrices, keyed by index value.
Each key is a value of the date column (a datetime.date in normal
use, but any hashable index value such as an integer is supported, hence
the Hashable key type). Each value is the EWMA covariance matrix at
that timestamp normalised to a correlation matrix (unit diagonal).
Contract
- Warmup: the first
cfg.corr + 1timestamps are omitted — a key exists only once at least one matrix cell is finite (see :func:~tinycta.ewm_cov.ewm_covariance). That takescfg.corrobservations of :attr:ret_adj, which itself starts on the third row becausevol_adjneeds two log returns to standardise one. - NaN cells: a cell is
NaNwhile either asset is still in its own warmup, and a zero-variance asset (outer == 0) yieldsNaNcorrelations rather than a divide-by-zero.
Example
import math import polars as pl from tinycta.config import Config from tinycta.engine import Engine dates = list(range(1, 11)) prices = pl.DataFrame( ... { ... "date": dates, ... "A": [100.0, 101.5, 100.8, 102.3, 103.1, 102.0, 104.5, 105.2, 104.1, 106.0], ... "B": [50.0, 49.2, 50.4, 49.8, 51.1, 50.3, 49.5, 50.8, 51.6, 50.9], ... } ... ) mu = pl.DataFrame({"date": dates, "A": [0.1] * 10, "B": [-0.05] * 10}) cfg = Config(vola=3, corr=3, clip=4.2, shrink=0.5) cor = Engine(prices=prices, mu=mu, cfg=cfg).cor
The first cfg.corr + 1 timestamps are omitted, so the mapping is
keyed by the surviving dates rather than by position:
sorted(cor) [5, 6, 7, 8, 9, 10]
Each value is a correlation matrix with a unit diagonal:
mat = cor[5] mat.shape (2, 2) [round(float(v), 6) for v in mat.diagonal()][1.0, 1.0] bool(-1.0 <= mat[0, 1] <= 1.0) True
A zero-variance asset yields NaN rather than a divide-by-zero. Here
B never moves, so every cell touching it is NaN while A keeps
its unit diagonal:
flat = prices.with_columns(pl.lit(50.0).alias("B")) flat_cor = Engine(prices=flat, mu=mu, cfg=cfg).cor[5] math.isnan(flat_cor[1, 1]), math.isnan(flat_cor[0, 1]) (True, True) round(float(flat_cor[0, 0]), 6) 1.0
ret_adj
property
¶
Per-asset EWMA-volatility-adjusted log returns clipped by cfg.clip.
vola
property
¶
Per-asset EWMA volatility of percentage returns.
__post_init__()
¶
Validate that prices and mu are aligned and both contain a date column.