蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行通道、次开成交、绩效和 ATR 仓位预算

PYTHON隔离 CPython 3.12.14、NumPy 2.5.4、Pandas 3.1.0、Matplotlib 3.11.2trend.py
trend.py183 行
"""Replay a long-only closing breakout with explicit next-open fills."""
import json
from math import floor, isfinite
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


ENTRY, EXIT = 20, 10
START = ENTRY + 1


def bars(closes, first_gap=0):
    closes = np.asarray(closes,dtype="float64")
    openings = np.r_[closes[0],closes[:-1]]
    openings[START] += first_gap
    dates = pd.bdate_range("2024-03-04",periods=len(closes))
    return pd.DataFrame({"open":openings,"close":closes},index=dates)


def signals(frame, entry=ENTRY, exit_window=EXIT):
    close = frame["close"]
    if (frame[["open","close"]]<=0).any().any() or not np.isfinite(frame[["open","close"]]).all().all():
        raise ValueError("Open and close must be finite positive prices")
    if not frame.index.is_unique or not frame.index.is_monotonic_increasing:
        raise ValueError("One ordered record per session required")
    upper = close.rolling(entry,min_periods=entry).max().shift(1)
    lower = close.rolling(exit_window,min_periods=exit_window).min().shift(1)
    held = False
    states, events = [], []
    for index,price in enumerate(close):
        if not held and price>upper.iloc[index]:
            held = True
            events.append((index,"entry"))
        elif held and price<lower.iloc[index]:
            held = False
            events.append((index,"exit"))
        states.append(int(held))
    return upper,lower,np.asarray(states),events


def simulate(frame, target, *, fee=.001, slippage=.002):
    cash,shares = 1.,0.
    equity = [cash]
    fills = []
    for day in range(START,len(frame)):
        target_position = target[day-1]
        opening,closing = frame.iloc[day][["open","close"]]
        if target_position and shares==0:
            fill = float(opening*(1+slippage))
            shares = cash/(fill*(1+fee))
            fills.append(dict(day=day,signal_day=day-1,side="buy",open=float(opening),price=fill,
                              fee=float(shares*fill*fee)))
            cash = 0.
        elif not target_position and shares>0:
            fill = float(opening*(1-slippage))
            gross = shares*fill
            fills.append(dict(day=day,signal_day=day-1,side="sell",open=float(opening),price=fill,
                              fee=float(gross*fee)))
            cash = gross*(1-fee)
            shares = 0.
        equity.append(float(cash+shares*closing))
    return np.asarray(equity),fills


def performance(equity,annual_risk_free=.03):
    returns=equity[1:]/equity[:-1]-1
    cumulative=float(equity[-1]/equity[0]-1)
    annual=float((1+cumulative)**(252/len(returns))-1)
    spread=float(returns.std(ddof=1))
    periods=np.maximum.accumulate(equity)
    drawdown=float((1-equity/periods).max())
    daily_rf=(1+annual_risk_free)**(1/252)-1
    sharpe=float((returns.mean()-daily_rf)*np.sqrt(252)/spread) if spread>0 else None
    return dict(observed_periods=len(returns),cumulative=cumulative,cagr=annual,
                annual_volatility=spread*np.sqrt(252),max_drawdown=drawdown,sharpe=sharpe)


def atr_size(equity,cash,entry_price,atr,*,risk=.01,stop_multiple=2,point_value=1):
    if not all(isfinite(value) and value>0 for value in
               (equity,cash,entry_price,atr,risk,stop_multiple,point_value)):
        raise ValueError("Need positive finite inputs and valid ATR")
    units_by_risk=floor(equity*risk/(atr*stop_multiple*point_value))
    units_by_cash=floor(cash/(entry_price*point_value))
    return min(units_by_risk,units_by_cash)


def plot(frame,upper,lower,events,fills,equity,baseline,output):
    fig,axes=plt.subplots(2,1,figsize=(8,6),sharex=True,layout="constrained")
    price,nav=axes
    price.plot(frame.index,frame.close,color="#203952",label="Close")
    price.plot(upper,"--",color="#147e6d",label="Prior 20 closes: max")
    price.plot(lower,"--",color="#a64d33",label="Prior 10 closes: min")
    for action,color,marker in (("entry","#168870","^"),("exit","#b55735","v")):
        points=[index for index,kind in events if kind==action]
        price.scatter(frame.index[points],frame.close.iloc[points],facecolors="none",edgecolors=color,
                      marker=marker,s=52,label=f"{action.title()} signal")
    for side,color,marker in (("buy","#168870","^"),("sell","#b55735","v")):
        trades=[trade for trade in fills if trade["side"]==side]
        price.scatter(frame.index[[trade["day"] for trade in trades]],[trade["price"] for trade in trades],
                      color=color,marker=marker,s=38,label=f"{side.title()} fill")
    nav.plot(frame.index[START:],equity[1:],color="#147e6d",label="Breakout")
    nav.plot(frame.index[START:],baseline[1:],color="#3b5a91",label="Buy and hold")
    nav.axhline(1,color="#62707b",linewidth=.8)
    price.set(title="Close decisions and next-open fills",ylabel="Synthetic price")
    nav.set(ylabel="Equity after close",xlabel="Synthetic session")
    for axis in axes:
        axis.grid(alpha=.2)
        axis.legend(ncols=3,loc="upper left",fontsize=8)
    fig.autofmt_xdate()
    fig.savefig(output,dpi=120)
    plt.close(fig)


def main():
    rising=bars([100.]*21+list(range(101,132)))
    falling=bars(range(150,98,-1))
    choppy=bars([100.]*20+[110,111,90,89,112,113,88,87,114,115,86,85,
                            116,117,84,83,118,119,82,81,120],first_gap=4)
    upper,lower,target,events=signals(choppy)
    assert pd.isna(upper.iloc[19]) and upper.iloc[20]==100 and lower.iloc[22]==100
    assert events[:2]==[(20,"entry"),(22,"exit")] and events[-1]==(40,"entry")
    current_included=choppy.close.rolling(ENTRY).max()
    assert not (choppy.close>current_included).any()
    flat=bars([100.]*41)
    assert signals(flat)[3]==[]
    changed=choppy.copy()
    changed.iloc[-1,changed.columns.get_loc("close")]=200
    assert signals(changed)[3][:-1]==events[:-1]

    examples = {}
    for name,frame in (("rising",rising),("falling",falling),("choppy",choppy)):
        _,_,signal,source_events=signals(frame)
        nav,fills=simulate(frame,signal)
        benchmark,_=simulate(frame,np.ones(len(frame),dtype=int))
        free,_=simulate(frame,signal,fee=0,slippage=0)
        assert len(nav)==len(benchmark) and free[-1]>=nav[-1]-1e-12
        assert all(row["day"]==row["signal_day"]+1 for row in fills)
        examples[name]=dict(strategy=performance(nav),baseline=performance(benchmark),
            entries=sum(side=="entry" for _,side in source_events),fills=len(fills),
            filled_buys=sum(row["side"]=="buy" for row in fills),
            filled_sells=sum(row["side"]=="sell" for row in fills),free_terminal_equity=float(free[-1]))
    assert examples["falling"]["fills"]==0 and examples["falling"]["strategy"]["cumulative"]==0
    assert examples["falling"]["strategy"]["sharpe"] is None and examples["falling"]["baseline"]["cumulative"]<0
    assert 0<examples["rising"]["strategy"]["cumulative"]<examples["rising"]["baseline"]["cumulative"]
    assert examples["choppy"]["strategy"]["cumulative"]<0 and examples["choppy"]["fills"]==10

    nav,fills=simulate(choppy,target)
    benchmark,_=simulate(choppy,np.ones(len(choppy),dtype=int))
    assert fills[0]["open"]==114 and np.isclose(fills[0]["price"],114.228) and nav[1]<1
    assert fills[-1]["day"]==39 and all(row["signal_day"]!=40 for row in fills)
    assert np.isclose(performance(np.array([1.,1.1,.99,1.02]))["max_drawdown"],.1)
    output=Path("breakout-fills.png")
    plot(choppy,upper,lower,events,fills,nav,benchmark,output)

    sizes=[atr_size(10000,10000,100,value) for value in (2.,5.)]
    constrained=atr_size(10000,150,100,2.)
    assert sizes==[25,10] and constrained==1
    try:
        atr_size(10000,10000,100,0.)
    except ValueError:
        invalid_atr_rejected=True
    else:
        raise AssertionError("Zero ATR accepted")
    print(json.dumps(dict(
        channels=dict(first_signal=events[0],first_exit=events[1],last_pending=events[-1],
                      first_upper=float(upper.iloc[20]),first_exit_lower=float(lower.iloc[22]),
                      current_inclusive_breakouts=int((choppy.close>current_included).sum()),ties_trigger=False),
        execution=dict(first_fill=fills[0],last_fill=fills[-1],fills=fills,first_close_equity=float(nav[1])),
        regimes=examples,sizing=dict(units=sizes,cash_capped_units=constrained,zero_atr_rejected=invalid_atr_rejected),
        versions=dict(python=python_version(),numpy=np.__version__,pandas=pd.__version__,
                      matplotlib=matplotlib.__version__)
    ),indent=2,allow_nan=False))


if __name__=="__main__":
    main()
本例需在 隔离 CPython 3.12.14、NumPy 2.5.4、Pandas 3.1.0、Matplotlib 3.11.2 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:隔离 CPython 3.12.14、NumPy 2.5.4、Pandas 3.1.0、Matplotlib 3.11.2

入口文件:projects/quant-trend/trend.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 trend.py,或下载右侧课程工程包。
  2. 确认本地已准备 隔离 CPython 3.12.14、NumPy 2.5.4、Pandas 3.1.0、Matplotlib 3.11.2。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:量化交易

课程关联工程包(登记关联20章) · 含当前章节或实例 · mbskycom202612a303.zip

下载课程关联工程包:量化交易

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a316.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习