蓝色天空网mbsky.com · 知识 · 实践 · 创造量化交易 · 本地阅读预览
教程 / Python / 数据科学 / 量化交易

通道突破的信号、成交与回撤

用先前收盘通道产生趋势信号,再按次期开盘、费用和真实持仓记账。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

历史规则与本章的成交口径

Richard Dennis 与 William Eckhardt 在 1983 年末训练了首批被称为海龟的期货交易学员。原系统使用前期高低价的盘中突破,另有更长周期、加仓、保护性止损、过滤和组合限制。公开规则中的 N 表示以真实波幅平滑得到的波动量,用来确定头寸单位。

本站用单一标的、只做多的收盘信号演示 20/10 通道,盘中高低价突破与下一开盘成交是不同模型。仓位风险预算单独演算,回测主例用现金或满仓状态,便于隔离信号和成交。

通道使用当时能看到的数据

收盘时把当前价格同前 20 个收盘的最大值比较,已有多头时对照前 10 个收盘的最小值。先滚动再 shift(1) 才能让当前价与旧通道分开。若当期收盘参与上轨且仍用严格大于,突破永远不能触发。窗口没满时不产生该窗口的信号。

在空仓状态下只评估入场,在持仓状态下只评估离场。等于通道边界不触发。样本前 20 条为 100,第 21 条 110 产生入场信号,随后 90 跌破前 10 条的下轨 100。改动最后一条行情不会改变此前已形成的信号。

标记信号、开盘与实际成交价

收盘信号在下一条开盘才能执行,最后一条若无后续开盘就仍是待执行信号。把昨日仓位乘以今日收盘变化可以作一种简化收益记账,但无法重建下一开盘及其跳空。本站逐期维护现金、份额和收盘估值,滑点按买高卖低计,佣金按成交金额计。

震荡样本第一次信号收在 110,下一期开在 114,假定滑点后的买价为 114.228。当天收在 111,因此入场后的首日净值低于 1。图上空心三角标收盘信号,实心三角标次期开盘按假定滑点后的成交。最后一个空心标记没有对应成交。

以下同图下半部分比较策略和买入持有净值,两者采用同一评估窗口与费用模型。基准在首个可执行开盘买入并持有,终点按收盘估值,未人为补记清仓。

合成收盘通道、次开成交及策略基准净值
本站合成实验。空心为信号,实心为模拟成交,下图为同口径净值。

绩效统计与市场情景

复利用净值终值与初值之比,年化按实际收益期数换算。最大回撤用每个净值相对此前最高值的跌幅,本章记为正数。夏普以平均同频超额收益除以该收益的标准差再按频率换算,与用复合年化收益除以波动的旧公式分开。标准差为零时不给夏普数值。

合成上涨路径中,等到突破才买会晚于基准。下跌路径中无多头成交,策略保持现金。震荡路径中反复进出导致亏损,成本会进一步压低终值。各种路径只展示机制,真实涨跌幅、排队、停牌、分红、借券和跳空均要另建模型。

成交次数按真实成交记,同时报告买入和卖出。收盘信号计数、单边成交笔数和完整往返次数分别保存。历史股票结果及其具体数值仍待用相符行情版本核验。

用 ATR 单独演算风险预算

先定义账户预算与止损距离。例如权益 1 万元,假定每笔预算 1%,止损距离为 2 倍 ATR,点值为 1。ATR 为 2 时风险约束给 25 单位,ATR 为 5 时给 10 单位。现金、合约点值、交易单位和手续费会进一步限制可成交量。

预算设定不是最大实际亏损保证。资料有时用 2% 描述某种止损预算,须区分账户预算、每个 N 的金额、止损距离与叠加单位。零或缺失 ATR 时先不定仓位,跳空和价格限制可能使成交偏离保护价。

把 20/10 规则拆成可验证动作

动作输入、条件与输出
入场信号空仓且收盘严格超过前 20 条最高收盘,次期开盘执行
离场信号持仓且收盘严格低于前 10 条最低收盘,次期开盘执行
ATR 风险预算波动距离与点值决定数量,再施加资金限制

策略与基准的同口径评价

指标计算与可比条件
累计净值变动同一起始时点和成本,观察延迟入场及保持现金
最大回撤逐期比较既往净值峰值,输出正跌幅
夏普同频超额收益和标准差,零波动不定义

三种合成市场路径

路径观察与适用边界
上涨有意延迟突破,买入持有先暴露于上涨
下跌无入场信号时持有现金,已有仓位可能在退出前亏损
震荡反复的假突破和次开成交产生损失,成本进一步影响

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

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 第一次收盘信号价 110,次期开盘 114,模拟成交 114.228。震荡样本实际成交 10 笔,末条入场信号因缺少下一开盘而不执行。
运行通道、次开成交、绩效和 ATR 仓位预算

所需环境:隔离 CPython 3.12.14、NumPy 2.5.4、Pandas 3.1.0、Matplotlib 3.11.2

当前源码 SHA256:6ad1492ca0c57b51896cf9cf0759425c2f641eeabc4108f08033ec20f46e8160

下载本站示例源码

离线趋势实验

解压后按 README 安装依赖并运行 Python 程序。输出行情状态、成交、风险预算与绩效,目录中生成对比图。

下载趋势突破实验 ZIP

所需环境:隔离 CPython 3.12.14、NumPy 2.5.4、Pandas 3.1.0、Matplotlib 3.11.2

ZIP SHA256:14afda570ed754d605f689e9a1629e5b7b85172de3e7431d9eb16f45cdd06230

常见错误与边界

  • 信号时点、成交时点、成交价和估值时点应分别保存。不要从合成路径推断实际策略收益。

练习与解答

为什么把当前收盘也放进上轨后,严格突破不会触发?

展开参考解答

最大值至少等于当前收盘,因此当前值不可能严格大于包含自身的最大值。

规范与官方依据