python-synthetica 0.1.4__tar.gz → 0.4.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- python_synthetica-0.4.0/PKG-INFO +1444 -0
- python_synthetica-0.4.0/README.md +1428 -0
- python_synthetica-0.4.0/pyproject.toml +43 -0
- python_synthetica-0.4.0/synthetica/__init__.py +77 -0
- python_synthetica-0.4.0/synthetica/base.py +504 -0
- {python_synthetica-0.1.4 → python_synthetica-0.4.0}/synthetica/models.py +510 -423
- python_synthetica-0.4.0/synthetica/plot.py +341 -0
- python_synthetica-0.4.0/synthetica/regimes.py +241 -0
- python_synthetica-0.4.0/synthetica/stats.py +200 -0
- python_synthetica-0.1.4/PKG-INFO +0 -270
- python_synthetica-0.1.4/README.md +0 -251
- python_synthetica-0.1.4/pyproject.toml +0 -19
- python_synthetica-0.1.4/synthetica/__init__.py +0 -29
- python_synthetica-0.1.4/synthetica/base.py +0 -330
- python_synthetica-0.1.4/synthetica/stats.py +0 -92
- {python_synthetica-0.1.4 → python_synthetica-0.4.0}/LICENSE +0 -0
- {python_synthetica-0.1.4 → python_synthetica-0.4.0}/synthetica/config.py +0 -0
- {python_synthetica-0.1.4 → python_synthetica-0.4.0}/synthetica/decorators.py +0 -0
|
@@ -0,0 +1,1444 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: python-synthetica
|
|
3
|
+
Version: 0.4.0
|
|
4
|
+
Summary: Generate synthetic time series data.
|
|
5
|
+
Author: ActurialCapital
|
|
6
|
+
License-Expression: BSD-3-Clause
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Dist: numpy>=1.26.4
|
|
9
|
+
Requires-Dist: pandas>=2.2.2
|
|
10
|
+
Requires-Dist: scipy>=1.13.1
|
|
11
|
+
Requires-Dist: plotly>=6.1 ; extra == 'plot'
|
|
12
|
+
Requires-Python: >=3.11
|
|
13
|
+
Project-URL: Repository, https://github.com/ActurialCapital/synthetica
|
|
14
|
+
Provides-Extra: plot
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
<p align="center"><img src="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/logo.png" alt="synthetica" width="90%"></p>
|
|
18
|
+
|
|
19
|
+
| Overview | |
|
|
20
|
+
|---|---|
|
|
21
|
+
| **Open Source** | [](https://github.com/ActurialCapital/synthetica/blob/main/LICENSE) |
|
|
22
|
+
| **Code** | [](https://pypi.org/project/python-synthetica/) [](https://www.python.org/) |
|
|
23
|
+
| **CI/CD** | [](https://codecov.io/gh/ActurialCapital/synthetica) |
|
|
24
|
+
| **Downloads** |   [)](https://pepy.tech/project/python-synthetica) |
|
|
25
|
+
|
|
26
|
+
**synthetica** generates synthetic time series: prices, rates and signals from fifteen stochastic
|
|
27
|
+
models, with seeds that reproduce exactly, dependence across paths from a correlation matrix or
|
|
28
|
+
any vine copula, legs cointegrated with a known half-life, regimes that switch between models and their
|
|
29
|
+
dependence, and OHLC bars around the closes. Use it
|
|
30
|
+
to test trading and forecasting code on data whose true properties you know.
|
|
31
|
+
|
|
32
|
+
Each model takes an exact step where the maths allows it (GBM, Merton, Seasonal, Ornstein–Uhlenbeck) and a
|
|
33
|
+
published low-bias scheme where it does not (Heston, CIR), and each has a property test that checks
|
|
34
|
+
it against its closed form.
|
|
35
|
+
|
|
36
|
+
**Contents:** [Installation](#installation) · [Quick start](#quick-start) ·
|
|
37
|
+
[How it works](#how-it-works) · [Models](#models) · [Dependence across paths](#dependence-across-paths) ·
|
|
38
|
+
[Cointegration](#cointegration) · [OHLC bars](#ohlc-bars) · [Regimes](#regimes) · [Charts](#charts) · [Reproducibility](#reproducibility) ·
|
|
39
|
+
[Testing](#testing) · [Contributing](#contributing) · [License](#license)
|
|
40
|
+
|
|
41
|
+
## Installation
|
|
42
|
+
|
|
43
|
+
```sh
|
|
44
|
+
pip install python-synthetica
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Python 3.11 or later, with numpy ≥ 1.26.4, pandas ≥ 2.2.2 and scipy ≥ 1.13.1. Copulas take any
|
|
48
|
+
copula object; [pyvinecopulib](https://github.com/vinecopulib/pyvinecopulib)'s work as they are
|
|
49
|
+
(`pip install pyvinecopulib`). Charts need plotly: `pip install "python-synthetica[plot]"`.
|
|
50
|
+
|
|
51
|
+
## Quick start
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
import synthetica as sth
|
|
55
|
+
|
|
56
|
+
model = sth.GeometricBrownianMotion(length=252, num_paths=5, seed=42)
|
|
57
|
+
prices = model.transform()
|
|
58
|
+
prices.sth.paths(labels=True) # the chart below (pip install "python-synthetica[plot]")
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
`transform()` returns a pandas DataFrame with one row per step and one column per path
|
|
62
|
+
(`path_1` … `path_5`), indexed by daily dates that end today. With one path it returns a Series.
|
|
63
|
+
Pass a `pd.DatetimeIndex` as `length` to choose the dates yourself. Every model works the same
|
|
64
|
+
way: build it with its parameters and a `seed`, then call `transform()`.
|
|
65
|
+
|
|
66
|
+
<picture>
|
|
67
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/quickstart-dark.svg">
|
|
68
|
+
<img alt="Five GBM price paths over one year from 100, three in colour and two in grey; path_2 ends near 118, path_5 near 97" src="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/quickstart-light.svg" width="100%">
|
|
69
|
+
</picture>
|
|
70
|
+
|
|
71
|
+
Five paths at the defaults (drift μ = 5.8% and volatility σ = 12.5% a year), each starting from 100.
|
|
72
|
+
Drawn with `prices.sth.paths(labels=True)`.
|
|
73
|
+
|
|
74
|
+
## How it works
|
|
75
|
+
|
|
76
|
+
```mermaid
|
|
77
|
+
flowchart TD
|
|
78
|
+
seed(["seed"])
|
|
79
|
+
seed --> s0["stream 0: white noise<br/>cached in model.white_noise"]
|
|
80
|
+
seed --> s2["stream 2: copula draws"]
|
|
81
|
+
seed --> s1["stream 1: the model's own draws<br/>variance shocks,<br/>stable draws, inputs"]
|
|
82
|
+
seed --> s3["stream 3: the cycle"]
|
|
83
|
+
seed --> s4["stream 4: the jumps"]
|
|
84
|
+
seed --> s5["stream 5: OHLC bars<br/>stream 8: around a session jump"]
|
|
85
|
+
seed --> s6["stream 6: the regime chain<br/>stream 7: each regime's seed"]
|
|
86
|
+
s0 -- "default" --> ind["independent shocks"]
|
|
87
|
+
s0 -- "matrix=" --> chol["Cholesky factor:<br/>Gaussian dependence"]
|
|
88
|
+
s2 -- "copula=" --> cop["any copula: its sample(n, seeds),<br/>then the inverse normal CDF"]
|
|
89
|
+
ind --> step["the model's step"]
|
|
90
|
+
chol --> step
|
|
91
|
+
cop --> step
|
|
92
|
+
s1 --> step
|
|
93
|
+
s3 --> step
|
|
94
|
+
s4 --> step
|
|
95
|
+
s6 -- "Regimes" --> step
|
|
96
|
+
step --> out["prices from 100, or levels"]
|
|
97
|
+
out -- "ohlc=" --> bars["open, high, low<br/>around the closes"]
|
|
98
|
+
s5 --> bars
|
|
99
|
+
out --> pdx["pandas Series or DataFrame<br/>indexed by dates"]
|
|
100
|
+
bars --> pdx
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Every random number comes from `seed`, split into nine independent numpy streams, so the draws of
|
|
104
|
+
one stream never shift another's. Stream 0 is the white noise, normal with mean `mean` and standard
|
|
105
|
+
deviation `sigma * sqrt(delta)`, drawn once and cached in `model.white_noise`; stream 1 holds each
|
|
106
|
+
model's own draws (Heston's shocks, the stable draws, NARMA's inputs); stream 2 feeds a copula;
|
|
107
|
+
stream 3 drives the cycle and stream 4 the jumps, in every model that has them, stream 5 the
|
|
108
|
+
OHLC bars (stream 8 the bars around a session jump), and in `Regimes` stream 6 the regime chain and
|
|
109
|
+
stream 7 each regime's model's seed. Across paths the
|
|
110
|
+
noise is independent by default; `matrix` mixes it with its Cholesky factor (around `mean`, so each
|
|
111
|
+
path keeps its mean and scale), and `copula` replaces it with the copula's draws, mapped through the
|
|
112
|
+
inverse normal CDF to the same mean and scale. Each model then runs its own step on that noise: the
|
|
113
|
+
price models return prices that start from 100 (from `start_value` for `Heston` and the models built
|
|
114
|
+
on it), and `MeanReverting`, `CIR`, `AutoRegressive` and `NARMA` return levels.
|
|
115
|
+
`Heston`, `LevyStable` and `NARMA` draw their shocks, and their copula draws, from stream 1 and
|
|
116
|
+
apply `matrix` or `copula` in their own way, which their sections describe.
|
|
117
|
+
|
|
118
|
+
## Models
|
|
119
|
+
|
|
120
|
+
| Model | Simulates | Returns | Main parameters |
|
|
121
|
+
|---|---|---|---|
|
|
122
|
+
| [`GeometricBrownianMotion`](#gbm) | prices with a constant drift and volatility | prices from 100 | `mu`, `sigma` |
|
|
123
|
+
| [`Heston`](#heston) | prices whose variance is random and mean-reverting | prices from `start_value`, and `variance` | `rf`, `kappa`, `theta`, `nu`, `rho`, `vol0` |
|
|
124
|
+
| [`Merton`](#merton) | prices with random jumps | prices from 100 | `mu`, `sigma`, `lmbda`, `jump_mu`, `var` |
|
|
125
|
+
| [`LevyStable`](#levy) | prices with heavy-tailed, α-stable returns | prices from 100 | `alpha`, `beta`, `sigma` |
|
|
126
|
+
| [`Seasonal`](#seasonal) | prices around a fixed season, the same every year | prices from 100 | `mu`, `sigma`, `amplitude`, `omega`, `peak` |
|
|
127
|
+
| [`Cyclical`](#cyclical) | prices around random cycles of variable length | prices from 100, and `cycle` | `mu`, `sigma`, `amplitude`, `period`, `halflife` |
|
|
128
|
+
| [`Bates`](#bates) | Heston's random volatility with Merton's jumps | prices from `start_value`, and `variance` | Heston's, and `lmbda`, `jump_mu`, `var` |
|
|
129
|
+
| [`SeasonalHeston`](#seasonal-heston) | Heston's random volatility around a fixed season | prices from `start_value`, and `variance` | Heston's, and `amplitude`, `omega`, `peak` |
|
|
130
|
+
| [`CyclicalHeston`](#cyclical-heston) | Heston's random volatility around random cycles | prices from `start_value`, `variance` and `cycle` | Heston's, and `amplitude`, `period`, `halflife` |
|
|
131
|
+
| [`SeasonalMerton`](#seasonal-merton) | Merton's jumps around a fixed season | prices from 100 | Merton's, and `amplitude`, `omega`, `peak` |
|
|
132
|
+
| [`CyclicalMerton`](#cyclical-merton) | Merton's jumps around random cycles | prices from 100, and `cycle` | Merton's, and `amplitude`, `period`, `halflife` |
|
|
133
|
+
| [`MeanReverting`](#ou) | a level pulled back to μ (Ornstein–Uhlenbeck) | levels | `mu`, `kappa`, `sigma` |
|
|
134
|
+
| [`CIR`](#cir) | a rate pulled back to μ that never goes below zero | rates ≥ 0 | `mu`, `kappa`, `sigma` |
|
|
135
|
+
| [`AutoRegressive`](#ar) | an autoregressive signal of any order | levels | `ar` |
|
|
136
|
+
| [`NARMA`](#narma) | a nonlinear benchmark signal driven by random inputs | levels | `n`, `a`, `stabilize` |
|
|
137
|
+
|
|
138
|
+
Every model takes `length` (a number of steps or a `pd.DatetimeIndex`), `num_paths` and `seed`, and
|
|
139
|
+
`transform(matrix=None, copula=None)` returns a DataFrame with one column per path, or a Series for
|
|
140
|
+
one path. The first row is one step after the start. `Regimes` switches between the price models
|
|
141
|
+
over time: see [Regimes](#regimes).
|
|
142
|
+
|
|
143
|
+
<a name="gbm"></a>
|
|
144
|
+
|
|
145
|
+
### Geometric Brownian motion · `GeometricBrownianMotion`
|
|
146
|
+
|
|
147
|
+
Prices whose log returns are independent and normal, with a constant drift and volatility: the
|
|
148
|
+
Black-Scholes model. It has no fat tails, no volatility clustering and no jumps, which makes it the
|
|
149
|
+
baseline to test a strategy against and the base the other price models build on.
|
|
150
|
+
|
|
151
|
+
```math
|
|
152
|
+
dS_t = \mu S_t\,dt + \sigma S_t\,dW_t
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
What the code does each step (exact for any step size, Δ = `delta`):
|
|
156
|
+
|
|
157
|
+
```math
|
|
158
|
+
S_k = S_{k-1}\exp\!\Big(\text{mean} + \big(\mu - \tfrac{1}{2}\sigma^2\big)\Delta + \sigma\sqrt{\Delta}\,Z_k\Big),\qquad Z_k \sim N(0, 1),\quad S_0 = 100
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
| Parameter | Meaning | Default |
|
|
162
|
+
|---|---|---|
|
|
163
|
+
| `mu` | drift, per year: $E[S_t] = S_0e^{\mu t}$ | `0.058` |
|
|
164
|
+
| `sigma` | volatility of the log returns, per year | `0.125` |
|
|
165
|
+
| `delta` | step length, in years (1/252 is one trading day) | `1/252` |
|
|
166
|
+
| `mean` | constant added to every log return; keep 0 for a pure GBM | `0` |
|
|
167
|
+
|
|
168
|
+
```python
|
|
169
|
+
import numpy as np
|
|
170
|
+
import synthetica as sth
|
|
171
|
+
|
|
172
|
+
gbm = sth.GeometricBrownianMotion(length=252, num_paths=400, mu=0.08, sigma=0.2, seed=7)
|
|
173
|
+
prices = gbm.transform() # 252 x 400 DataFrame; row 0 is one step after S0 = 100
|
|
174
|
+
t = np.arange(1, 253) / 252 # each row's time, in years
|
|
175
|
+
prices.sth.fan(mean=100 * np.exp(0.08 * t)) # the chart below: the exact mean S0 exp(mu t)
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
<picture>
|
|
179
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/gbm-dark.svg">
|
|
180
|
+
<img alt="Fan of 400 GBM price paths over one year: a 5 to 95 percent band, the median, six thin sample paths and the exact mean rising at mu" src="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/gbm-light.svg" width="100%">
|
|
181
|
+
</picture>
|
|
182
|
+
|
|
183
|
+
The band holds the middle 90% of 400 paths; the median grows at μ − σ²/2 and stays below the mean,
|
|
184
|
+
which grows at μ. Drawn with `prices.sth.fan(mean=100 * np.exp(0.08 * t))`.
|
|
185
|
+
**Tested:** `test_gbm_moments` checks on 4,000 paths that the log returns have mean
|
|
186
|
+
$(\mu - \sigma^2/2)\Delta$ and variance $\sigma^2\Delta$ and that $S_T/S_0$ averages $e^{\mu T}$, and
|
|
187
|
+
`test_gbm` checks that the log returns pass a Shapiro-Wilk normality test.
|
|
188
|
+
|
|
189
|
+
<a name="heston"></a>
|
|
190
|
+
|
|
191
|
+
### Heston stochastic volatility · `Heston`
|
|
192
|
+
|
|
193
|
+
Prices whose variance is itself random: it reverts to a long-run level, and its shocks are
|
|
194
|
+
correlated with the price shocks. This gives volatility clustering and fat-tailed returns, which GBM
|
|
195
|
+
lacks. Use it when a strategy's results depend on calm and volatile regimes.
|
|
196
|
+
|
|
197
|
+
```math
|
|
198
|
+
\begin{aligned}
|
|
199
|
+
dS_t &= r\,S_t\,dt + \sqrt{v_t}\,S_t\,dW^S_t \\
|
|
200
|
+
dv_t &= \kappa\,(\theta - v_t)\,dt + \nu\sqrt{v_t}\,dW^v_t, \qquad dW^S_t\,dW^v_t = \rho\,dt
|
|
201
|
+
\end{aligned}
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
What the code does each step (Euler with full truncation for the variance, Lord et al. (2010), and a
|
|
205
|
+
log-Euler step for the price, Δ = `delta`):
|
|
206
|
+
|
|
207
|
+
```math
|
|
208
|
+
\begin{aligned}
|
|
209
|
+
v^+ &= \max(v_{k-1}, 0) \\
|
|
210
|
+
S_k &= S_{k-1}\exp\!\Big(\big(r - \tfrac{1}{2}v^+\big)\Delta + \sqrt{v^+\Delta}\,Z^S_k\Big) \\
|
|
211
|
+
v_k &= v_{k-1} + \kappa\,(\theta - v^+)\,\Delta + \nu\sqrt{v^+\Delta}\,Z^v_k, \qquad \operatorname{corr}(Z^S_k, Z^v_k) = \rho
|
|
212
|
+
\end{aligned}
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
The variance $v_k$ may go below zero inside the recursion; only its positive part $v^+$ enters the
|
|
216
|
+
drift and the diffusion, so the next step pulls it back up. At the defaults
|
|
217
|
+
$2\kappa\theta = 0.24 < \nu^2 = 0.36$ (the Feller condition fails), so the variance does reach zero,
|
|
218
|
+
and on those steps the return is exactly $r\Delta$ with no shock. After `transform`, the `variance`
|
|
219
|
+
attribute holds the variance behind each step's return, $v^+$, with 0 where it hit zero.
|
|
220
|
+
|
|
221
|
+
| Parameter | Meaning | Default |
|
|
222
|
+
|---|---|---|
|
|
223
|
+
| `rf` | $r$, the drift of the price, per year: prices are risk-neutral, $E[S_T] = S_0e^{rT}$ | `0.02` |
|
|
224
|
+
| `kappa` | $\kappa$, speed at which the variance reverts to `theta`, per year | `3` |
|
|
225
|
+
| `theta` | $\theta$, long-run variance (a variance: 0.20² is 20% volatility) | `0.20**2` |
|
|
226
|
+
| `nu` | $\nu$, volatility of the variance | `0.6` |
|
|
227
|
+
| `rho` | $\rho$, correlation of the price and variance shocks (equity data usually gives ρ < 0) | `0.7` |
|
|
228
|
+
| `vol0` | $v_0$, starting variance (a variance, not a volatility) | `0.25**2` |
|
|
229
|
+
| `start_value` | $S_0$, starting price | `100.0` |
|
|
230
|
+
| `delta` | step length, in years | `1/252` |
|
|
231
|
+
| `mean`, `sigma` | accepted for a common signature, not used by this model | `0`, `0.125` |
|
|
232
|
+
|
|
233
|
+
`transform(matrix=...)` correlates both the price and the variance shocks across paths.
|
|
234
|
+
`transform(copula=...)` drives only the price shocks $Z^S$ across paths; each variance shock keeps
|
|
235
|
+
its correlation ρ with its own price shock. The returns are $\sqrt{v^+\Delta}\,Z^S$ plus drift, so
|
|
236
|
+
their own dependence is weaker than the copula's (Kendall's τ about 0.08 lower at the defaults).
|
|
237
|
+
`(return - (rf - variance / 2) * delta) / sqrt(variance * delta)` gives the shocks back, which carry
|
|
238
|
+
the copula exactly; skip the steps where `variance` is 0.
|
|
239
|
+
|
|
240
|
+
```python
|
|
241
|
+
import synthetica as sth
|
|
242
|
+
|
|
243
|
+
h = sth.Heston(length=504, num_paths=5, seed=4) # default parameters
|
|
244
|
+
prices = h.transform()
|
|
245
|
+
variance = h.variance # the variance behind each step's return, 0 where it hit zero
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
<picture>
|
|
249
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/heston-dark.svg">
|
|
250
|
+
<img alt="Two stacked panels over two years: five Heston price paths, and below their variance, which swings from zero to five times its long-run level" src="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/heston-light.svg" width="100%">
|
|
251
|
+
</picture>
|
|
252
|
+
|
|
253
|
+
The variance reverts to θ = 0.04 but swings from zero to five times θ, and each path's sits at zero
|
|
254
|
+
on some steps (from 1 to 20 of them), where its price moves only by the drift. Drawn with
|
|
255
|
+
`prices.sth.paths(model=h)`, which adds the model's `variance` below.
|
|
256
|
+
**Tested:** `test_heston_martingale_and_variance` checks, with ν = 1 so the variance hits zero often,
|
|
257
|
+
that $E[S_T] = S_0e^{rT}$ and that the summed squared log returns match
|
|
258
|
+
$\theta T + (v_0 - \theta)(1 - e^{-\kappa T})/\kappa$, and `test_copula_own_innovations` checks that
|
|
259
|
+
the recovered price shocks carry the copula's Kendall's τ.
|
|
260
|
+
|
|
261
|
+
<a name="merton"></a>
|
|
262
|
+
|
|
263
|
+
### Merton jump diffusion · `Merton`
|
|
264
|
+
|
|
265
|
+
GBM plus jumps: at random times the log price jumps by a normally distributed amount. Returns get fat
|
|
266
|
+
tails and gaps that a diffusion cannot produce. Use it to test a strategy against sudden moves, such
|
|
267
|
+
as a stop that cannot fill at its level.
|
|
268
|
+
|
|
269
|
+
```math
|
|
270
|
+
\begin{aligned}
|
|
271
|
+
\frac{dS_t}{S_{t^-}} &= (\mu - \lambda\bar{k})\,dt + \sigma\,dW_t + d\Big(\sum_{j=1}^{N_t}(Y_j - 1)\Big) \\
|
|
272
|
+
N_t &\sim \text{Poisson}(\lambda t), \qquad \log Y_j \sim N(\mu_J, v_J), \qquad \bar{k} = e^{\mu_J + v_J/2} - 1
|
|
273
|
+
\end{aligned}
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
What the code does each step (exact on the time grid, Glasserman (2004), §3.5.1, Δ = `delta`):
|
|
277
|
+
|
|
278
|
+
```math
|
|
279
|
+
\begin{aligned}
|
|
280
|
+
N_k &\sim \text{Poisson}(\lambda\Delta), \qquad J_k = N_k\,\mu_J + \sqrt{N_k\,v_J}\;Z^J_k \\
|
|
281
|
+
S_k &= S_{k-1}\exp\!\Big(\text{mean} + \big(\mu - \tfrac{1}{2}\sigma^2 - \lambda\bar{k}\big)\Delta + \sigma\sqrt{\Delta}\,Z_k + J_k\Big),\qquad S_0 = 100
|
|
282
|
+
\end{aligned}
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
$N_k$ normal jumps sum to one normal with mean $N_k\mu_J$ and variance $N_kv_J$, so one draw covers
|
|
286
|
+
every jump in the step. The term $-\lambda\bar{k}$ compensates the jumps, so $E[S_T] = S_0e^{\mu T}$
|
|
287
|
+
whatever the jump parameters; with negative jumps, the drift between jumps is above μ.
|
|
288
|
+
|
|
289
|
+
| Parameter | Meaning | Default |
|
|
290
|
+
|---|---|---|
|
|
291
|
+
| `mu` | drift, per year: $E[S_T] = S_0e^{\mu T}$, jumps included | `0.058` |
|
|
292
|
+
| `sigma` | volatility of the diffusion part, per year | `0.125` |
|
|
293
|
+
| `lmbda` | $\lambda$, expected number of jumps per unit of time (per year when `delta` is 1/252) | `1.0` |
|
|
294
|
+
| `jump_mu` | $\mu_J$, mean jump size, in log | `-0.05` |
|
|
295
|
+
| `var` | $v_J$, variance of the jump size, in log (0.01 is a 10% standard deviation) | `0.01` |
|
|
296
|
+
| `delta` | step length, in years | `1/252` |
|
|
297
|
+
| `mean` | constant added to every log return; keep 0 | `0` |
|
|
298
|
+
|
|
299
|
+
```python
|
|
300
|
+
import synthetica as sth
|
|
301
|
+
|
|
302
|
+
kw = dict(length=756, mu=0.08, sigma=0.15, seed=1)
|
|
303
|
+
model = sth.Merton(lmbda=4, jump_mu=-0.06, var=0.03**2, **kw)
|
|
304
|
+
merton = model.transform()
|
|
305
|
+
gbm = sth.GeometricBrownianMotion(**kw).transform() # same seed: the same diffusion shocks
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
<picture>
|
|
309
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/merton-dark.svg">
|
|
310
|
+
<img alt="One Merton price path over three years with its twelve jumps marked as dots: the price drops at most of them and climbs between them" src="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/merton-light.svg" width="100%">
|
|
311
|
+
</picture>
|
|
312
|
+
|
|
313
|
+
The dots are the path's twelve jumps, as many as it expects in three years; between them it climbs
|
|
314
|
+
faster than μ, because its drift carries $-\lambda\bar{k} \approx$ +23% a year to pay for them. Drawn
|
|
315
|
+
with `merton.sth.paths(model=model)`, which marks the model's `jumps`.
|
|
316
|
+
**Tested:** `test_merton_moments` checks, with λ = 25 jumps a year, that $E[S_T] = S_0e^{\mu T}$ and
|
|
317
|
+
that the per-step variance is $\sigma^2\Delta + \lambda\Delta(\mu_J^2 + v_J)$, and `test_merton`
|
|
318
|
+
checks that the log returns have fat tails: excess kurtosis above 10, where GBM's is 0.1.
|
|
319
|
+
|
|
320
|
+
<a name="levy"></a>
|
|
321
|
+
|
|
322
|
+
### Lévy stable · `LevyStable`
|
|
323
|
+
|
|
324
|
+
Prices whose log returns are α-stable: heavy-tailed, and with infinite variance when α < 2, so a
|
|
325
|
+
single day can move the price by tens of percent. α = 2 is the normal case, and a lower α gives
|
|
326
|
+
fatter tails. Use it to test a strategy against crashes and jumps that a normal model treats as
|
|
327
|
+
impossible.
|
|
328
|
+
|
|
329
|
+
```math
|
|
330
|
+
S_t = S_0\, e^{L_t}, \qquad L_{t+\Delta} - L_t \sim \mathrm{Stable}\big(\alpha,\ \beta,\ \text{scale } \sigma\,\Delta^{1/\alpha}\big),\ \text{independent of the past}
|
|
331
|
+
```
|
|
332
|
+
|
|
333
|
+
What the code does each step (exact draws from scipy's `levy_stable` in its S1 parameterization, Δ = `delta`):
|
|
334
|
+
|
|
335
|
+
```math
|
|
336
|
+
r_k \sim \mathrm{Stable}_{S1}\big(\alpha,\ \beta,\ \text{loc} = \text{mean},\ \text{scale} = \sigma\,\Delta^{1/\alpha}\big), \qquad S_k = 100\,\exp\Big(\sum_{j=1}^{k} r_j\Big)
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
A step's scale grows as Δ^(1/α), not √Δ, because a stable process is self-similar with index 1/α.
|
|
340
|
+
With α = 2 a step is normal with standard deviation σ√(2Δ), so `sigma` is not GBM's volatility.
|
|
341
|
+
Prices are the exponential of the summed returns, so one extreme draw multiplies the price by
|
|
342
|
+
e^r: with a small α or a large σ, prices can reach extreme values, even 0 or infinity in floating point.
|
|
343
|
+
|
|
344
|
+
`transform(matrix=...)` and `transform(copula=...)` make the paths dependent by rank reordering
|
|
345
|
+
(Iman–Conover). Each path keeps its own stable draws, put in the order of the ranks of correlated
|
|
346
|
+
normals or of the copula's draws, so every path stays exactly iid stable: with the same seed, a
|
|
347
|
+
path holds the same values with or without dependence, only in a different order. With α < 2 the
|
|
348
|
+
variance is infinite, so a matrix cannot set a linear correlation; it sets a Gaussian copula,
|
|
349
|
+
with Kendall's τ = (2/π) arcsin ρ.
|
|
350
|
+
|
|
351
|
+
| Parameter | Meaning | Default |
|
|
352
|
+
|---|---|---|
|
|
353
|
+
| `mean` | location of each step's log return, per step (its mean when α > 1) | `0` |
|
|
354
|
+
| `delta` | time step Δ (years) | `1/252` |
|
|
355
|
+
| `sigma` | scale per unit of time; a step has scale σΔ^(1/α) | `0.125` |
|
|
356
|
+
| `alpha` | stability index in (0, 2]: lower means heavier tails, 2 is normal | `1.68` |
|
|
357
|
+
| `beta` | skewness in [−1, 1]; 0 is symmetric | `0.01` |
|
|
358
|
+
|
|
359
|
+
```python
|
|
360
|
+
import numpy as np
|
|
361
|
+
import synthetica as sth
|
|
362
|
+
|
|
363
|
+
prices = sth.LevyStable(20_000, alpha=1.7, seed=2).transform()
|
|
364
|
+
returns = np.log(prices).diff()
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
<picture>
|
|
368
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/levy-dark.svg">
|
|
369
|
+
<img alt="Share of 20,000 Lévy stable daily log returns larger than x, on a log scale, against a normal with the same median and interquartile range: the Lévy curve declines slowly as a power law while the normal curve falls off a cliff before x reaches 3%" src="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/levy-light.svg" width="100%">
|
|
370
|
+
</picture>
|
|
371
|
+
|
|
372
|
+
The share of days with a move larger than x falls like a power law for Lévy returns and drops off
|
|
373
|
+
a cliff for a normal with the same median and interquartile range: beyond 5%, about 1 day in 170
|
|
374
|
+
against 1 in 3 trillion, and the largest Lévy move is 40%. Drawn with `prices.sth.tails()`.
|
|
375
|
+
**Tested:** each path's log returns match the stable quantiles for scale σΔ^(1/α) within five
|
|
376
|
+
standard errors, and a correlation matrix ρ gives Kendall's τ = (2/π) arcsin ρ between paths.
|
|
377
|
+
|
|
378
|
+
<a name="seasonal"></a>
|
|
379
|
+
|
|
380
|
+
### Seasonal GBM · `Seasonal`
|
|
381
|
+
|
|
382
|
+
Prices that follow a GBM around a fixed seasonal cycle: the same high and low season every year,
|
|
383
|
+
on every path, like gas prices that peak each winter. The drift and the noise are a GBM's; the
|
|
384
|
+
season moves the price above and below that trend. Use it to test a strategy that must not mistake
|
|
385
|
+
a calendar pattern for a signal, or one that trades the season.
|
|
386
|
+
|
|
387
|
+
```math
|
|
388
|
+
\log S_t = \log S_0 + \big(\mu - \tfrac{1}{2}\sigma^2\big)t + \sigma W_t + A\big(\cos(2\pi\omega(t - \text{peak})) - \cos(2\pi\omega\,\text{peak})\big)
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
What the code does each step (exact, Δ = `delta`, $t_k = k\Delta$):
|
|
392
|
+
|
|
393
|
+
```math
|
|
394
|
+
\log S_k = \log S_{k-1} + \text{mean} + \big(\mu - \tfrac{1}{2}\sigma^2\big)\Delta + \sigma\sqrt{\Delta}\,Z_k + A\big(\cos(2\pi\omega(t_k - \text{peak})) - \cos(2\pi\omega(t_{k-1} - \text{peak}))\big),\qquad S_0 = 100
|
|
395
|
+
```
|
|
396
|
+
|
|
397
|
+
The season is a known curve, so the step is exact, and the mean is the trend times a seasonal factor:
|
|
398
|
+
$E[S_t] = S_0e^{\mu t}e^{A(\cos(2\pi\omega(t - \text{peak})) - \cos(2\pi\omega\,\text{peak}))}$. The season is measured
|
|
399
|
+
from where the series starts: with `peak = 0` the series starts at its high and the mean stays below
|
|
400
|
+
the trend, while a `peak` a quarter of a cycle in starts it mid-season and the mean swings evenly
|
|
401
|
+
around the trend.
|
|
402
|
+
|
|
403
|
+
| Parameter | Meaning | Default |
|
|
404
|
+
|---|---|---|
|
|
405
|
+
| `mu` | drift, per year: the trend the season moves around | `0.058` |
|
|
406
|
+
| `sigma` | volatility of the log price, per year | `0.125` |
|
|
407
|
+
| `amplitude` | $A$, the seasonal swing of the log price (0.1 is about ±10%) | `0.1` |
|
|
408
|
+
| `omega` | $\omega$, seasonal cycles per unit of time: 1 is annual, 4 quarterly | `1.0` |
|
|
409
|
+
| `peak` | when in the cycle the season is highest, in units of time from the start | `0.0` |
|
|
410
|
+
| `delta` | step length, in years | `1/252` |
|
|
411
|
+
| `mean` | constant added to every log return; keep 0 | `0` |
|
|
412
|
+
|
|
413
|
+
```python
|
|
414
|
+
import synthetica as sth
|
|
415
|
+
|
|
416
|
+
model = sth.Seasonal(756, 400, mu=0.05, sigma=0.15, amplitude=0.15, omega=1.0, peak=0.25, seed=3)
|
|
417
|
+
prices = model.transform()
|
|
418
|
+
```
|
|
419
|
+
|
|
420
|
+
<picture>
|
|
421
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/seasonal-dark.svg">
|
|
422
|
+
<img alt="A band of 400 seasonal GBM price paths over three years, with the exact mean and the median rising and falling every year" src="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/seasonal-light.svg" width="100%">
|
|
423
|
+
</picture>
|
|
424
|
+
|
|
425
|
+
The exact mean (orange) peaks at the same time every year, around a GBM trend of 5% a year; the band
|
|
426
|
+
holds the middle 90% of 400 paths. Drawn with `prices.sth.fan(mean=...)`, the mean from the formula
|
|
427
|
+
above.
|
|
428
|
+
**Tested:** on 20,000 paths, the mean price matches $E[S_t]$ above at five dates through the cycle.
|
|
429
|
+
|
|
430
|
+
<a name="cyclical"></a>
|
|
431
|
+
|
|
432
|
+
### Cyclical GBM · `Cyclical`
|
|
433
|
+
|
|
434
|
+
Prices that follow a GBM around a random cycle: booms and busts that last about `period` years, but
|
|
435
|
+
each cycle differs in length and size, and each path has its own timing, like a business or a credit
|
|
436
|
+
cycle. Unlike `Seasonal`, nothing repeats exactly. Use it to test a strategy across regimes that come
|
|
437
|
+
back without a fixed calendar.
|
|
438
|
+
|
|
439
|
+
```math
|
|
440
|
+
\log S_t = \log S_0 + \big(\mu - \tfrac{1}{2}\sigma^2\big)t + \sigma W_t + c_t - c_0 - A^2\big(1 - \rho^{k}\cos(\lambda k)\big),\qquad k = t/\Delta
|
|
441
|
+
```
|
|
442
|
+
|
|
443
|
+
The cycle $c_t$ is Harvey's (1989) stochastic cycle, the one statsmodels' `UnobservedComponents` uses.
|
|
444
|
+
What the code does each step, with $\lambda = 2\pi\Delta/\text{period}$, $\rho = 2^{-\Delta/\text{halflife}}$ and two
|
|
445
|
+
independent shocks $\kappa_k, \kappa^*_k \sim N(0, A^2(1 - \rho^2))$:
|
|
446
|
+
|
|
447
|
+
```math
|
|
448
|
+
\begin{pmatrix} c_k \\ c^*_k \end{pmatrix} = \rho \begin{pmatrix} \cos\lambda & \sin\lambda \\ -\sin\lambda & \cos\lambda \end{pmatrix} \begin{pmatrix} c_{k-1} \\ c^*_{k-1} \end{pmatrix} + \begin{pmatrix} \kappa_k \\ \kappa^*_k \end{pmatrix}
|
|
449
|
+
```
|
|
450
|
+
|
|
451
|
+
Each step turns the pair by the angle λ, so a full turn takes `period`, and shrinks it by ρ, so a
|
|
452
|
+
cycle's shape fades over `halflife` while the shocks keep new cycles coming. The cycle starts from its
|
|
453
|
+
long-run law, so each path has its own phase and size; it has standard deviation $A$ and
|
|
454
|
+
autocorrelation $\rho^k\cos(\lambda k)$ at a lag of k steps. The last term of the log price takes out the
|
|
455
|
+
cycle's lift on the mean, so $E[S_t] = S_0e^{\mu t}$ as in a GBM. After `transform`, the `cycle`
|
|
456
|
+
attribute holds $c_k$ behind each row. `matrix` and `copula` tie the GBM shocks across paths; the
|
|
457
|
+
cycles stay independent.
|
|
458
|
+
|
|
459
|
+
| Parameter | Meaning | Default |
|
|
460
|
+
|---|---|---|
|
|
461
|
+
| `mu` | drift, per year: $E[S_t] = S_0e^{\mu t}$ | `0.058` |
|
|
462
|
+
| `sigma` | volatility of the GBM part, per year | `0.125` |
|
|
463
|
+
| `amplitude` | $A$, the cycle's typical size in log price (its standard deviation) | `0.15` |
|
|
464
|
+
| `period` | the typical length of one cycle, in years | `4.0` |
|
|
465
|
+
| `halflife` | how long a cycle keeps its shape, in years: long gives regular cycles, short irregular ones | `3.0` |
|
|
466
|
+
| `delta` | step length, in years | `1/252` |
|
|
467
|
+
| `mean` | constant added to every log return; keep 0 | `0` |
|
|
468
|
+
|
|
469
|
+
```python
|
|
470
|
+
import synthetica as sth
|
|
471
|
+
|
|
472
|
+
model = sth.Cyclical(12 * 252, 3, mu=0.05, sigma=0.12, amplitude=0.2, period=4.0, halflife=4.0, seed=8)
|
|
473
|
+
prices = model.transform()
|
|
474
|
+
cycle = model.cycle # the cycle behind each row, in log price
|
|
475
|
+
```
|
|
476
|
+
|
|
477
|
+
<picture>
|
|
478
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/cyclical-dark.svg">
|
|
479
|
+
<img alt="Two stacked panels over twelve years: three cyclical GBM price paths, and below their cycles, each lasting about four years with its own timing and size" src="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/cyclical-light.svg" width="100%">
|
|
480
|
+
</picture>
|
|
481
|
+
|
|
482
|
+
Three paths over 12 years: their cycles last about four years, each with its own timing and size,
|
|
483
|
+
and the prices carry them on top of the trend. Drawn with `model.transform().sth.paths(model=model)`,
|
|
484
|
+
which adds the model's `cycle` below.
|
|
485
|
+
**Tested:** on 2,000 paths, the cycle's standard deviation is `amplitude`, its autocorrelation is
|
|
486
|
+
$\rho^k\cos(\lambda k)$ at a quarter, one and two years, and the mean price is $S_0e^{\mu t}$.
|
|
487
|
+
|
|
488
|
+
<a name="bates"></a>
|
|
489
|
+
|
|
490
|
+
### Bates stochastic volatility with jumps · `Bates`
|
|
491
|
+
|
|
492
|
+
Heston's prices with Merton's jumps ([Bates, 1996](https://doi.org/10.1093/rfs/9.1.69)): volatility
|
|
493
|
+
that clusters and sudden gaps, the two features equity returns show together. Use it to test a
|
|
494
|
+
strategy against calm and volatile stretches and crashes at once.
|
|
495
|
+
|
|
496
|
+
```math
|
|
497
|
+
\begin{aligned}
|
|
498
|
+
\frac{dS_t}{S_{t^-}} &= (r - \lambda\bar{k})\,dt + \sqrt{v_t}\,dW^S_t + d\Big(\sum_{j=1}^{N_t}(Y_j - 1)\Big) \\
|
|
499
|
+
dv_t &= \kappa\,(\theta - v_t)\,dt + \nu\sqrt{v_t}\,dW^v_t, \qquad dW^S_t\,dW^v_t = \rho\,dt
|
|
500
|
+
\end{aligned}
|
|
501
|
+
```
|
|
502
|
+
|
|
503
|
+
What the code does each step: Heston's step, plus Merton's compensated jump (Δ = `delta`):
|
|
504
|
+
|
|
505
|
+
```math
|
|
506
|
+
\log S_k = \log S_{k-1} + \big(r - \tfrac{1}{2}v^+\big)\Delta + \sqrt{v^+\Delta}\,Z^S_k + J_k - \lambda\bar{k}\Delta
|
|
507
|
+
```
|
|
508
|
+
|
|
509
|
+
with $v^+$ and $Z^S_k$ as in [Heston](#heston) and $J_k$, $\bar{k}$ as in [Merton](#merton). The jumps
|
|
510
|
+
are compensated, so $E[S_T] = S_0e^{rT}$ whatever the jump parameters.
|
|
511
|
+
|
|
512
|
+
It takes Heston's parameters (`rf`, `kappa`, `theta`, `nu`, `rho`, `vol0`, `start_value`, by position or
|
|
513
|
+
keyword) and Merton's jumps as keywords:
|
|
514
|
+
|
|
515
|
+
| Parameter | Meaning | Default |
|
|
516
|
+
|---|---|---|
|
|
517
|
+
| `lmbda` | $\lambda$, expected number of jumps per year | `1.0` |
|
|
518
|
+
| `jump_mu` | $\mu_J$, mean jump size, in log | `-0.05` |
|
|
519
|
+
| `var` | $v_J$, variance of the jump size, in log | `0.01` |
|
|
520
|
+
|
|
521
|
+
`variance` holds Heston's variance behind each step. `matrix` and `copula` tie the price shocks
|
|
522
|
+
across paths, as in Heston; the jumps stay independent. With one seed, `Bates` is `Heston`'s path
|
|
523
|
+
with `Merton`'s jumps.
|
|
524
|
+
|
|
525
|
+
```python
|
|
526
|
+
import synthetica as sth
|
|
527
|
+
|
|
528
|
+
kw = dict(length=756, num_paths=2, rho=-0.7, seed=2)
|
|
529
|
+
model = sth.Bates(lmbda=4, jump_mu=-0.06, var=0.03**2, **kw)
|
|
530
|
+
bates = model.transform()
|
|
531
|
+
heston = sth.Heston(**kw).transform() # same seed: the same paths without the jumps
|
|
532
|
+
```
|
|
533
|
+
|
|
534
|
+
<picture>
|
|
535
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/bates-dark.svg">
|
|
536
|
+
<img alt="Two stacked panels over three years: two Bates price paths with their jumps marked as dots, ten each, and below their variance, which swings from zero to five times its long-run level" src="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/bates-light.svg" width="100%">
|
|
537
|
+
</picture>
|
|
538
|
+
|
|
539
|
+
The dots are each path's ten jumps, as many as λ = 4 a year gives in three years; the variance below
|
|
540
|
+
swings from zero to five times θ, and the paths end far apart (75 and 137). Drawn with
|
|
541
|
+
`bates.sth.paths(model=model)`.
|
|
542
|
+
**Tested:** `test_bates_mean` checks, with 25 jumps a year, that $E[S_T] = S_0e^{rT}$, and
|
|
543
|
+
`test_combined_models` that `Bates / Heston` equals `Merton / GeometricBrownianMotion` path by path
|
|
544
|
+
with one seed.
|
|
545
|
+
|
|
546
|
+
<a name="seasonal-heston"></a>
|
|
547
|
+
|
|
548
|
+
### Seasonal Heston · `SeasonalHeston`
|
|
549
|
+
|
|
550
|
+
Heston's random volatility around Seasonal's fixed season: the same high and low season every year,
|
|
551
|
+
with volatility that comes in bursts. Use it for seasonal markets whose volatility clusters, such
|
|
552
|
+
as energy.
|
|
553
|
+
|
|
554
|
+
```math
|
|
555
|
+
\log S_k = \log H_k + A\big(\cos(2\pi\omega(t_k - \text{peak})) - \cos(2\pi\omega\,\text{peak})\big)
|
|
556
|
+
```
|
|
557
|
+
|
|
558
|
+
with $H_k$ Heston's price for the same seed and the season as in [Seasonal](#seasonal). The season
|
|
559
|
+
is not random, so $E[S_t] = S_0e^{rt}$ times the seasonal factor.
|
|
560
|
+
|
|
561
|
+
It takes Heston's parameters, by position or keyword, and Seasonal's as keywords:
|
|
562
|
+
|
|
563
|
+
| Parameter | Meaning | Default |
|
|
564
|
+
|---|---|---|
|
|
565
|
+
| `amplitude` | $A$, the seasonal swing of the log price | `0.1` |
|
|
566
|
+
| `omega` | $\omega$, seasonal cycles per year | `1.0` |
|
|
567
|
+
| `peak` | when in the cycle the season is highest, in years from the start | `0.0` |
|
|
568
|
+
|
|
569
|
+
`variance` holds Heston's variance; `matrix` and `copula` act as in Heston.
|
|
570
|
+
|
|
571
|
+
```python
|
|
572
|
+
import synthetica as sth
|
|
573
|
+
|
|
574
|
+
model = sth.SeasonalHeston(756, 400, rho=-0.7, amplitude=0.15, peak=0.25, seed=3)
|
|
575
|
+
prices = model.transform()
|
|
576
|
+
variance = model.variance
|
|
577
|
+
```
|
|
578
|
+
|
|
579
|
+
<picture>
|
|
580
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/seasonal-heston-dark.svg">
|
|
581
|
+
<img alt="A band of 400 seasonal Heston price paths over three years with the exact mean peaking every year" src="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/seasonal-heston-light.svg" width="100%">
|
|
582
|
+
</picture>
|
|
583
|
+
|
|
584
|
+
The exact mean (orange) peaks every year around Heston's trend $S_0e^{rt}$, and the band holds the
|
|
585
|
+
middle 90% of 400 paths. Drawn with `prices.sth.fan(mean=...)`.
|
|
586
|
+
**Tested:** `test_combined_models` checks that `SeasonalHeston / Heston` equals
|
|
587
|
+
`Seasonal / GeometricBrownianMotion` path by path with one seed.
|
|
588
|
+
|
|
589
|
+
<a name="cyclical-heston"></a>
|
|
590
|
+
|
|
591
|
+
### Cyclical Heston · `CyclicalHeston`
|
|
592
|
+
|
|
593
|
+
Heston's random volatility around Cyclical's random cycle: booms and busts of about `period` years,
|
|
594
|
+
each path with its own timing and size, and volatility that clusters. Use it to test a strategy
|
|
595
|
+
across business cycles whose calm and volatile stretches do not follow the cycle.
|
|
596
|
+
|
|
597
|
+
```math
|
|
598
|
+
\log S_k = \log H_k + c_k - c_0 - A^2\big(1 - \varrho^{k}\cos(\lambda k)\big)
|
|
599
|
+
```
|
|
600
|
+
|
|
601
|
+
with $H_k$ Heston's price for the same seed and $c_k$ the cycle as in [Cyclical](#cyclical), whose
|
|
602
|
+
damping is written $\varrho = 2^{-\Delta/\text{halflife}}$ here to keep $\rho$ for Heston. The cycle's
|
|
603
|
+
lift is taken out, so $E[S_t] = S_0e^{rt}$.
|
|
604
|
+
|
|
605
|
+
It takes Heston's parameters, by position or keyword, and Cyclical's as keywords:
|
|
606
|
+
|
|
607
|
+
| Parameter | Meaning | Default |
|
|
608
|
+
|---|---|---|
|
|
609
|
+
| `amplitude` | $A$, the cycle's typical size in log price | `0.15` |
|
|
610
|
+
| `period` | the typical length of one cycle, in years | `4.0` |
|
|
611
|
+
| `halflife` | how long a cycle keeps its shape, in years | `3.0` |
|
|
612
|
+
|
|
613
|
+
`variance` holds Heston's variance and `cycle` the cycle behind each row. `matrix` and `copula` tie
|
|
614
|
+
the price shocks across paths; the cycles stay independent.
|
|
615
|
+
|
|
616
|
+
```python
|
|
617
|
+
import synthetica as sth
|
|
618
|
+
|
|
619
|
+
model = sth.CyclicalHeston(12 * 252, 3, rho=-0.7, amplitude=0.2, period=4.0, halflife=4.0, seed=8)
|
|
620
|
+
prices = model.transform()
|
|
621
|
+
cycle, variance = model.cycle, model.variance
|
|
622
|
+
```
|
|
623
|
+
|
|
624
|
+
<picture>
|
|
625
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/cyclical-heston-dark.svg">
|
|
626
|
+
<img alt="Three stacked panels over twelve years: three cyclical Heston price paths, each path's own variance in bursts, and their cycles of about four years" src="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/cyclical-heston-light.svg" width="100%">
|
|
627
|
+
</picture>
|
|
628
|
+
|
|
629
|
+
Three paths over 12 years: each has its own variance (middle), in bursts up to 0.2–0.28, and its own
|
|
630
|
+
cycle of about four years (bottom), so the paths end far apart, from 75 to 384. Drawn with
|
|
631
|
+
`model.transform().sth.paths(model=model)`, which adds the model's `variance` and `cycle`.
|
|
632
|
+
**Tested:** `test_combined_models` checks that `CyclicalHeston / Heston` equals
|
|
633
|
+
`Cyclical / GeometricBrownianMotion` path by path with one seed (the same cycle).
|
|
634
|
+
|
|
635
|
+
<a name="seasonal-merton"></a>
|
|
636
|
+
|
|
637
|
+
### Seasonal Merton · `SeasonalMerton`
|
|
638
|
+
|
|
639
|
+
Merton's jumps around Seasonal's fixed season: a seasonal price that can gap. Use it to test a
|
|
640
|
+
seasonal strategy against sudden moves, such as a stop that cannot fill at its level.
|
|
641
|
+
|
|
642
|
+
```math
|
|
643
|
+
\log S_k = \log M_k + A\big(\cos(2\pi\omega(t_k - \text{peak})) - \cos(2\pi\omega\,\text{peak})\big)
|
|
644
|
+
```
|
|
645
|
+
|
|
646
|
+
with $M_k$ Merton's price for the same seed. The jumps are compensated and the season is not
|
|
647
|
+
random, so $E[S_t] = 100\,e^{\mu t}$ times the seasonal factor.
|
|
648
|
+
|
|
649
|
+
It takes Merton's parameters (`mu`, `sigma`, `lmbda`, `jump_mu`, `var`, by position or keyword) and
|
|
650
|
+
Seasonal's `amplitude`, `omega` and `peak` as keywords, with Seasonal's defaults.
|
|
651
|
+
|
|
652
|
+
```python
|
|
653
|
+
import synthetica as sth
|
|
654
|
+
|
|
655
|
+
model = sth.SeasonalMerton(756, 2, mu=0.05, sigma=0.15, lmbda=4, jump_mu=-0.06, var=0.03**2,
|
|
656
|
+
amplitude=0.15, peak=0.25, seed=3)
|
|
657
|
+
prices = model.transform()
|
|
658
|
+
```
|
|
659
|
+
|
|
660
|
+
<picture>
|
|
661
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/seasonal-merton-dark.svg">
|
|
662
|
+
<img alt="Two seasonal Merton price paths over three years that peak every year and drop at their jumps, marked as dots" src="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/seasonal-merton-light.svg" width="100%">
|
|
663
|
+
</picture>
|
|
664
|
+
|
|
665
|
+
Both paths rise and fall with the season every year and drop at their jumps (15 and 12 in three
|
|
666
|
+
years, dots), climbing a little faster between them. Drawn with
|
|
667
|
+
`model.transform().sth.paths(model=model)`.
|
|
668
|
+
**Tested:** `test_combined_models` checks that `SeasonalMerton / Merton` equals
|
|
669
|
+
`Seasonal / GeometricBrownianMotion` path by path with one seed.
|
|
670
|
+
|
|
671
|
+
<a name="cyclical-merton"></a>
|
|
672
|
+
|
|
673
|
+
### Cyclical Merton · `CyclicalMerton`
|
|
674
|
+
|
|
675
|
+
Merton's jumps around Cyclical's random cycle: business cycles with crashes. Use it to test a
|
|
676
|
+
strategy across cycles of variable length when single days can gap.
|
|
677
|
+
|
|
678
|
+
```math
|
|
679
|
+
\log S_k = \log M_k + c_k - c_0 - A^2\big(1 - \varrho^{k}\cos(\lambda k)\big)
|
|
680
|
+
```
|
|
681
|
+
|
|
682
|
+
with $M_k$ Merton's price for the same seed and $c_k$ the cycle as in [Cyclical](#cyclical). The
|
|
683
|
+
jumps are compensated and the cycle's lift is taken out, so $E[S_t] = 100\,e^{\mu t}$.
|
|
684
|
+
|
|
685
|
+
It takes Merton's parameters, by position or keyword, and Cyclical's `amplitude`, `period` and
|
|
686
|
+
`halflife` as keywords, with Cyclical's defaults. `cycle` holds the cycle behind each row; `matrix`
|
|
687
|
+
and `copula` tie the diffusion shocks across paths, and the jumps and cycles stay independent.
|
|
688
|
+
|
|
689
|
+
```python
|
|
690
|
+
import synthetica as sth
|
|
691
|
+
|
|
692
|
+
model = sth.CyclicalMerton(12 * 252, 3, mu=0.05, sigma=0.12, lmbda=1, jump_mu=-0.1, var=0.03**2,
|
|
693
|
+
amplitude=0.2, period=4.0, halflife=4.0, seed=8)
|
|
694
|
+
prices, cycle = model.transform(), model.cycle
|
|
695
|
+
```
|
|
696
|
+
|
|
697
|
+
<picture>
|
|
698
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/cyclical-merton-dark.svg">
|
|
699
|
+
<img alt="Two stacked panels over twelve years: three cyclical Merton price paths with their jumps marked as dots, about one a year each, and below their cycles of about four years" src="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/cyclical-merton-light.svg" width="100%">
|
|
700
|
+
</picture>
|
|
701
|
+
|
|
702
|
+
Each path has its own cycle (below) and about one jump a year (11, 11 and 10 in 12 years, dots),
|
|
703
|
+
each about −10%. Drawn with `model.transform().sth.paths(model=model)`.
|
|
704
|
+
**Tested:** `test_combined_models` checks that `CyclicalMerton / Merton` equals
|
|
705
|
+
`Cyclical / GeometricBrownianMotion` path by path with one seed.
|
|
706
|
+
|
|
707
|
+
<a name="ou"></a>
|
|
708
|
+
|
|
709
|
+
### Ornstein–Uhlenbeck · `MeanReverting`
|
|
710
|
+
|
|
711
|
+
A level pulled back to μ at speed κ: the further it strays, the harder the pull. Its values are
|
|
712
|
+
Gaussian and can go negative. Use it for spreads, a basis or any quantity that reverts to a known
|
|
713
|
+
level. It is also available as `sth.OrnsteinUhlenbeck` and `sth.CAR`.
|
|
714
|
+
|
|
715
|
+
```math
|
|
716
|
+
dX_t = \kappa\,(\mu - X_t)\,dt + \sigma\, dW_t
|
|
717
|
+
```
|
|
718
|
+
|
|
719
|
+
What the code does each step (exact, Δ = `delta`, $\varepsilon_k \sim N(0, 1)$, $X_0$ = `start_value`):
|
|
720
|
+
|
|
721
|
+
```math
|
|
722
|
+
X_k = \mu + (X_{k-1} - \mu)\,e^{-\kappa\Delta} + \sigma\sqrt{\frac{-\operatorname{expm1}(-2\kappa\Delta)}{2\kappa}}\;\varepsilon_k
|
|
723
|
+
```
|
|
724
|
+
|
|
725
|
+
The step is the exact transition of the SDE, so any Δ gives the right distribution. The shock's
|
|
726
|
+
scale is computed with `expm1`, which keeps a small κΔ exact, and κ = 0 gives the random walk
|
|
727
|
+
X_k = X_{k−1} + σ√Δ ε_k. The half-life, the time for the expected gap to μ to halve, is ln 2/κ
|
|
728
|
+
years: the default κ = 6 gives 0.116 years, about 29 trading days. The output starts one step
|
|
729
|
+
after `start_value`.
|
|
730
|
+
|
|
731
|
+
| Parameter | Meaning | Default |
|
|
732
|
+
|---|---|---|
|
|
733
|
+
| `mean` | must be `0` (anything else raises): `mu` sets the level | `0` |
|
|
734
|
+
| `delta` | time step Δ (years) | `1/252` |
|
|
735
|
+
| `sigma` | volatility of the shocks (per √year) | `0.125` |
|
|
736
|
+
| `start_value` | X₀, the level before the first step | `0.5` |
|
|
737
|
+
| `kappa` | speed of reversion (per year); half-life ln 2/κ | `6.0` |
|
|
738
|
+
| `mu` | long-run level | `0.5` |
|
|
739
|
+
|
|
740
|
+
```python
|
|
741
|
+
import numpy as np
|
|
742
|
+
import synthetica as sth
|
|
743
|
+
|
|
744
|
+
kappa = np.log(2) / (20 / 252) # a half-life of 20 trading days
|
|
745
|
+
levels = sth.MeanReverting(120, 300, sigma=0.2, start_value=1.0, kappa=kappa, mu=0.5, seed=1).transform()
|
|
746
|
+
expected = 0.5 + (1.0 - 0.5) * np.exp(-kappa * np.arange(1, 121) / 252) # mu + (x0 - mu) e^(-kappa t)
|
|
747
|
+
```
|
|
748
|
+
|
|
749
|
+
<picture>
|
|
750
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/ou-dark.svg">
|
|
751
|
+
<img alt="A band of 300 mean-reverting paths over 120 trading days, all starting at 1.0 and closing on mu = 0.5 along the expected path" src="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/ou-light.svg" width="100%">
|
|
752
|
+
</picture>
|
|
753
|
+
|
|
754
|
+
300 paths start at 1.0; their mean follows the expected path μ + (x₀ − μ)e^(−κt), closing half the
|
|
755
|
+
gap to μ = 0.5 every 20 trading days (0.752 after 20 days, against 0.75), and after 120 days the
|
|
756
|
+
band holds 0.42 to 0.58. Drawn with `levels.sth.fan(mean=expected)`.
|
|
757
|
+
**Tested:** with a half-life of h steps the lag-1 coefficient is 2^(−1/h) and the variance after
|
|
758
|
+
T is σ²(1 − e^(−2κT))/(2κ); κ = 0 adds the white noise exactly, and a non-zero `mean` raises.
|
|
759
|
+
|
|
760
|
+
<a name="cir"></a>
|
|
761
|
+
|
|
762
|
+
### Cox–Ingersoll–Ross · `CIR`
|
|
763
|
+
|
|
764
|
+
A mean-reverting rate whose noise scales with √r, so the noise shrinks as the rate nears zero and
|
|
765
|
+
the rate stays non-negative. Use it for short rates, credit intensities or variances (it is the
|
|
766
|
+
variance process inside Heston).
|
|
767
|
+
|
|
768
|
+
```math
|
|
769
|
+
dr_t = \kappa\,(\mu - r_t)\,dt + \sigma\sqrt{r_t}\, dW_t
|
|
770
|
+
```
|
|
771
|
+
|
|
772
|
+
What the code does each step (Euler with full truncation, Lord et al. 2010, Δ = `delta`, $x^+ = \max(x, 0)$, $\varepsilon_k \sim N(0, 1)$):
|
|
773
|
+
|
|
774
|
+
```math
|
|
775
|
+
\tilde r_k = \tilde r_{k-1} + \kappa\,\big(\mu - \tilde r_{k-1}^{+}\big)\,\Delta + \sigma\sqrt{\tilde r_{k-1}^{+}}\,\sqrt{\Delta}\;\varepsilon_k, \qquad r_k = \tilde r_k^{+}
|
|
776
|
+
```
|
|
777
|
+
|
|
778
|
+
The internal state r̃ can dip below zero; the drift and the square root use its positive part,
|
|
779
|
+
and the output is the positive part, so a rate is never negative. The Feller condition
|
|
780
|
+
2κμ ≥ σ² keeps the exact process away from zero; when it fails the rate touches zero, which the
|
|
781
|
+
scheme handles by leaving an atom at zero that the exact process does not have (about 2% of the
|
|
782
|
+
values at one year with the chart's parameters, fewer with smaller steps): code that takes log(r)
|
|
783
|
+
or divides by r must allow for zeros. The defaults satisfy it (2κμ = 6 against σ² ≈ 0.016). The state starts at
|
|
784
|
+
r̃₀ = `start_value`, and the output starts one step later.
|
|
785
|
+
|
|
786
|
+
| Parameter | Meaning | Default |
|
|
787
|
+
|---|---|---|
|
|
788
|
+
| `mean` | must be `0` (anything else raises): `mu` sets the level | `0` |
|
|
789
|
+
| `delta` | time step Δ (years) | `1/252` |
|
|
790
|
+
| `sigma` | volatility; a step's shock is σ√(r⁺Δ) ε | `0.125` |
|
|
791
|
+
| `start_value` | r₀, the rate before the first step | `0.5` |
|
|
792
|
+
| `kappa` | speed of reversion (per year) | `6.0` |
|
|
793
|
+
| `mu` | long-run rate | `0.5` |
|
|
794
|
+
|
|
795
|
+
```python
|
|
796
|
+
import synthetica as sth
|
|
797
|
+
|
|
798
|
+
# Feller violated: 2 * 0.8 * 0.03 = 0.048 < 0.3**2 = 0.09
|
|
799
|
+
rates = sth.CIR(5 * 252, 500, start_value=0.05, mu=0.03, kappa=0.8, sigma=0.3, seed=1).transform()
|
|
800
|
+
```
|
|
801
|
+
|
|
802
|
+
<picture>
|
|
803
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/cir-dark.svg">
|
|
804
|
+
<img alt="A band of 500 CIR rate paths over 5 years with the Feller condition violated: the lower edge of the 5 to 95 percent band sits at zero, and the exact mean decays from 5% to 3% above the median" src="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/cir-light.svg" width="100%">
|
|
805
|
+
</picture>
|
|
806
|
+
|
|
807
|
+
Over 500 paths the mean decays from 5% to 3% as μ + (r₀ − μ)e^(−κt), and the band's lower edge sits
|
|
808
|
+
at zero: 85% of the paths touch zero but none goes below (the time at zero comes from the scheme;
|
|
809
|
+
the exact process only touches zero). Drawn with `rates.sth.fan(mean=...)`.
|
|
810
|
+
**Tested:** with Feller violated (r₀ = 0, μ = 0.02, κ = 0.5, σ = 0.3) every rate is ≥ 0 and the
|
|
811
|
+
one-year mean and variance match the exact CIR moments; a non-zero `mean` raises.
|
|
812
|
+
|
|
813
|
+
<a name="ar"></a>
|
|
814
|
+
|
|
815
|
+
### Autoregressive · `AutoRegressive`
|
|
816
|
+
|
|
817
|
+
An autoregressive process of any order: each value is a weighted sum of the previous ones plus
|
|
818
|
+
Gaussian noise, and the length of the `ar` list sets the order. Use it for stationary signals with
|
|
819
|
+
short memory, or to check that a model recovers known lag coefficients. `sth.AR` is an alias.
|
|
820
|
+
|
|
821
|
+
```math
|
|
822
|
+
x_t = c + \sum_{j=1}^{p} a_j\, x_{t-j} + \varepsilon_t, \qquad \varepsilon_t \sim N(0, s^2)
|
|
823
|
+
```
|
|
824
|
+
|
|
825
|
+
What the code does each step (exact recursion from zeros, Δ = `delta`):
|
|
826
|
+
|
|
827
|
+
```math
|
|
828
|
+
x_t = \sum_{j=1}^{p} a_j\, x_{t-j} + \varepsilon_t, \qquad \varepsilon_t \sim N\big(\text{mean},\ \sigma^2 \Delta\big), \qquad x_0 = x_{-1} = \dots = x_{1-p} = 0
|
|
829
|
+
```
|
|
830
|
+
|
|
831
|
+
| Parameter | Meaning | Default |
|
|
832
|
+
|---|---|---|
|
|
833
|
+
| `ar` | coefficients a₁ … aₚ, as a list; its length is the order p. Not checked: pass a stationary set (for an AR(2): `ar[1] > -1`, `ar[0] + ar[1] < 1`, `ar[1] - ar[0] < 1`) or the paths explode | `None` → `[0.8]` |
|
|
834
|
+
| `mean` | noise mean, which acts as the intercept c: a stationary path settles at mean / (1 − sum of `ar`), not at `mean` | `0` |
|
|
835
|
+
| `sigma` | noise scale: each step's noise has standard deviation σ√Δ | `0.125` |
|
|
836
|
+
| `delta` | time step; it only scales the noise | `1/252` |
|
|
837
|
+
|
|
838
|
+
```python
|
|
839
|
+
import synthetica as sth
|
|
840
|
+
|
|
841
|
+
x = sth.AutoRegressive(5000, ar=[1.2, -0.7], seed=1).transform()
|
|
842
|
+
acf = [x.autocorr(k) for k in range(1, 16)] # sample ACF, lags 1-15
|
|
843
|
+
```
|
|
844
|
+
|
|
845
|
+
<picture>
|
|
846
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/ar-dark.svg">
|
|
847
|
+
<img alt="300 steps of an AR(2) signal with ar = [1.2, -0.7], swinging up and down in irregular cycles of about eight steps" src="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/ar-light.svg" width="100%">
|
|
848
|
+
</picture>
|
|
849
|
+
|
|
850
|
+
This AR(2) has complex roots, so the signal swings in irregular cycles of about 8 steps: its
|
|
851
|
+
autocorrelation is the damped wave of the Yule–Walker values ρ₁ = a₁ / (1 − a₂),
|
|
852
|
+
ρₖ = a₁ρₖ₋₁ + a₂ρₖ₋₂. Drawn with `x.iloc[:300].sth.paths()`, its first 300 steps.
|
|
853
|
+
**Tested:** least squares on the two lags of 200 paths of 1,000 steps with `ar=[0.5, -0.3]` recovers both coefficients within 0.01.
|
|
854
|
+
|
|
855
|
+
<a name="narma"></a>
|
|
856
|
+
|
|
857
|
+
### NARMA · `NARMA`
|
|
858
|
+
|
|
859
|
+
A nonlinear autoregressive moving-average signal of order n, driven by uniform random inputs
|
|
860
|
+
([Atiya & Parlos, 2000](https://doi.org/10.1109/72.846741)). Each output depends on the last n
|
|
861
|
+
outputs and on the product of the newest input and the one n − 1 steps before it, so a model must
|
|
862
|
+
remember n steps to predict it. It is a benchmark for sequence models (recurrent networks,
|
|
863
|
+
reservoir computing), not a price model.
|
|
864
|
+
|
|
865
|
+
```math
|
|
866
|
+
y(k+1) = a_0\, y(k) + a_1\, y(k) \sum_{i=0}^{n-1} y(k-i) + a_2\, u(k-n+1)\, u(k) + a_3, \qquad u(k) \sim U(0, 0.5)
|
|
867
|
+
```
|
|
868
|
+
|
|
869
|
+
What the code does each step (exact recursion; there is no Δ, the step is the time unit):
|
|
870
|
+
|
|
871
|
+
```math
|
|
872
|
+
u_k = \tfrac{1}{2}\, \Phi(z_k), \quad z_k \sim N(0, 1), \qquad y_{k+1} = s\Big(a_0\, y_k + a_1\, y_k \sum_{i=0}^{n-1} y_{k-i} + a_2\, u_{k-n+1}\, u_k + a_3\Big)
|
|
873
|
+
```
|
|
874
|
+
|
|
875
|
+
The first n rows, y₀ … yₙ₋₁, are history set to `start_value` and are not returned. Φ is the normal
|
|
876
|
+
CDF, so the inputs are uniform on (0, 0.5). `transform(matrix=...)` correlates the z's across paths
|
|
877
|
+
(a Gaussian copula) and `transform(copula=...)` replaces Φ(z) with the copula's draws: the inputs
|
|
878
|
+
become dependent across paths, and each path is still a NARMA path.
|
|
879
|
+
|
|
880
|
+
`s` is set by `stabilize`. NARMA-10 has an unstable balance point near y ≈ 1.02: a run of large
|
|
881
|
+
inputs can push a path over it, and the path then runs to infinity (1–2% of 3,000-step paths,
|
|
882
|
+
about 5% of 10,000-step ones).
|
|
883
|
+
With `'redraw'` (s is the identity) the code reruns those paths with new inputs, all of them when a
|
|
884
|
+
matrix or copula ties them, up to 100 times before it raises: the output is NARMA given that it
|
|
885
|
+
stays bounded. With `'tanh'` every step is squashed into (−1, 1) (Jaeger, 2003): it never blows
|
|
886
|
+
up, but it is a different system, whose mean level is about 14% lower at the default coefficients.
|
|
887
|
+
|
|
888
|
+
| Parameter | Meaning | Default |
|
|
889
|
+
|---|---|---|
|
|
890
|
+
| `start_value` | value of the n history rows before the first output | `0.5` |
|
|
891
|
+
| `n` | order: the number of past outputs in the sum, and n − 1 is the lag between the two inputs | `10` |
|
|
892
|
+
| `a` | the four coefficients [a₀, a₁, a₂, a₃] | `None` → `[0.3, 0.05, 1.5, 0.1]` |
|
|
893
|
+
| `stabilize` | what to do with paths that blow up: `'redraw'` their inputs or squash every step with `'tanh'` | `'redraw'` |
|
|
894
|
+
|
|
895
|
+
```python
|
|
896
|
+
import synthetica as sth
|
|
897
|
+
|
|
898
|
+
y = sth.NARMA(300, seed=7).transform() # NARMA-10
|
|
899
|
+
y_tanh = sth.NARMA(300, stabilize='tanh', seed=7).transform() # bounded in (-1, 1)
|
|
900
|
+
```
|
|
901
|
+
|
|
902
|
+
<picture>
|
|
903
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/narma-dark.svg">
|
|
904
|
+
<img alt="300 steps of a NARMA-10 output that hovers around 0.4 and climbs to about 0.95 near step 55" src="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/narma-light.svg" width="100%">
|
|
905
|
+
</picture>
|
|
906
|
+
|
|
907
|
+
The output hovers near 0.4; a run of large inputs around steps 35–55 lifts it to about 0.95 before it
|
|
908
|
+
settles back. Drawn with `y.sth.paths()`.
|
|
909
|
+
**Tested:** with `a=[0, 0, 1, 0]` the output is u(k − n + 1)·u(k), whose autocorrelation is 3/7 at lag n − 1 and 0 at lag n, and with n = 1 a `matrix` or `copula` passes its Kendall's τ to the outputs; 10,000-step NARMA-10 paths stay finite with `'redraw'` (alone, with a matrix, with a vine copula) and inside (−1, 1) with `'tanh'`.
|
|
910
|
+
|
|
911
|
+
## Dependence across paths
|
|
912
|
+
|
|
913
|
+
`transform` ties paths together in one of two ways:
|
|
914
|
+
|
|
915
|
+
- `matrix`: a correlation matrix, one row and column per path. Its Cholesky factor gives Gaussian
|
|
916
|
+
dependence: correlated on average, but with no tail dependence, so extreme days become close to
|
|
917
|
+
independent. Use it when a correlation is all you need.
|
|
918
|
+
- `copula`: any copula object with one dimension per path, such as a pyvinecopulib `Bicop`
|
|
919
|
+
(2 paths) or `Vinecop` (any number); see [What `copula` accepts](#what-copula-accepts). Its draws become the shocks, so the paths share its dependence, tails included: a Clayton
|
|
920
|
+
copula makes paths crash together (lower tail), a Gumbel copula makes them rally together
|
|
921
|
+
(upper tail). Use it when joint extremes matter, for example to stress a pair or a basket.
|
|
922
|
+
|
|
923
|
+
<picture>
|
|
924
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/matrix-paths-dark.svg">
|
|
925
|
+
<img alt="Three side-by-side panels of two GBM price paths over two years with the same first leg: at correlation -0.8 the second leg mirrors the first, at 0 it ignores it, at +0.8 it follows it" src="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/matrix-paths-light.svg" width="100%">
|
|
926
|
+
</picture>
|
|
927
|
+
|
|
928
|
+
With one seed, leg 1 is the same in every panel, and leg 2 is ρ times leg 1's shock plus
|
|
929
|
+
√(1 − ρ²) times its own: it mirrors leg 1 at ρ = −0.8, ignores it at 0 and follows it at +0.8
|
|
930
|
+
(daily-return correlations −0.79, −0.02 and +0.78). Drawn with `sth.plot.paths({...})`, one panel per matrix.
|
|
931
|
+
|
|
932
|
+
```python
|
|
933
|
+
import numpy as np
|
|
934
|
+
import synthetica as sth
|
|
935
|
+
|
|
936
|
+
m = np.array([[1, -0.8], [-0.8, 1]]) # one row and one column per path
|
|
937
|
+
legs = sth.GeometricBrownianMotion(504, 2, mu=0.08, sigma=0.25, seed=2).transform(matrix=m)
|
|
938
|
+
```
|
|
939
|
+
|
|
940
|
+
A matrix only sets how much the legs move together on average. A copula also sets how they move
|
|
941
|
+
on extreme days:
|
|
942
|
+
|
|
943
|
+
<picture>
|
|
944
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/copula-paths-dark.svg">
|
|
945
|
+
<img alt="Two side-by-side panels of two GBM price paths over two years with the same Kendall tau of 0.6 and the same first leg: with a Gaussian copula the legs crash together on 13 days, with a Clayton copula on 19" src="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/copula-paths-light.svg" width="100%">
|
|
946
|
+
</picture>
|
|
947
|
+
|
|
948
|
+
Both panels have Kendall's τ = 0.6 and the same leg 1, and leg 2 comes from the same random draw
|
|
949
|
+
put through each dependence, so the only difference is the dependence. On average the legs move
|
|
950
|
+
together just as much; on their worst days they part with the matrix and fall together with
|
|
951
|
+
Clayton: 19 days in two years when both are in their worst 5%, against 13. Drawn with `sth.plot.crashes({...})`.
|
|
952
|
+
The chart fixes leg 1 and the draw by hand (`docs/save_charts.py`); with a model, each
|
|
953
|
+
dependence is one keyword, and each call draws its own legs:
|
|
954
|
+
|
|
955
|
+
```python
|
|
956
|
+
import numpy as np
|
|
957
|
+
import pyvinecopulib as pv
|
|
958
|
+
import synthetica as sth
|
|
959
|
+
|
|
960
|
+
model = sth.GeometricBrownianMotion(length=504, num_paths=2, seed=1)
|
|
961
|
+
|
|
962
|
+
rho = np.sin(np.pi * 0.6 / 2) # Kendall's tau 0.6 as a correlation
|
|
963
|
+
gaussian = model.transform(matrix=np.array([[1, rho], [rho, 1]]))
|
|
964
|
+
|
|
965
|
+
clayton = pv.Bicop(family=pv.families.clayton, parameters=np.array([[3.0]])) # tau 0.6
|
|
966
|
+
crash = model.transform(copula=clayton)
|
|
967
|
+
```
|
|
968
|
+
|
|
969
|
+
To copy the dependence of a real pair, fit a copula to its returns and pass it as it is:
|
|
970
|
+
|
|
971
|
+
```python
|
|
972
|
+
fitted = pv.Bicop.from_data(pv.to_pseudo_obs(np.asarray(returns))) # returns: real daily returns, T x 2
|
|
973
|
+
synthetic = sth.GeometricBrownianMotion(len(returns), 2, seed=1).transform(copula=fitted)
|
|
974
|
+
```
|
|
975
|
+
|
|
976
|
+
The rank view shows the same thing on 2,000 days: each dot is one day's pair of return ranks.
|
|
977
|
+
|
|
978
|
+
<picture>
|
|
979
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/dependence-dark.svg">
|
|
980
|
+
<img alt="Two scatter plots of the return ranks of two paths with the same Kendall tau of 0.6: with a Gaussian matrix the worst days are shared 45 times in 99, with a Clayton copula 84 times" src="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/dependence-light.svg" width="100%">
|
|
981
|
+
</picture>
|
|
982
|
+
|
|
983
|
+
Of path 1's 99 worst days (its worst 5%), 45 are also among path 2's worst with the matrix, and 84
|
|
984
|
+
with the Clayton copula; the best days go the other way (48 and 21). Drawn with
|
|
985
|
+
`sth.plot.ranks({...})`, one panel per dependence.
|
|
986
|
+
|
|
987
|
+
For more than two paths, a vine chains pair copulas: here Clayton ties legs 1 and 2, Gumbel ties
|
|
988
|
+
legs 2 and 3, and legs 1 and 3 are independent given leg 2 (`pv.Bicop()` is the independence
|
|
989
|
+
copula).
|
|
990
|
+
|
|
991
|
+
<picture>
|
|
992
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/vine-paths-dark.svg">
|
|
993
|
+
<img alt="Three scatter plots of the return ranks of a three-leg vine: legs 1 and 2 share their worst days, legs 2 and 3 their best days, and legs 1 and 3 neither much" src="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/vine-paths-light.svg" width="100%">
|
|
994
|
+
</picture>
|
|
995
|
+
|
|
996
|
+
Over 2,000 days, legs 1 and 2 (Clayton) share their crashes: 77 of their 99 worst days in common,
|
|
997
|
+
against 20 of their best; legs 2 and 3 (Gumbel) share their rallies (73 against 38); legs 1 and 3,
|
|
998
|
+
tied only through leg 2, share 36 and 19. Drawn with `sth.plot.ranks({...})`, one panel per pair.
|
|
999
|
+
|
|
1000
|
+
```python
|
|
1001
|
+
gumbel = pv.Bicop(family=pv.families.gumbel, parameters=np.array([[2.5]])) # tau 0.6
|
|
1002
|
+
vine = pv.Vinecop.from_structure(
|
|
1003
|
+
structure=pv.DVineStructure(order=[1, 2, 3]), # variable j drives path_j
|
|
1004
|
+
pair_copulas=[[clayton, gumbel], [pv.Bicop()]],
|
|
1005
|
+
)
|
|
1006
|
+
three = sth.GeometricBrownianMotion(504, 3, mu=0.08, sigma=0.25, seed=4).transform(copula=vine)
|
|
1007
|
+
```
|
|
1008
|
+
|
|
1009
|
+
### What `copula` accepts
|
|
1010
|
+
|
|
1011
|
+
**Any object** whose `sample(n, seeds)` returns an n × num_paths array of numbers strictly between
|
|
1012
|
+
0 and 1, one column per path. `seeds` is a list of integers that synthetica derives from `seed`:
|
|
1013
|
+
draw from it and the output stays reproducible. synthetica imports no copula library, so you can
|
|
1014
|
+
use any of them. pyvinecopulib's `Bicop` and `Vinecop` already have that method, as above.
|
|
1015
|
+
Anything else needs a short wrapper, for example statsmodels' copulas (two paths, or an elliptical
|
|
1016
|
+
copula for more) or the empirical copula of real data, which copies its dependence without fitting
|
|
1017
|
+
any model:
|
|
1018
|
+
|
|
1019
|
+
```python
|
|
1020
|
+
import numpy as np
|
|
1021
|
+
from scipy import stats
|
|
1022
|
+
from statsmodels.distributions.copula.api import ClaytonCopula, StudentTCopula
|
|
1023
|
+
|
|
1024
|
+
|
|
1025
|
+
class Statsmodels:
|
|
1026
|
+
"""A statsmodels copula."""
|
|
1027
|
+
|
|
1028
|
+
def __init__(self, copula):
|
|
1029
|
+
self.copula = copula
|
|
1030
|
+
|
|
1031
|
+
def sample(self, n, seeds):
|
|
1032
|
+
return self.copula.rvs(n, rng=np.random.default_rng(seeds))
|
|
1033
|
+
|
|
1034
|
+
|
|
1035
|
+
class Empirical:
|
|
1036
|
+
"""The dependence of real data, with no model: resample whole days of return ranks."""
|
|
1037
|
+
|
|
1038
|
+
def __init__(self, returns):
|
|
1039
|
+
self.u = stats.rankdata(returns, axis=0) / (len(returns) + 1)
|
|
1040
|
+
|
|
1041
|
+
def sample(self, n, seeds):
|
|
1042
|
+
return self.u[np.random.default_rng(seeds).integers(len(self.u), size=n)]
|
|
1043
|
+
|
|
1044
|
+
|
|
1045
|
+
pair = sth.GeometricBrownianMotion(504, 2, seed=1).transform(copula=Statsmodels(ClaytonCopula(theta=3)))
|
|
1046
|
+
|
|
1047
|
+
corr = np.array([[1, 0.7, 0.3], [0.7, 1, 0.5], [0.3, 0.5, 1]])
|
|
1048
|
+
basket = sth.GeometricBrownianMotion(504, 3, seed=1).transform(
|
|
1049
|
+
copula=Statsmodels(StudentTCopula(corr=corr, df=4, k_dim=3))
|
|
1050
|
+
)
|
|
1051
|
+
|
|
1052
|
+
# returns: real daily returns, T x d; the synthetic paths keep their joint ranks day by day
|
|
1053
|
+
copied = sth.GeometricBrownianMotion(504, returns.shape[1], seed=1).transform(copula=Empirical(returns))
|
|
1054
|
+
```
|
|
1055
|
+
|
|
1056
|
+
| Source | Paths | Wrapper | Dependence |
|
|
1057
|
+
|---|---|---|---|
|
|
1058
|
+
| pyvinecopulib `Bicop` | 2 | none | any of its families, rotations included |
|
|
1059
|
+
| pyvinecopulib `Vinecop` | any | none | a pair copula per edge: crashes on some pairs, rallies on others |
|
|
1060
|
+
| statsmodels | 2, or any for Gaussian and Student-t | `Statsmodels` above | Clayton, Gumbel, Frank, Gaussian, Student-t |
|
|
1061
|
+
| real data | any | `Empirical` above | whatever the data has, with no model |
|
|
1062
|
+
|
|
1063
|
+
A copula that returns exactly 0 or 1 raises a `ValueError`: the inverse normal CDF would turn it
|
|
1064
|
+
into an infinite shock, and the price into 0 or infinity.
|
|
1065
|
+
|
|
1066
|
+
- synthetica depends on no copula library: install the one you use (`pip install pyvinecopulib`).
|
|
1067
|
+
- `matrix` and `copula` cannot be combined, and the copula needs one dimension per path; both
|
|
1068
|
+
mistakes raise a `ValueError`.
|
|
1069
|
+
- A matrix that is not positive definite has no Cholesky factor, so synthetica replaces it with
|
|
1070
|
+
the nearest one that is, using `sth.nearest_positive_definite` (Higham, 1988). Check the
|
|
1071
|
+
correlations you get back when you pass a matrix built by hand or from patchy data.
|
|
1072
|
+
|
|
1073
|
+
## Cointegration
|
|
1074
|
+
|
|
1075
|
+
Every price model's `transform` takes `cointegrate=`: its paths become legs whose spreads, weighted
|
|
1076
|
+
sums of the legs' log prices, revert to a level with the half-life you give. That is a planted edge,
|
|
1077
|
+
known exactly, to test a pair or basket strategy on. With `cointegrate=np.inf` the legs come back
|
|
1078
|
+
unchanged, and with the same seed they are the same legs: the matched null.
|
|
1079
|
+
|
|
1080
|
+
```math
|
|
1081
|
+
s_{k,t} = w_k \cdot \log P_t, \qquad s_{k,t} - L_{k,t-1} = \phi_k\,(s_{k,t-1} - L_{k,t-1}) + e_{k,t}, \qquad \phi_k = 2^{-1/h_k}
|
|
1082
|
+
```
|
|
1083
|
+
|
|
1084
|
+
What the code does each step: the legs close the share $1 - \phi_k$ of each spread's gap to its
|
|
1085
|
+
level at the step before, so the equation holds exactly, with $e_{k,t}$ the spread's own shock in
|
|
1086
|
+
the model's output. The correction uses the spreads and the level up to $t - 1$ only: each leg's
|
|
1087
|
+
return changes by a term known one step ahead, so there is no look-ahead, and the legs' shocks, and
|
|
1088
|
+
their copula, stay as the model drew them. The legs not in `fixed` share each correction in the
|
|
1089
|
+
smallest way that moves only its own spread. The level models (`MeanReverting`, `CIR`,
|
|
1090
|
+
`AutoRegressive`, `NARMA`) do not take `cointegrate`: their levels can be negative.
|
|
1091
|
+
|
|
1092
|
+
| Keyword argument | Meaning | Default |
|
|
1093
|
+
|---|---|---|
|
|
1094
|
+
| `cointegrate` | $h$, each spread's half-life in steps: one value, one per spread, one per row (a break), or one per row and spread; `np.inf` for no pull | |
|
|
1095
|
+
| `weights` | $w$, one row per spread and one column per path: the weights on the log prices (`[1, -0.7]` is a pair with a hedge ratio of 0.7) | every path against the first |
|
|
1096
|
+
| `level` | $L$, the level each spread reverts to: one value, one per spread, one per row (a moving level, such as a random walk), or one per row and spread | each spread's value just before its first finite half-life |
|
|
1097
|
+
| `fixed` | paths that never move, such as a market index or an ETF | none |
|
|
1098
|
+
|
|
1099
|
+
After `transform`, `model.spreads` holds the spreads behind each row (`None` after a call without
|
|
1100
|
+
`cointegrate`). The default level is where the spread stands when the pull starts, so an edge that
|
|
1101
|
+
starts late does not first pull back to where the spread began. A `level` with one value per row,
|
|
1102
|
+
such as a random walk, gives a spread that reverts to a level that itself wanders (partial
|
|
1103
|
+
cointegration); the pull uses yesterday's level, so this has no look-ahead either. When a spread's
|
|
1104
|
+
shocks have a mean $d$ per step (legs with different drifts, or weights that do not sum to 0), it
|
|
1105
|
+
reverts to $L + d/(1 - \phi)$ instead of $L$.
|
|
1106
|
+
|
|
1107
|
+
```python
|
|
1108
|
+
import numpy as np
|
|
1109
|
+
import synthetica as sth
|
|
1110
|
+
|
|
1111
|
+
model = sth.GeometricBrownianMotion(504, 2, mu=0.08, sigma=0.25, seed=5)
|
|
1112
|
+
prices = model.transform(cointegrate=20) # a planted edge: a 20-day half-life
|
|
1113
|
+
spread = model.spreads # the true spread behind each row
|
|
1114
|
+
null = model.transform(cointegrate=np.inf) # the same legs (same seed), no edge
|
|
1115
|
+
|
|
1116
|
+
# The edge stops after a year: a pair that breaks
|
|
1117
|
+
broken = model.transform(cointegrate=np.r_[np.full(252, 20.0), np.full(252, np.inf)])
|
|
1118
|
+
```
|
|
1119
|
+
|
|
1120
|
+
Set `seed`: with `seed=None` each call draws new legs, and the null no longer shares them.
|
|
1121
|
+
|
|
1122
|
+
The same maths works on any price table, such as real prices: `prices, spreads =
|
|
1123
|
+
sth.cointegrate(legs, halflife=20)`, with `weights`, `level` and `fixed` as above.
|
|
1124
|
+
|
|
1125
|
+
<picture>
|
|
1126
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/cointegrated-dark.svg">
|
|
1127
|
+
<img alt="Two stacked panels over two years: two GBM legs made cointegrated with a 20-day half-life, which move together, and below their log spread, which stays within 0.23 of zero" src="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/cointegrated-light.svg" width="100%">
|
|
1128
|
+
</picture>
|
|
1129
|
+
|
|
1130
|
+
With a 20-day half-life the spread stays within 0.23 of its level, with a standard deviation of 0.085
|
|
1131
|
+
(0.079 in theory), and the legs move together. Without the edge (`cointegrate=np.inf`, the same legs)
|
|
1132
|
+
their spread wanders from −0.45 to 0.53 in two years, and with the edge stopping after a year it
|
|
1133
|
+
wanders off to −0.58: the pair has broken. Drawn with
|
|
1134
|
+
`model.transform(cointegrate=20).sth.paths(model=model)`, which adds the model's `spreads` below.
|
|
1135
|
+
|
|
1136
|
+
More legs work the same way. With the default weights, every path is tied to the first, so the legs
|
|
1137
|
+
share one trend and every pair of them reverts with the same half-life:
|
|
1138
|
+
|
|
1139
|
+
```python
|
|
1140
|
+
# Five legs: all 10 pairs revert with a 20-day half-life
|
|
1141
|
+
five = sth.GeometricBrownianMotion(756, 5, seed=11).transform(cointegrate=20)
|
|
1142
|
+
|
|
1143
|
+
# An ETF against three of its stocks; the ETF never moves
|
|
1144
|
+
basket = sth.GeometricBrownianMotion(756, 4, seed=2).transform(
|
|
1145
|
+
cointegrate=20, weights=[1, -0.5, -0.3, -0.2], fixed=[0])
|
|
1146
|
+
|
|
1147
|
+
# Two separate pairs on Heston legs, with their own half-lives; path 5 stays free
|
|
1148
|
+
two = sth.Heston(756, 5, seed=3).transform(
|
|
1149
|
+
cointegrate=[10, 40], weights=[[1, -1, 0, 0, 0], [0, 0, 1, -1, 0]])
|
|
1150
|
+
|
|
1151
|
+
# A pair that reverts to a level that wanders: a random walk, one value per row
|
|
1152
|
+
walk = np.cumsum(np.random.default_rng(0).normal(0, 0.005, 756))
|
|
1153
|
+
partial = sth.GeometricBrownianMotion(756, 2, seed=4).transform(cointegrate=20, level=walk)
|
|
1154
|
+
```
|
|
1155
|
+
|
|
1156
|
+
<picture>
|
|
1157
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/cointegrated-legs-dark.svg">
|
|
1158
|
+
<img alt="Two side-by-side panels over three years on the same scale: five GBM legs that wander apart from 56 to 144, and the same legs made cointegrated with a 20-day half-life, which stay together between about 80 and 125" src="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/cointegrated-legs-light.svg" width="100%">
|
|
1159
|
+
</picture>
|
|
1160
|
+
|
|
1161
|
+
The same five legs without and with the edge: on their own they end anywhere from 56 to 144, with
|
|
1162
|
+
pairs up to 1.00 apart in log; cointegrated, every pair stays within 0.33 and they end between 89
|
|
1163
|
+
and 101. With different half-lives per spread, the pairs that mix two spreads still revert, but not
|
|
1164
|
+
with one half-life. Drawn with `sth.plot.paths({...})`, one panel per call.
|
|
1165
|
+
**Tested:** for a pair with a hedge ratio (on Heston legs), a break, an edge that starts late, a
|
|
1166
|
+
moving level, a basket with a fixed leg and two pairs with their own half-lives, every spread is the
|
|
1167
|
+
AR(1) above to 1e-12, and the fixed and free legs are unchanged; with the default weights all 10
|
|
1168
|
+
pairs of 5 legs are; changing a leg or the level from row t on leaves every correction up to row t
|
|
1169
|
+
unchanged; `cointegrate=np.inf` returns the model's own output bit for bit; `spreads` never holds
|
|
1170
|
+
a previous call's spreads; booleans, `weights`, `level` or `fixed` without `cointegrate`, prices of
|
|
1171
|
+
0 or infinity, a non-finite level and a 1-D shape that could mean either rows or spreads raise; and
|
|
1172
|
+
the level models refuse it.
|
|
1173
|
+
|
|
1174
|
+
## OHLC bars
|
|
1175
|
+
|
|
1176
|
+
Every price model's `transform` also takes `ohlc=`, the share of each step's variance before the
|
|
1177
|
+
open, and then returns open, high, low and close bars around its closes, which stay as they are.
|
|
1178
|
+
Use it when a backtest fills at the next open, puts a stop between the low and the high, or
|
|
1179
|
+
measures time by the range. It combines with `cointegrate`.
|
|
1180
|
+
|
|
1181
|
+
What the code does each step: the log price from the previous close to this one is a Brownian
|
|
1182
|
+
bridge in the step's own variance-time. The open is the bridge at the `overnight` share of the step,
|
|
1183
|
+
and the high and low are its exact maximum and minimum over the session, drawn on 8 slices. Each
|
|
1184
|
+
jump lands overnight with probability `overnight`, else in the session: a step's session jumps land
|
|
1185
|
+
together at a uniform time, and the high and low are taken on each side of them. The bridge's draws
|
|
1186
|
+
use the model's `matrix` or `copula`, so the legs move together within the step as they do from
|
|
1187
|
+
close to close, and come from their own stream (5) of the model's seed; those around a session jump
|
|
1188
|
+
come from stream 8, so bars without one keep their draws.
|
|
1189
|
+
|
|
1190
|
+
The bridge must use each step's true variance. If it is too small, the open already holds part of
|
|
1191
|
+
the step's move, and a strategy that fills at the open finds an edge that is not there. Measured
|
|
1192
|
+
over 100,000 bars with `overnight=0.3` (the correlation of the overnight move with the open-to-close
|
|
1193
|
+
move must be 0):
|
|
1194
|
+
|
|
1195
|
+
| Bars built from | Correlation | Overnight share |
|
|
1196
|
+
|---|---|---|
|
|
1197
|
+
| GBM, with σ²Δ | −0.003 | 0.30 |
|
|
1198
|
+
| Heston, with its own `variance` | +0.002 | 0.30 |
|
|
1199
|
+
| Heston, with a constant variance (wrong) | +0.051 | 0.28 |
|
|
1200
|
+
| Cyclical, with the cycle's own shock | +0.005 | 0.30 |
|
|
1201
|
+
| Cyclical, without it (wrong) | +0.236 | 0.21 |
|
|
1202
|
+
| Merton, with its session jumps at a uniform time | +0.000 | 0.30 |
|
|
1203
|
+
| Merton, with the jumps ignored (wrong) | +0.475 | 0.16 |
|
|
1204
|
+
|
|
1205
|
+
So each model gives the bridge what it knows:
|
|
1206
|
+
|
|
1207
|
+
| Model | Variance per step | Jumps |
|
|
1208
|
+
|---|---|---|
|
|
1209
|
+
| `GeometricBrownianMotion`, `Seasonal` | $\sigma^2\Delta$ | none |
|
|
1210
|
+
| `Heston` | its `variance` × Δ, step by step | none |
|
|
1211
|
+
| `Merton` | $\sigma^2\Delta$ | its `jumps`, overnight or at a uniform time of the session |
|
|
1212
|
+
| `Cyclical` | $\sigma^2\Delta + A^2(1 - \varrho^2)$, the cycle's own shock | none |
|
|
1213
|
+
| `Bates` and the other combined models | the engine's, plus the cycle's | the jumps' |
|
|
1214
|
+
| with `cointegrate` | the model's: the correction is known a step ahead, so the bridge is unchanged | the model's |
|
|
1215
|
+
| `Regimes` | each step's regime's | each step's regime's, with its copula |
|
|
1216
|
+
| `LevyStable` | not supported: its stable steps have no variance (raises an error) | |
|
|
1217
|
+
|
|
1218
|
+
`ohlc` is in [0, 1): 0 opens at the previous close; US stocks have about 0.2 to 0.3. The level
|
|
1219
|
+
models do not take it. `transform(ohlc=...)` returns one DataFrame with columns `Open`, `High`, `Low`
|
|
1220
|
+
and `Close`, each with one column per leg (or the four alone for one path); the closes are the
|
|
1221
|
+
model's.
|
|
1222
|
+
|
|
1223
|
+
```python
|
|
1224
|
+
import numpy as np
|
|
1225
|
+
import synthetica as sth
|
|
1226
|
+
|
|
1227
|
+
bates = sth.Bates(63, 2, rho=-0.7, lmbda=4, jump_mu=-0.06, var=0.03**2, seed=2)
|
|
1228
|
+
bars = bates.transform(cointegrate=20, ohlc=0.3) # a cointegrated Bates pair, as bars
|
|
1229
|
+
opens = bars["Open"] # one column per leg
|
|
1230
|
+
leg1 = bars.xs("path_1", axis=1, level=1) # one leg's Open, High, Low, Close (as vectorbt's Data takes)
|
|
1231
|
+
```
|
|
1232
|
+
|
|
1233
|
+
<picture>
|
|
1234
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/ohlc-dark.svg">
|
|
1235
|
+
<img alt="63 days of daily OHLC bars for the two legs of a cointegrated Bates pair, each bar a vertical line from low to high with the open ticked on the left and the close on the right; on 17 February leg 1 opens about 7% below its previous close, a jump that landed overnight" src="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/ohlc-light.svg" width="100%">
|
|
1236
|
+
</picture>
|
|
1237
|
+
|
|
1238
|
+
Three months of a cointegrated Bates pair. Most opens sit near the previous close, with 30% of the
|
|
1239
|
+
day's variance overnight; on 17 February (session 34) a jump landed overnight and leg 1 opens about
|
|
1240
|
+
7% below its previous close. Over 100,000 bars with these settings, the overnight move does not
|
|
1241
|
+
predict the rest of the day (correlation 0.006) and holds 29.4% of its variance. Drawn with
|
|
1242
|
+
`bars.sth.ohlc()`.
|
|
1243
|
+
**Tested:** for GBM, Heston, Cyclical, CyclicalHeston, Merton, CyclicalMerton and Bates (100 jumps a year),
|
|
1244
|
+
`Regimes`, a cointegrated pair and one with a moving level,
|
|
1245
|
+
the overnight and open-to-close moves are uncorrelated and the overnight share is `overnight`; the
|
|
1246
|
+
squared log range matches Parkinson's $4\ln 2$ times the session's variance (GBM, Heston); a session jump's dip below min(open, close) and the range
|
|
1247
|
+
match the exact law, a bridge on each side of a uniform jump time; the high
|
|
1248
|
+
and low hold the open and close, and the closes are the model's; with a matrix, the legs' overnight
|
|
1249
|
+
moves correlate at its ρ; with a random-walk `level` the open still does not predict the rest of the
|
|
1250
|
+
day; and LevyStable, `ohlc=1` and `ohlc=True` raise.
|
|
1251
|
+
|
|
1252
|
+
## Regimes
|
|
1253
|
+
|
|
1254
|
+
`Regimes` switches between price models over time: a calm, a volatile and a crashing market in one
|
|
1255
|
+
path, with the regime of every day known. Use it to test a strategy through regime shifts, or a
|
|
1256
|
+
regime detector against the truth.
|
|
1257
|
+
|
|
1258
|
+
```math
|
|
1259
|
+
\log P_t = \log P_{t-1} + r^{(k_t)}_t, \qquad P(k_t = k_{t-1}) = 1 - 1/d_{k_{t-1}}
|
|
1260
|
+
```
|
|
1261
|
+
|
|
1262
|
+
What the code does: each regime's model runs over the whole horizon in the background, on the same
|
|
1263
|
+
dates and paths, with its own seed. Each step keeps the log return $r^{(k)}_t$ of the regime $k_t$
|
|
1264
|
+
active at that step, chained from 100, so the price never gaps at a switch, and Heston's variance
|
|
1265
|
+
and a cycle keep running while their regime is off (Haas et al., 2004). The regimes follow a chain:
|
|
1266
|
+
a spell in regime $k$ lasts a geometric number of steps with mean $d_k$, then moves to regime $j$
|
|
1267
|
+
with probability `switch[k][j]`. So the one-step transition matrix is
|
|
1268
|
+
$\mathrm{diag}(1 - 1/d) + \mathrm{diag}(1/d)\,S$, and the long-run share of time in $k$ is
|
|
1269
|
+
proportional to $\nu_k d_k$, with $\nu$ the stationary law of $S$. The chain draws from its own
|
|
1270
|
+
stream (6) of the seed, and each regime's model gets its seed from stream 7, so other durations
|
|
1271
|
+
give other regimes on the same background paths.
|
|
1272
|
+
|
|
1273
|
+
The dependence switches with the regime: with `copula={'calm': gaussian, 'crash': clayton}` (or a
|
|
1274
|
+
dict of matrices), the paths' shocks on a step in regime $k$ follow $k$'s copula (Rodriguez, 2007;
|
|
1275
|
+
Okimoto, 2008); a regime left out of the dict has independent paths, and one copula or matrix
|
|
1276
|
+
applies to every regime. The `ohlc` bars follow each step's regime too: its variance, its jumps and
|
|
1277
|
+
its copula. `cointegrate` works on the joined prices.
|
|
1278
|
+
|
|
1279
|
+
| Argument | Meaning | Default |
|
|
1280
|
+
|---|---|---|
|
|
1281
|
+
| `models` | `{name: price model}`, all with the same `delta`; their own `length`, `num_paths`, `freq` and `seed` are not used | |
|
|
1282
|
+
| `durations` | `{name: mean spell in steps}`, at least 1: a Markov chain. Or `{name: law}`, whose `rvs(random_state=)` gives whole steps, at least 1: a semi-Markov chain, such as regular spells | |
|
|
1283
|
+
| `switch` | $S$, K × K in the order of `models` (a DataFrame by its labels): where a spell goes when it ends (zero diagonal, rows summing to 1) | any other regime, equally likely |
|
|
1284
|
+
| `schedule` | the regime name of each step, instead of a chain (another `Regimes`' `regime` works as is) | |
|
|
1285
|
+
| `start` | the first regime | drawn from the long-run shares |
|
|
1286
|
+
| `shared` | one chain for every path (a market-wide regime), or one per path (independent scenarios; then no `matrix` or `copula`) | `True` |
|
|
1287
|
+
|
|
1288
|
+
After `transform`, `regime` holds the regime of each step (categorical; a DataFrame with one chain
|
|
1289
|
+
per path) and `models` the models that ran, with their `variance`, `jumps` or `cycle`.
|
|
1290
|
+
`transition` (Markov chains only), `shares` and `params` describe the chain and the models.
|
|
1291
|
+
`regime` is the truth: a strategy must never see it.
|
|
1292
|
+
|
|
1293
|
+
```python
|
|
1294
|
+
import numpy as np
|
|
1295
|
+
import pyvinecopulib as pv
|
|
1296
|
+
import synthetica as sth
|
|
1297
|
+
|
|
1298
|
+
gauss = pv.Bicop(family=pv.families.gaussian, parameters=np.array([[0.7]]))
|
|
1299
|
+
clayton = pv.Bicop(family=pv.families.clayton, parameters=np.array([[3.0]]))
|
|
1300
|
+
market = sth.Regimes(
|
|
1301
|
+
{'calm': sth.GeometricBrownianMotion(sigma=0.10, mu=0.08),
|
|
1302
|
+
'volatile': sth.Heston(rho=-0.7),
|
|
1303
|
+
'crash': sth.Merton(sigma=0.25, lmbda=25, jump_mu=-0.03, var=0.02**2, mu=-0.2)},
|
|
1304
|
+
durations={'calm': 250, 'volatile': 40, 'crash': 10}, # mean spell, in days
|
|
1305
|
+
switch=[[0, 1, 0], [0.8, 0, 0.2], [0, 1, 0]], # calm -> volatile -> calm or crash
|
|
1306
|
+
length=2520, num_paths=2, seed=1,
|
|
1307
|
+
)
|
|
1308
|
+
bars = market.transform(copula={'calm': gauss, 'volatile': gauss, 'crash': clayton}, ohlc=0.3)
|
|
1309
|
+
regime = market.regime # 1775 calm, 726 volatile and 19 crash days
|
|
1310
|
+
heston = market.models['volatile'] # the model that ran, with its variance
|
|
1311
|
+
|
|
1312
|
+
# A pair that reverts with a 20-day half-life, except in a crash
|
|
1313
|
+
pair = market.transform(cointegrate=np.where(regime == 'crash', np.inf, 20))
|
|
1314
|
+
|
|
1315
|
+
# A fixed stress test: calm, a 20-day crash from day 500, calm again
|
|
1316
|
+
stress = sth.Regimes(
|
|
1317
|
+
{'calm': sth.GeometricBrownianMotion(sigma=0.10), 'crash': sth.Merton(sigma=0.25, lmbda=25)},
|
|
1318
|
+
schedule=np.repeat(['calm', 'crash', 'calm'], [500, 20, 2000]), length=2520, num_paths=2, seed=2,
|
|
1319
|
+
)
|
|
1320
|
+
prices = stress.transform(copula={'crash': clayton}) # independent legs, tied in the crash
|
|
1321
|
+
```
|
|
1322
|
+
|
|
1323
|
+
<picture>
|
|
1324
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/regimes-dark.svg">
|
|
1325
|
+
<img alt="The example's two legs over ten years of regime-switching prices, with volatile spells shaded light grey and crash spells dark grey; the legs move together and the price never gaps at a switch" src="https://raw.githubusercontent.com/ActurialCapital/synthetica/0.4.0/docs/static/regimes-light.svg" width="100%">
|
|
1326
|
+
</picture>
|
|
1327
|
+
|
|
1328
|
+
The example's market over ten years: the shaded spells are the volatile (light) and crash (dark)
|
|
1329
|
+
regimes, and the price never gaps at a switch. Drawn with
|
|
1330
|
+
`market.transform(copula={'calm': gauss, 'volatile': gauss, 'crash': clayton}).sth.paths(model=market)`,
|
|
1331
|
+
which shades the model's `regime`.
|
|
1332
|
+
|
|
1333
|
+
Over 40,000 days of two GBM legs, Gaussian (ρ 0.7, Kendall's τ 0.494) when calm and Clayton (θ 3,
|
|
1334
|
+
τ 0.6) under stress, the calm days fit a Gaussian copula with ρ 0.699 and the stress days a Clayton
|
|
1335
|
+
with θ 2.96: when one leg is in its worst 5%, the other is too on 79% of stress days and 39% of
|
|
1336
|
+
calm days. All 40,000 days together fit a survival Gumbel (τ 0.537), a family in neither regime: a
|
|
1337
|
+
model fitted on a window that mixes regimes gets the tails wrong. Over 802 volatile spells of the
|
|
1338
|
+
example's chain, Heston's variance entering the spell averaged 0.039 (θ = 0.04), where a restart
|
|
1339
|
+
would give `vol0` = 0.0625 every time. Merton's jumps are independent across paths, so the crash
|
|
1340
|
+
days' returns depend less than their copula: in the example's chain they fit a Frank copula with
|
|
1341
|
+
τ 0.48.
|
|
1342
|
+
**Tested:** each step is the active regime's own log return (to 1e-12) and `cointegrate=np.inf`
|
|
1343
|
+
changes nothing; the one-step transitions match `transition` within 5 standard errors over 200,000
|
|
1344
|
+
steps, and the time in each regime matches `shares`; a semi-Markov law gives its exact spells; a `switch` DataFrame is read by its labels; on a
|
|
1345
|
+
random schedule the legs' Kendall's τ is the Gaussian's on calm days and Clayton's on crash days,
|
|
1346
|
+
and 0 for a regime left out of the dict; the open's surprise has each step's regime's variance and
|
|
1347
|
+
copula, and a regime's jumps keep the overnight share; the same seed repeats the prices and the
|
|
1348
|
+
regimes, each regime's model has its own seed, and other durations leave its path unchanged; and
|
|
1349
|
+
15 bad inputs raise, among them a level model, two deltas, a spell under one step, a duration law
|
|
1350
|
+
with an infinite mean, an unknown regime, one chain per path with a matrix or copula, and `LevyStable` with `ohlc`.
|
|
1351
|
+
|
|
1352
|
+
## Charts
|
|
1353
|
+
|
|
1354
|
+
`pip install "python-synthetica[plot]"` adds plotly charts. Every price table gets them as `.sth`, a
|
|
1355
|
+
pandas accessor like vectorbt's `.vbt` (pandas' own `.plot` is untouched):
|
|
1356
|
+
|
|
1357
|
+
```python
|
|
1358
|
+
import synthetica as sth
|
|
1359
|
+
|
|
1360
|
+
model = sth.Bates(756, 2, seed=2)
|
|
1361
|
+
prices = model.transform()
|
|
1362
|
+
prices.sth.paths() # one line per path
|
|
1363
|
+
prices.sth.paths(model=model) # and what the model kept: variance, cycle and spread panels, jump dots, regime spells
|
|
1364
|
+
prices.sth.fan() # a band of the paths' 5-95% quantiles and their median (mean= adds one)
|
|
1365
|
+
prices.sth.ranks() # two paths' return ranks (their copula), joint worst and best days highlighted
|
|
1366
|
+
prices.sth.crashes() # the paths, with a dot on each day all of them are in their worst 5%
|
|
1367
|
+
prices.sth.tails() # P(|r| > x) on a log scale, against a normal
|
|
1368
|
+
model.transform(ohlc=0.3).sth.ohlc() # OHLC bars
|
|
1369
|
+
```
|
|
1370
|
+
|
|
1371
|
+
Each returns a plotly Figure: `.show()` it, save it with `.write_html(...)`, or serve it in Dash.
|
|
1372
|
+
Keyword arguments go to the figure's layout (`title=...`, `height=...`); `theme="dark"` uses the dark
|
|
1373
|
+
palette, and the plotly templates `synthetica` and `synthetica_dark` carry the same look for your
|
|
1374
|
+
own figures. `synthetica.plot` has the same functions, which also take a dict `{title: prices}` and
|
|
1375
|
+
draw one panel per entry, side by side: `sth.plot.paths({"ρ = −0.8": a, "ρ = 0.8": b})`. Every chart
|
|
1376
|
+
in this README is one such call (`docs/save_charts.py`). plotly loads only when a chart is drawn.
|
|
1377
|
+
|
|
1378
|
+
## Reproducibility
|
|
1379
|
+
|
|
1380
|
+
`seed` fixes every random draw:
|
|
1381
|
+
|
|
1382
|
+
- The same seed gives the same values on every call and on every machine with the same versions of
|
|
1383
|
+
numpy (and scipy for `LevyStable`, and the copula library you use).
|
|
1384
|
+
- numpy's global generator is never used or touched: `np.random.seed` has no effect on synthetica,
|
|
1385
|
+
and synthetica does not change your own `np.random` draws.
|
|
1386
|
+
- `seed=None` draws fresh numbers, so each new model differs. One model caches its white noise in
|
|
1387
|
+
`model.white_noise`, so calling `transform()` on it again repeats that noise, while its stream 1
|
|
1388
|
+
to 8 draws (copula draws, cycles, jumps, bars, regimes, ...) are new on each call. Setting `seed`, `mean`, `delta` or
|
|
1389
|
+
`sigma` on the model clears the cache.
|
|
1390
|
+
- The dates are not seeded: an integer `length` gives that many dates at `freq` (daily by default),
|
|
1391
|
+
ending today. Pass a `pd.DatetimeIndex` as `length` to fix them as well.
|
|
1392
|
+
- Two models built with the same seed share the same noise. `GeometricBrownianMotion(seed=1)` and
|
|
1393
|
+
`MeanReverting(seed=1)` get the same white noise, so their shocks are perfectly correlated. Give
|
|
1394
|
+
legs that should be independent different seeds, or simulate them as paths of one model. The same
|
|
1395
|
+
goes for jumps and cycles: `Bates(seed=1)` has `Merton(seed=1)`'s jumps.
|
|
1396
|
+
|
|
1397
|
+
## Testing
|
|
1398
|
+
|
|
1399
|
+
```sh
|
|
1400
|
+
uv run pytest
|
|
1401
|
+
```
|
|
1402
|
+
|
|
1403
|
+
The dev dependencies (pytest, statsmodels, pyvinecopulib) come with `uv sync`.
|
|
1404
|
+
|
|
1405
|
+
| Model | What its test checks |
|
|
1406
|
+
|---|---|
|
|
1407
|
+
| `GeometricBrownianMotion` | Log returns have mean (μ − σ²/2)Δ and variance σ²Δ, and are normal; E[S_T] = S₀e^(μT). |
|
|
1408
|
+
| `Heston` | E[S_T] = S₀e^(r_f T); the realised variance follows the variance process, even with ν = 1 (variance often at zero); volatility clusters. |
|
|
1409
|
+
| `Merton` | E[S_T] = S₀e^(μT) with compensated jumps; step variance σ²Δ + λΔ(jump_mu² + var); fat tails (excess kurtosis above 10, where GBM's is 0.1). |
|
|
1410
|
+
| `LevyStable` | Return quantiles match the stable law with scale σΔ^(1/α); with a matrix, Kendall's τ = (2/π) arcsin ρ. |
|
|
1411
|
+
| `MeanReverting` | The lag-1 coefficient matches the half-life; variance at T is σ²(1 − e^(−2κT))/(2κ); κ = 0 is an exact random walk; no unit root; `mean` must be 0. |
|
|
1412
|
+
| `CIR` | Mean and variance at T match the closed form with the Feller condition violated (2κμ < σ²); rates stay at or above 0; no unit root; `mean` must be 0. |
|
|
1413
|
+
| `AutoRegressive` | Least squares on the lags recovers the coefficients. |
|
|
1414
|
+
| `NARMA` | Inputs are wired right (autocorrelation 3/7 at lag n − 1, 0 at lag n); a matrix ties the inputs, not the outputs; paths stay finite with `'redraw'` (also with a matrix or a copula) and inside (−1, 1) with `'tanh'`. |
|
|
1415
|
+
| `Seasonal` | The mean price matches S₀e^(μt) times the seasonal factor at five dates through the cycle. |
|
|
1416
|
+
| `Cyclical` | The cycle has standard deviation `amplitude` and autocorrelation ρᵏcos(λk); E[S_t] = S₀e^(μt); its cycle shares no random numbers with the other models (lead-lag check against Heston). |
|
|
1417
|
+
| Combined models | Each is its engine's path times its ingredient: `Bates / Heston = Merton / GBM` path by path with one seed, and likewise for the other four; `Bates` keeps E[S_T] = S₀e^(r_f T) with 25 jumps a year; positional arguments reach their parameters in `Merton`, `Seasonal`, `Cyclical` and the combined models; `jumps` and `cycle` are exactly what they add to the GBM path. |
|
|
1418
|
+
| Seeds (every model) | Same seed, same output; another seed, another output; numpy's global generator untouched; right type and shape for many sizes; each ingredient draws from its documented stream, and each regime's model gets its stream-7 seed. |
|
|
1419
|
+
| Copula recovery | A Clayton (θ = 3) or Gumbel (θ = 2.5) copula fitted back from GBM returns: same family, θ within 8%. |
|
|
1420
|
+
| Copula, own innovations | `Heston`, `LevyStable` and `NARMA` outputs carry the copula's Kendall's τ. |
|
|
1421
|
+
| Copula column order | An uneven 3-path vine puts each pair's τ on the right paths. |
|
|
1422
|
+
| Copula plumbing | Every model takes a copula reproducibly; `matrix` with `copula`, or a copula of the wrong dimension, raises. |
|
|
1423
|
+
| `cointegrate` | Every spread is an exact AR(1) with φ = 2^(−1/h), driven by its own shock in the model's output (a pair with a hedge ratio, a break, a late start, a moving level, a basket with a fixed leg, two pairs with their own half-lives); with the default weights all 10 pairs of 5 legs are; the correction at t uses the spreads and the level up to t − 1; `cointegrate=np.inf` returns the model's output; `spreads` is reset on each call; bad inputs raise (booleans, prices of 0 or infinity, a non-finite level, an ambiguous 1-D shape, positional use); the level models refuse it; every price model's `transform` shows it, `ohlc` and the rest keyword-only in its signature and help. |
|
|
1424
|
+
| `ohlc` | The overnight move does not predict the open-to-close move and holds the `ohlc` share (GBM, Heston, Heston from 50, Cyclical, CyclicalHeston, Merton, CyclicalMerton, Bates, `Regimes` of combined models, a cointegrated pair, a moving level); Parkinson's range matches the session's variance; a session jump's dip below min(open, close) and the range match the exact law, a bridge on each side of a uniform jump time; high and low hold open and close; with a matrix the legs' overnight moves correlate at ρ; LevyStable, `ohlc=1` and booleans are refused. |
|
|
1425
|
+
| `Regimes` | Each step is the active regime's own log return; the one-step transitions match `transition` within 5 SE and the time shares `shares`; a semi-Markov law gives its exact spells; `params` lists each regime's model, parameters, spell and share; the legs' Kendall's τ follows each step's regime's copula (0 for a regime left out); the bars' open surprise has each regime's variance and copula, and its jumps keep the overnight share; seeds repeat, each regime's model has its own; 15 bad inputs raise. |
|
|
1426
|
+
| Charts (`tests/test_plot.py`) | Each chart holds the data: one line per path with its colour and label, a model's variance, cycle and spread panels and its jump days, one shaded band per regime spell, the fan's quantiles, median and mean, the return ranks and their joint-tail corners, the joint crash days, the tail curve and its normal, the OHLC fields; dict panels side by side, a path keeping its colour and one legend entry across panels; prices from another transform than the model's last, or one regime chain per path, raise; a `mean` Series sits on its own dates; the tail curve keeps at most 2,000 points; plotly loads on the first chart, and a reload of synthetica is quiet. |
|
|
1427
|
+
| Noise (`tests/test_base.py`) | `matrix` keeps each path's mean and scale and sets the correlation; a matrix that is not positive definite is repaired; the white noise cache and its setters; dates pass through, and an integer `length` gives that many dates at any `freq`. |
|
|
1428
|
+
|
|
1429
|
+
Tolerances are about 5 standard errors of the estimate (or 5 standard deviations over seeds), so a
|
|
1430
|
+
correct model passes for almost any seed, and each test was checked to fail on the bug it guards.
|
|
1431
|
+
|
|
1432
|
+
## Contributing
|
|
1433
|
+
|
|
1434
|
+
Issues and pull requests are welcome. The project uses [uv](https://docs.astral.sh/uv/):
|
|
1435
|
+
|
|
1436
|
+
```sh
|
|
1437
|
+
uv sync # the library and its dev dependencies
|
|
1438
|
+
uv run pytest # the test suite
|
|
1439
|
+
uv run --group docs python docs/save_charts.py # regenerate the README charts (kaleido needs Chrome)
|
|
1440
|
+
```
|
|
1441
|
+
|
|
1442
|
+
## License
|
|
1443
|
+
|
|
1444
|
+
BSD 3-Clause. See [`LICENSE`](https://github.com/ActurialCapital/synthetica/blob/0.4.0/LICENSE).
|