mirror of
https://github.com/manifoldbt/manifoldbt.git
synced 2026-08-24 14:38:04 +00:00
release: v0.3.0
This commit is contained in:
@@ -42,13 +42,14 @@ config = mbt.BacktestConfig(
|
||||
universe=[1],
|
||||
time_range_start=start,
|
||||
time_range_end=end,
|
||||
bar_interval=Interval.hours(12),
|
||||
bar_interval=Interval.hours(1),
|
||||
initial_capital=10_000,
|
||||
execution=mbt.ExecutionConfig(
|
||||
allow_short=False,
|
||||
max_position_pct=0.5,
|
||||
position_sizing_mode="FractionOfInitialCapital",
|
||||
),
|
||||
output_resolution=Interval.hours(1),
|
||||
fees=mbt.FeeConfig.binance_perps(),
|
||||
slippage=Slippage.fixed_bps(2),
|
||||
warmup_bars=30,
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
"""Stochastic Simulation -- synthetic price paths via SDE expression DSL.
|
||||
|
||||
Demonstrates:
|
||||
- Built-in presets (GBM, Heston, Merton, GARCH-JD)
|
||||
- Custom SDE model via string expressions
|
||||
- Stochastic fan chart visualization
|
||||
- CUDA GPU acceleration (device="cuda")
|
||||
- All expressions compile to native Rust — full Rayon / CUDA parallelism
|
||||
|
||||
Usage:
|
||||
python examples/13_stochastic_simulation.py
|
||||
"""
|
||||
import time
|
||||
import manifoldbt as mbt
|
||||
|
||||
N = 10_000_000 # 10M paths
|
||||
DEVICE = "cuda" # "cpu" or "cuda"
|
||||
|
||||
if __name__ == "__main__":
|
||||
# ── 1. Geometric Brownian Motion (preset) ───────────────────────────────
|
||||
print(f"1. GBM preset ({N:,} paths, 252 steps) [{DEVICE}]")
|
||||
t0 = time.perf_counter()
|
||||
result = mbt.run_stochastic(
|
||||
"gbm",
|
||||
s0=100.0,
|
||||
n_paths=N,
|
||||
n_steps=252,
|
||||
dt=1 / 252,
|
||||
params={"mu": 0.05, "sigma": 0.20},
|
||||
seed=42,
|
||||
device=DEVICE,
|
||||
)
|
||||
elapsed = time.perf_counter() - t0
|
||||
print(f" Mean final price: {result['final_price']['mean']:.2f}")
|
||||
print(f" Median max DD: {result['max_drawdown']['percentiles'][3][1]:.2%}")
|
||||
print(f" Elapsed: {elapsed:.3f}s\n")
|
||||
|
||||
# ── 2. Heston stochastic volatility (preset) ────────────────────────────
|
||||
print(f"2. Heston preset ({N:,} paths) [{DEVICE}]")
|
||||
t0 = time.perf_counter()
|
||||
result = mbt.run_stochastic(
|
||||
"heston",
|
||||
s0=100.0,
|
||||
n_paths=N,
|
||||
n_steps=252,
|
||||
dt=1 / 252,
|
||||
params={"mu": 0.05, "kappa": 2.0, "theta": 0.04, "xi": 0.3},
|
||||
seed=42,
|
||||
device=DEVICE,
|
||||
)
|
||||
elapsed = time.perf_counter() - t0
|
||||
print(f" Mean final price: {result['final_price']['mean']:.2f}")
|
||||
print(f" Ann. vol (mean): {result['annualized_vol']['mean']:.2%}")
|
||||
print(f" Elapsed: {elapsed:.3f}s\n")
|
||||
|
||||
# ── 3. Merton Jump Diffusion (preset) ───────────────────────────────────
|
||||
print(f"3. Merton Jump Diffusion ({N:,} paths) [{DEVICE}]")
|
||||
t0 = time.perf_counter()
|
||||
result = mbt.run_stochastic(
|
||||
"merton",
|
||||
s0=100.0,
|
||||
n_paths=N,
|
||||
n_steps=252,
|
||||
dt=1 / 252,
|
||||
params={
|
||||
"mu": 0.05,
|
||||
"sigma": 0.20,
|
||||
"lambda": 1.0, # 1 jump/year on average
|
||||
"mu_j": -0.05, # mean jump = -5%
|
||||
"sigma_j": 0.08, # jump vol = 8%
|
||||
},
|
||||
seed=42,
|
||||
device=DEVICE,
|
||||
)
|
||||
elapsed = time.perf_counter() - t0
|
||||
print(f" Mean final price: {result['final_price']['mean']:.2f}")
|
||||
print(f" Elapsed: {elapsed:.3f}s\n")
|
||||
|
||||
# ── 4. Custom GARCH(1,1) Jump Diffusion ─────────────────────────────────
|
||||
print(f"4. Custom GARCH(1,1) Jump Diffusion ({N:,} paths) [{DEVICE}]")
|
||||
model = mbt.StochasticModel(
|
||||
name="my_garch_jd",
|
||||
drift="mu",
|
||||
diffusion="sqrt(h)",
|
||||
jump_intensity="lambda",
|
||||
jump_size="normal(mu_j, sigma_j)",
|
||||
state_vars={"h": 1e-4},
|
||||
state_update={"h": "omega + alpha * (ret - mu) ** 2 + beta * h"},
|
||||
params={
|
||||
"mu": 0.08,
|
||||
"omega": 1e-6,
|
||||
"alpha": 0.10,
|
||||
"beta": 0.85,
|
||||
"lambda": 5.0,
|
||||
"mu_j": -0.02,
|
||||
"sigma_j": 0.04,
|
||||
},
|
||||
)
|
||||
t0 = time.perf_counter()
|
||||
result = mbt.run_stochastic(
|
||||
model,
|
||||
s0=100.0,
|
||||
n_paths=N,
|
||||
n_steps=252,
|
||||
dt=1 / 252,
|
||||
seed=42,
|
||||
device=DEVICE,
|
||||
)
|
||||
elapsed = time.perf_counter() - t0
|
||||
print(f" Mean final price: {result['final_price']['mean']:.2f}")
|
||||
print(f" Max DD (P5): {result['max_drawdown']['percentiles'][0][1]:.2%}")
|
||||
print(f" Elapsed: {elapsed:.3f}s\n")
|
||||
|
||||
# ── 5. Custom mean-reverting model (CPU — store_paths needs RAM) ────────
|
||||
N_PLOT = 10_000
|
||||
print(f"5. Custom mean-reverting model ({N_PLOT:,} paths) [cpu, store_paths]")
|
||||
mean_rev = mbt.StochasticModel(
|
||||
name="mean_reverting",
|
||||
# Drift pulls price back toward 100
|
||||
drift="kappa * (log(100.0) - log(S))",
|
||||
diffusion="sigma",
|
||||
params={"kappa": 2.0, "sigma": 0.25},
|
||||
)
|
||||
t0 = time.perf_counter()
|
||||
result = mbt.run_stochastic(
|
||||
mean_rev,
|
||||
s0=80.0, # start below mean
|
||||
n_paths=N_PLOT,
|
||||
n_steps=252,
|
||||
dt=1 / 252,
|
||||
seed=42,
|
||||
store_paths=True,
|
||||
device="cpu",
|
||||
)
|
||||
elapsed = time.perf_counter() - t0
|
||||
print(f" Mean final price: {result['final_price']['mean']:.2f} (target: 100)")
|
||||
print(f" Elapsed: {elapsed:.3f}s\n")
|
||||
|
||||
# ── 6. Fan chart visualization ──────────────────────────────────────────
|
||||
print("6. Plotting fan chart...")
|
||||
mbt.plot.stochastic_paths(
|
||||
result,
|
||||
title=f"Mean-reverting model (S0=80, target=100, {N_PLOT:,} paths)",
|
||||
show=True,
|
||||
)
|
||||
@@ -0,0 +1,84 @@
|
||||
"""Multi-Timeframe Strategy -- trend on 12h, entry on 1h.
|
||||
|
||||
Demonstrates:
|
||||
- bt.tf() for referencing higher-timeframe columns
|
||||
- extra_timeframes config to inject resampled OHLCV
|
||||
- Combining slow trend filter (12h EMA) with faster entry (1h RSI)
|
||||
|
||||
Logic:
|
||||
- 12h trend: EMA(20) > EMA(50) → bullish regime
|
||||
- 1h entry: RSI(14) < 35 during bullish regime → buy the dip
|
||||
- Size: 50% of initial capital when conditions met, else flat
|
||||
|
||||
Usage:
|
||||
python examples/14_multi_timeframe.py
|
||||
"""
|
||||
import os
|
||||
import time
|
||||
import manifoldbt as mbt
|
||||
from manifoldbt.indicators import ema, rsi, close
|
||||
from manifoldbt.helpers import time_range, Slippage, Interval
|
||||
|
||||
# -- Higher timeframe references ---------------------------------------------
|
||||
h12 = mbt.tf("12h") # references columns like "12h.close"
|
||||
|
||||
# -- Indicators ---------------------------------------------------------------
|
||||
# Trend filter on 12-hour bars (forward-filled onto 1h grid)
|
||||
trend_fast = ema(h12.close, 20)
|
||||
trend_slow = ema(h12.close, 50)
|
||||
bullish = trend_fast > trend_slow
|
||||
|
||||
# Entry signal on 1-hour bars (native resolution)
|
||||
entry_rsi = rsi(close, 14)
|
||||
dip = entry_rsi < 35.0
|
||||
|
||||
# -- Strategy -----------------------------------------------------------------
|
||||
strategy = (
|
||||
mbt.Strategy.create("multi_tf_trend_dip")
|
||||
.signal("bullish", bullish)
|
||||
.signal("entry_rsi", entry_rsi)
|
||||
.signal("dip", dip)
|
||||
.size(mbt.when(mbt.col("bullish") & mbt.col("dip"), 0.5, 0.0))
|
||||
.stop_loss(pct=3.0)
|
||||
.describe("12h EMA trend + 1h RSI dip-buy, 3% stop-loss")
|
||||
)
|
||||
|
||||
# -- Config -------------------------------------------------------------------
|
||||
start, end = time_range("2022-01-01", "2025-01-01")
|
||||
|
||||
config = mbt.BacktestConfig(
|
||||
universe=[1],
|
||||
time_range_start=start,
|
||||
time_range_end=end,
|
||||
bar_interval=Interval.hours(1),
|
||||
initial_capital=10_000,
|
||||
execution=mbt.ExecutionConfig(
|
||||
allow_short=False,
|
||||
max_position_pct=0.5,
|
||||
position_sizing_mode="FractionOfInitialCapital",
|
||||
),
|
||||
fees=mbt.FeeConfig.binance_perps(),
|
||||
slippage=Slippage.fixed_bps(2),
|
||||
warmup_bars=50,
|
||||
extra_timeframes={
|
||||
"12h": Interval.hours(12),
|
||||
},
|
||||
)
|
||||
|
||||
# -- Run ----------------------------------------------------------------------
|
||||
if __name__ == "__main__":
|
||||
root = os.path.join(os.path.dirname(__file__), "..")
|
||||
store = mbt.DataStore(
|
||||
data_root=os.path.abspath(os.path.join(root, "data")),
|
||||
metadata_db=os.path.abspath(os.path.join(root, "metadata", "metadata.sqlite")),
|
||||
)
|
||||
|
||||
t0 = time.perf_counter()
|
||||
result = mbt.run(strategy, config, store)
|
||||
elapsed = time.perf_counter() - t0
|
||||
|
||||
|
||||
print(result.summary())
|
||||
print(f"\nElapsed: {elapsed:.3f}s")
|
||||
|
||||
mbt.plot.equity(result, show=True)
|
||||
Reference in New Issue
Block a user