"""Time-ordered dual-moving-average research with fixed synthetic prices."""
import json
from pathlib import Path
from platform import python_version
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
FAST=(5,10,15,20,25,30)
SLOW=(40,60,80,100,120)
WARMUP=max(SLOW)+1
FEE=.001
def fixture():
rng=np.random.default_rng(1801)
t=np.arange(780)
regimes=np.repeat([.0012,.0004,-.0010,.0010,-.0006,.0003],130)
changes=regimes+.004*np.sin(t/8)+rng.normal(0,.006,len(t))
close=pd.Series(100*np.exp(changes.cumsum()))
opening=np.r_[close.iloc[0],close.iloc[:-1].to_numpy()]*(1+.002*np.cos(t))
return close,opening
def positions(close,fast,slow):
fast_average=close.rolling(fast,min_periods=fast).mean()
slow_average=close.rolling(slow,min_periods=slow).mean()
return (fast_average>slow_average).shift(1,fill_value=False).to_numpy(dtype=int)
def ledger(held,asset_returns,fee=FEE):
turnover=np.abs(np.diff(np.r_[0,held]))
growth=(1+held*asset_returns)*(1-fee*turnover)
growth[-1]*=1-fee*held[-1] # Close any last position at the boundary.
equity=np.r_[1.,np.cumprod(growth)]
return dict(cumulative=float(equity[-1]-1),annualized=float(equity[-1]**(252/len(held))-1),
max_drawdown=float((1-equity/np.maximum.accumulate(equity)).max()),
turnover=int(turnover.sum()+held[-1]),periods=len(held))
def period(opening,start,end):
# Score opening[start] to opening[end], with exactly end-start intervals.
return opening[start+1:end+1]/opening[start:end]-1
def grid(close,opening,start,end):
asset=period(opening,start,end)
return pd.DataFrame(
[[ledger(positions(close,f,s)[start:end],asset)["annualized"] for f in FAST] for s in SLOW],
index=SLOW,columns=FAST)
def choose(scores):
slow,fast=scores.stack().idxmax()
return int(fast),int(slow)
def neighborhood(scores,fast,slow):
row,col=scores.index.get_loc(slow),scores.columns.get_loc(fast)
adjacent=scores.iloc[max(0,row-1):row+2,max(0,col-1):col+2].to_numpy().ravel()
return dict(center=float(scores.loc[slow,fast]),neighbor_median=float(np.median(adjacent)),
neighborhood_min=float(adjacent.min()),neighborhood_max=float(adjacent.max()))
def search(close,opening,output):
boundary=540
training=grid(close,opening,WARMUP,boundary-1)
fast,slow=choose(training)
assert training.shape==(5,6) and training.loc[slow,fast]==training.to_numpy().max()
fitted=positions(close,fast,slow)
test=period(opening,boundary,len(close)-1)
holdout=ledger(fitted[boundary:-1],test)
benchmark=ledger(np.ones(len(test),dtype=int),test)
full=grid(close,opening,WARMUP,len(close)-1)
modified=close.copy()
modified.iloc[boundary:]*=np.linspace(1.3,.7,len(close)-boundary)
altered_open=opening.copy()
altered_open[boundary:]*=np.linspace(.8,1.4,len(close)-boundary)
pd.testing.assert_frame_equal(training,grid(modified,altered_open,WARMUP,boundary-1))
assert np.array_equal(fitted[:boundary],positions(modified,fast,slow)[:boundary])
assert not np.array_equal(full.to_numpy(),grid(modified,altered_open,WARMUP,len(close)-1).to_numpy())
surface=pd.DataFrame([[.12,.12,.12,.01,.01],[.12,.12,.12,.01,.01],[.12,.12,.12,.01,.22]],
index=[40,60,80],columns=[5,10,15,20,25])
plateau=neighborhood(surface,10,60)
spike=neighborhood(surface,25,80)
assert plateau["neighborhood_max"]==plateau["neighborhood_min"]==.12
assert spike["center"]==.22 and spike["neighbor_median"]==.01
fig,ax=plt.subplots(figsize=(8,4.6),layout="constrained")
layer=ax.imshow(training.to_numpy()*100,cmap="RdYlGn",aspect="auto")
ax.set(xticks=range(len(FAST)),xticklabels=FAST,yticks=range(len(SLOW)),yticklabels=SLOW,
xlabel="Fast observations",ylabel="Slow observations",title="Training-only annualized net return (%)")
for row,slow_label in enumerate(SLOW):
for col,fast_label in enumerate(FAST):
ax.text(col,row,f"{100*training.loc[slow_label,fast_label]:.1f}",ha="center",va="center",fontsize=8)
ax.scatter(FAST.index(fast),SLOW.index(slow),s=460,marker="s",facecolors="none",edgecolors="#253550",linewidths=1.6)
fig.colorbar(layer,ax=ax,label="Percent")
fig.savefig(output,dpi=120); plt.close(fig)
return dict(grid=training.to_numpy().tolist(),shape=list(training.shape),fast=list(FAST),slow=list(SLOW),
plateau=plateau,spike=spike,selection=[fast,slow],full_data_selection=choose(full),
train_end=boundary-1,holdout_start=boundary,train_grid_unchanged=True,
holdout=holdout,holdout_buy_hold=benchmark,training_optimum=float(training.loc[slow,fast])),fitted[boundary:-1],test
def walk_forward(close,opening):
folds=[]
for start in (270,370,470,570,670):
end=start+100
train_end=start-1
fit=grid(close,opening,WARMUP,train_end)
fast,slow=choose(fit)
held=positions(close,fast,slow)[start:end]
actual=ledger(held,period(opening,start,end))
assert train_end<start and actual["periods"]==100
folds.append(dict(train_start=WARMUP,train_end=train_end,test_start=start,test_end=end,
selected=[fast,slow],training_annualized=float(fit.loc[slow,fast]),test=actual))
assert all(previous["test_end"]==following["test_start"] for previous,following in zip(folds,folds[1:]))
stitched=float(np.prod([1+fold["test"]["cumulative"] for fold in folds])-1)
return dict(folds=folds,stitched_net_return=stitched,reset_and_terminal_liquidation_per_fold=True)
def null_reference(held,asset):
rng=np.random.default_rng(399)
actual=ledger(held,asset)["cumulative"]
permuted=[]
for _ in range(499):
random=rng.permutation(held)
assert random.sum()==held.sum()
permuted.append(ledger(random,asset)["cumulative"])
circular=[]
for offset in range(1,len(held)):
shifted=np.roll(held,offset)
assert shifted.sum()==held.sum()
circular.append(ledger(shifted,asset)["cumulative"])
def summarize(values):
return dict(draws=len(values),tail_fraction=(1+sum(v>=actual for v in values))/(len(values)+1),
median=float(np.median(values)),range=[float(min(values)),float(max(values))])
return dict(actual=actual,independent_shuffle=summarize(permuted),circular_shift=summarize(circular),
same_exposure_count=True,fee_applied_each_replay=True)
if __name__=="__main__":
close,opening=fixture()
search_results,held,asset=search(close,opening,Path("training-grid.png"))
report=dict(search=search_results,walk_forward=walk_forward(close,opening),null=null_reference(held,asset),
versions=dict(python=python_version(),pandas=pd.__version__,numpy=np.__version__,matplotlib=matplotlib.__version__))
print(json.dumps(report,indent=2,allow_nan=False))
本例需在 隔离 CPython 3.12.14、Pandas 3.1.0、NumPy 2.5.4、Matplotlib 3.11.2 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:隔离 CPython 3.12.14、Pandas 3.1.0、NumPy 2.5.4、Matplotlib 3.11.2
入口文件:projects/quant-optimization/optimization.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
optimization.py,或下载右侧课程工程包。 - 确认本地已准备 隔离 CPython 3.12.14、Pandas 3.1.0、NumPy 2.5.4、Matplotlib 3.11.2。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a310.zip
课程关联工程包(登记关联20章) · 含当前章节或实例 · mbskycom202612a303.zip