import json
from math import sqrt
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from bars import load_bars, validate_bars
def targets(close, fast=3, slow=5, *, short=False):
if not 1<=fast<slow:
raise ValueError("Require 1 <= fast < slow")
spread = close.rolling(fast).mean()-close.rolling(slow).mean()
direction = (spread>0).astype(int)
if short:
direction -= (spread<0).astype(int)
return direction.rename("target")
def simulate(frame, target, *, fee=0, slippage=0):
if not 0<=fee<.25 or not 0<=slippage<.25:
raise ValueError("Set valid per-unit turnover rates")
data = validate_bars(frame)
if len(data)<2 or not target.index.equals(data.index) or not target.isin([-1,0,1]).all():
raise ValueError("Supply aligned positions and at least two bars")
position = target.shift(1,fill_value=0).iloc[:-1]
turnover = position.sub(position.shift(1,fill_value=0)).abs()
move = data["open"].shift(-1).div(data["open"]).sub(1).iloc[:-1]
net = (1-turnover*(fee+slippage))*(1+position*move)-1
if (net<=-1).any():
raise ValueError("Nonpositive equity: model requires separate margin handling")
equity = pd.Series(np.r_[1.,(1+net).cumprod().to_numpy()],index=data.index,name="equity")
ledger = pd.DataFrame({"position":position,"turnover":turnover,"gross":position*move,"net":net,
"mark_at":data.index[1:]})
return equity,ledger
def metrics(equity, periods=252, annual_rf=0.0):
daily = equity.pct_change(fill_method=None).iloc[1:]
deviation = daily.std(ddof=1)
risk_free = (1+annual_rf)**(1/periods)-1
return dict(total=equity.iloc[-1]/equity.iloc[0]-1,
annual=(equity.iloc[-1]/equity.iloc[0])**(periods/len(daily))-1,
vol=deviation*sqrt(periods) if pd.notna(deviation) else None,
sharpe=(daily.mean()-risk_free)/deviation*sqrt(periods) if pd.notna(deviation) and deviation>0 else None,
max_drawdown=float((1-equity/equity.cummax()).max()))
def render(strategy, baseline, output):
fig,ax = plt.subplots(figsize=(8.8,4.0),layout="constrained")
ax.plot(strategy.index,strategy,label="Long / cash",color="#08779b",marker=".",linewidth=1.9)
ax.plot(baseline.index,baseline,label="Buy and hold",color="#ad6212",linewidth=1.6)
ax.set(title="Blue Sky | Net equity marked at the open",ylabel="Starting equity = 1",xlabel="Synthetic session")
ax.grid(alpha=.25)
ax.legend()
ax.tick_params(axis="x",labelrotation=35)
fig.savefig(output,dpi=140)
plt.close(fig)
def main():
frame = load_bars("synthetic-prices.csv")
rules = targets(frame["close"])
strategy,_ = simulate(frame,rules,fee=.001,slippage=.001)
hold = frame["open"]/frame["open"].iloc[0]*(1-.002)
hold.iloc[0]=1
render(strategy,hold,Path("backtest.png"))
print(json.dumps({"strategy":metrics(strategy),"baseline":metrics(hold)},ensure_ascii=False))
if __name__=="__main__":
main()
本例需在 CPython 3.12.14、Pandas 3.1.0;图表用 Pyecharts 2.1.0、ECharts 6.1.0 和本机 Edge 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12.14、Pandas 3.1.0;图表用 Pyecharts 2.1.0、ECharts 6.1.0 和本机 Edge
入口文件:projects/quant-execution/backtest.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
backtest.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12.14、Pandas 3.1.0;图表用 Pyecharts 2.1.0、ECharts 6.1.0 和本机 Edge。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联2章) · 含当前章节或实例 · mbskycom202612a305.zip
课程关联工程包(登记关联20章) · 含当前章节或实例 · mbskycom202612a303.zip