查看全课大纲(第 26 / 59 节)
  1. 1.量化投资必备基础知识
  2. 2.趋势型策略及模型原理
  3. 3.均值回复型策略及模型原理
  4. 4.配对交易策略及模型原理
  5. 5.量化策略研发流程与基本技能
  6. 6.常用的量化平台概述及如何选择
  7. 7.如何量化一个主观策略思路
  8. 8.常用技术指标及指标计算过程
  9. 9.如何编写指标代码
  10. 10.指标的物理意义
  11. 11.技术指标的应用技巧
  12. 12.更多的交易决策
  13. 13.编写程序去量化一个趋势型技术指标
  14. 14.编写趋势型技术指标的性能评价
  15. 15.策略对交易成本和持仓周期的影响
  16. 16.股票池策略的原理及基本框架
  17. 17.基于多因子分析的股票池设计与实现
  18. 18.股票池的性能评估
  19. 19.使用定制化财务因子构建股票池
  20. 20.趋势型策略原理及股票池机制的设计
  21. 21.趋势型择时信号的设计方法与编程实现
  22. 22.趋势型策略的回测与性能评估
  23. 23.优化趋势型策略的思路及方法
  24. 24.量化体系中的风险控制思想
  25. 25.风险的度量-波动率
  26. 26.常用的风险控制方法
  27. 27.实现止盈止损模块以提高策略性能
  28. 28.策略性能的评估与优化
  29. 29.探讨波动率与风险的关系
  30. 30.量化策略中的经典资金管理模型
  31. 31.用python编程实现资金管理模块
  32. 32.构建一个完善的量化交易策略
  33. 33.趋势型量化策略必备的期货知识
  34. 34.期货量化工具介绍
  35. 35.商品期货趋势型策略原理
  36. 36.用TB编写商品期货趋势型策略(上)
  37. 37.用TB编写商品期货趋势型策略(下)
  38. 38.分析优化商品期货趋势型策略的方法思路
  39. 39.期货交易策略的注意事项
  40. 40.均值回复型策略的原理
  41. 41.A股市场有没有稳定的均值回复效应?
  42. 42.编写一个均值回复型股票量化策略
  43. 43.编写多空组合策略进行策略改进
  44. 44.在策略中实现头寸管理进行策略优化
  45. 45.套利策略原理及常见套利类型
  46. 46.用MC开发一个跨品种套利交易策略(上)
  47. 47.用MC开发一个跨品种套利交易策略(下)
  48. 48.统计套利之股票配对交易策略
  49. 49.实盘中的细节问题:加减仓
  50. 50.关于高频交易
  51. 51.如何评价实盘量化策略的性能
  52. 52.量化系统的工作过程及研发流程
  53. 53.运气or实力
  54. 54.量化实盘交易需要满足什么条件
  55. 55.未来函数的坑
  56. 56.实盘数据接口异常的自动报警
  57. 57.交易系统的压力测试
  58. 58.自动运行的交易策略,什么时候需要人工干预
  59. 59.预案准备和实盘心理建设

常用的风险控制方法

约 18 分钟

📺 正在播放小象学院官方高清录播(支持倍速与清晰度调节)

小象实战讲义 · 进阶量化交易实战:迭代式的量化策略研发 本讲义仅用于编程与量化方法教学,不构成任何投资建议。

控制风险并非简单地减少交易,而是建立系统化的多维度风控边界。本节深入剖析量化交易中最常用的四大风控工具:固定金额止损、移动跟踪止损(Trailing Stop)、时间止损以及基于波动率(ATR)的自适应止损带设计。

💡 核心导读

  • 四大经典量化风控手段:
    • 固定比例止损(Hard Stop):亏损达到建仓本金的固定百分比(如 2%~5%)无条件离场;
    • 移动跟踪止损(Trailing Stop):从持仓期间的最高盈利点回撤特定幅度平仓,锁定已实现浮盈;
    • 时间止损(Time Stop):开仓后 TT 个 Bar 内未能脱离成本区或突破预设阻力,主动平仓释放资金效率;
    • ATR 吊灯止损(Chandelier Exit):以持仓最高价减去 k×ATRk \times ATR 作为动态止损线下轨。
┌─────────────────────────────────────────────────────────────┐
│                    四大常用风控工具逻辑执行拓扑图           │
└──────────────────────────────┬──────────────────────────────┘
                               │
 ┌─────────────────────────────┼─────────────────────────────┐
 ▼                             ▼                             ▼
┌─────────────────────────┐   ┌─────────────────────────┐   ┌─────────────────────────┐
│ 固定金额/比例止损       │   │ 移动跟踪止损 (Trailing) │   │ ATR 吊灯动态止损        │
├─────────────────────────┤   ├─────────────────────────┤   ├─────────────────────────┤
│ • EntryPrice * (1 - 2%) │   │ • PeakPrice * (1 - 5%)  │   │ • PeakPrice - 3.0 * ATR │
│ • 截断单笔不可控亏损    │   │ • 动态上移,锁住利润    │   │ • 波动放大自动拉宽保护带│
└─────────────────────────┘   └─────────────────────────┘   └─────────────────────────┘

一、ATR 吊灯止损带(Chandelier Exit)数学模型

吊灯止损通过挂在持仓期间最高价 Hmax⁡H_{\max} 之下动态跟踪行情。多头吊灯止损线计算公式为:

StopLinet=max⁡(StopLinet−1, max⁡t0≤s≤tHighs−k×ATRt)\text{StopLine}_t = \max\left( \text{StopLine}_{t-1},\ \max_{t_0 \le s \le t} High_s - k \times ATR_t \right)

止损线单调递增(只能向上平移,绝不向下放松),在趋势发展中不断上移锁定利润,在趋势拐头时迅速触发止损离场。

import pandas as pd
import numpy as np

def calculate_chandelier_exit(df: pd.DataFrame, entry_idx: int, atr_col: str = 'ATR_14', k: float = 3.0) -> pd.Series:
    """
    计算开仓后的 ATR 吊灯动态多头止损线(单调不下降)
    """
    stop_line = pd.Series(index=df.index, dtype=float)
    max_high = -np.inf
    current_stop = -np.inf
    
    for i in range(entry_idx, len(df)):
        h = df['high'].iloc[i]
        atr = df[atr_col].iloc[i]
        if h > max_high:
            max_high = h
        
        # 止损线只能上移
        raw_stop = max_high - k * atr
        if raw_stop > current_stop:
            current_stop = raw_stop
        stop_line.iloc[i] = current_stop
        
    return stop_line

# 合成数据演示吊灯止损线计算(历史回测样例,不代表未来表现)
rng = np.random.default_rng(42)
n_bars = 20
base_prices = 100.0 + np.cumsum(rng.normal(0, 1, n_bars))
df_demo = pd.DataFrame({
    'high': base_prices + 0.5,
    'low': base_prices - 0.5,
    'close': base_prices,
    'ATR_14': np.full(n_bars, 2.0)  # 固定ATR简化演示
})

entry_bar = 5
stop_series = calculate_chandelier_exit(df_demo, entry_idx=entry_bar, k=2.0)

print("===== 吊灯止损线计算演示 =====")
print(f"入场 Bar: {entry_bar}, 入场价: {df_demo['close'].iloc[entry_bar]:.2f}")
print(f"入场后最高价: {df_demo['high'].iloc[entry_bar:].max():.2f}")
print(f"Bar {entry_bar+2} 止损线: {stop_series.iloc[entry_bar+2]:.2f}")
print(f"Bar {entry_bar+5} 止损线: {stop_series.iloc[entry_bar+5]:.2f}")
print("吊灯止损线单调不下降验证:", all(stop_series.iloc[entry_bar+1:].diff().dropna() >= 0))
===== 吊灯止损线计算演示 =====
入场 Bar: 5, 入场价: 97.70
入场后最高价: 100.46
Bar 7 止损线: 94.33
Bar 10 止损线: 94.33
吊灯止损线单调不下降验证: True

二、时间止损与横盘磨损保护机制

当策略触发买入信号后,若价格在 NN 根 K 线内未能有效拉升并突破成本线,表明该次突破缺乏跟风盘动能。此时执行时间止损能够大幅降低长期横盘等待的机会成本与潜在下行风险。

TimeExit: (t−tentry>Nmax⁡)∧(Pt<Pentry+0.5×ATR)\text{TimeExit: } (t - t_{\text{entry}} > N_{\max}) \land (P_t < P_{\text{entry}} + 0.5 \times ATR)

import pandas as pd
import numpy as np

def apply_time_stop(df: pd.DataFrame, entry_idx: int, max_hold_bars: int = 10, profit_threshold: float = 0.01) -> int:
    """
    检验时间止损触发点(合成教学样例,参数需根据市场状态调整,避免过拟合)
    """
    entry_price = df['close'].iloc[entry_idx]
    for i in range(entry_idx + 1, min(entry_idx + max_hold_bars + 1, len(df))):
        current_return = (df['close'].iloc[i] - entry_price) / entry_price
        if current_return >= profit_threshold:
            return -1  # 走势良好,不触发时间止损
            
    return entry_idx + max_hold_bars  # 耗尽最大持有周期,强制平仓

# 合成数据演示时间止损逻辑
rng = np.random.default_rng(123)
n_bars = 30
# 构造一段先微涨后横盘的行情
trend_part = np.linspace(0, 0.005, 15)
flat_part = np.full(15, 0.005)
cumulative_returns = np.concatenate([trend_part, flat_part])
prices = 50.0 * (1 + cumulative_returns) + rng.normal(0, 0.2, n_bars)

df_time = pd.DataFrame({'close': prices})

entry_bar = 0
max_hold = 12
profit_target = 0.008

exit_bar = apply_time_stop(df_time, entry_idx=entry_bar, max_hold_bars=max_hold, profit_threshold=profit_target)

print("===== 时间止损逻辑演示 =====")
print(f"入场 Bar: {entry_bar}, 入场价: {df_time['close'].iloc[entry_bar]:.2f}")
print(f"最大持有周期: {max_hold} bars, 盈利目标: {profit_target*100:.2f}%")
if exit_bar == -1:
    print("结果: 在最大持有期内达到盈利目标,未触发时间止损")
else:
    print(f"结果: 在 Bar {exit_bar} 触发时间止损,平仓价: {df_time['close'].iloc[exit_bar]:.2f}")
    print(f"实际持有期: {exit_bar - entry_bar} bars, 最终收益率: {(df_time['close'].iloc[exit_bar] - df_time['close'].iloc[entry_bar])/df_time['close'].iloc[entry_bar]*100:.2f}%")
===== 时间止损逻辑演示 =====
入场 Bar: 0, 入场价: 49.80
最大持有周期: 12 bars, 盈利目标: 0.80%
结果: 在最大持有期内达到盈利目标,未触发时间止损

📝 动手练一练

编写 Python 仿真脚本,测试吊灯止损与时间止损在突发假突破走势中的保护效果:

import pandas as pd
import numpy as np

def calculate_chandelier_exit(df: pd.DataFrame, entry_idx: int, atr_col: str = 'ATR_14', k: float = 3.0) -> pd.Series:
    """
    计算开仓后的 ATR 吊灯动态多头止损线(单调不下降)
    """
    stop_line = pd.Series(index=df.index, dtype=float)
    max_high = -np.inf
    current_stop = -np.inf
    
    for i in range(entry_idx, len(df)):
        h = df['high'].iloc[i]
        atr = df[atr_col].iloc[i]
        if h > max_high:
            max_high = h
        
        raw_stop = max_high - k * atr
        if raw_stop > current_stop:
            current_stop = raw_stop
        stop_line.iloc[i] = current_stop
        
    return stop_line

def run_risk_methods_test():
    rng = np.random.default_rng(42)
    # 模拟先拉升后急跌行情(合成数据,不代表实际市场)
    n_up = 30
    n_down = 30
    up_part = np.linspace(0, 8, n_up)
    down_part = np.linspace(8, -6, n_down)
    price_changes = np.concatenate([up_part, down_part])
    prices = 100.0 + price_changes
    
    df = pd.DataFrame({
        'high': prices + 0.8,
        'low': prices - 0.8,
        'close': prices,
        'ATR_14': np.full(len(prices), 1.5)  # 固定ATR简化
    })
    
    # 第 5 根 Bar 开仓
    entry_idx = 5
    stop_line = calculate_chandelier_exit(df, entry_idx=entry_idx, k=2.0)
    
    # 检测止损平仓点(教学演示采用收盘确认口径)
    exit_triggered = False
    exit_idx = -1
    for i in range(entry_idx, len(df)):
        if df['close'].iloc[i] < stop_line.iloc[i]:
            exit_triggered = True
            exit_idx = i
            break
    
    # 同时计算时间止损(作为对比)
    def apply_time_stop_local(df, entry_idx, max_hold_bars=10, profit_threshold=0.01):
        entry_price = df['close'].iloc[entry_idx]
        for i in range(entry_idx + 1, min(entry_idx + max_hold_bars + 1, len(df))):
            current_return = (df['close'].iloc[i] - entry_price) / entry_price
            if current_return >= profit_threshold:
                return -1
        return entry_idx + max_hold_bars
    
    time_exit = apply_time_stop_local(df, entry_idx=entry_idx, max_hold_bars=15, profit_threshold=0.05)
    
    print("================ 常用风控方法实操验证 ================")
    print(f"入场点位 (Bar {entry_idx}) : {df['close'].iloc[entry_idx]:.2f}")
    print(f"行情最高点位 (Bar {df['high'].argmax()}) : {df['high'].max():.2f}")
    print(f"吊灯止损触发 Bar : {exit_idx} (平仓价: {df['close'].iloc[exit_idx]:.2f})")
    print(f"吊灯止损收益率 : {(df['close'].iloc[exit_idx] - df['close'].iloc[entry_idx])/df['close'].iloc[entry_idx]*100:.2f}%")
    if time_exit != -1:
        print(f"时间止损触发 Bar : {time_exit} (平仓价: {df['close'].iloc[time_exit]:.2f})")
        print(f"时间止损收益率 : {(df['close'].iloc[time_exit] - df['close'].iloc[entry_idx])/df['close'].iloc[entry_idx]*100:.2f}%")
    else:
        print("时间止损: 在持有期内达到盈利目标,未触发")
    print("✅ 动态吊灯止损与风险控制方法测试 PASS")
    print("====================================================")

run_risk_methods_test()

运行结果输出:

================ 常用风控方法实操验证 ================
入场点位 (Bar 5) : 101.38
行情最高点位 (Bar 29) : 108.80
吊灯止损触发 Bar : 35 (平仓价: 105.59)
吊灯止损收益率 : 4.15%
时间止损触发 Bar : 20 (平仓价: 105.52)
时间止损收益率 : 4.08%
✅ 动态吊灯止损与风险控制方法测试 PASS
====================================================
👉 点击查看解析

未提供具体的练习代码或题目,无法提炼本节练习的核心要点。

本章小结

  1. 灵活组合多种止损机制:将初始硬止损、动态吊灯止损与时间止损串联构成完备防御矩阵。
  2. 吊灯止损锁定浮盈:止损线只升不降,让利润在强趋势中充分奔跑,在见顶反转时果断兑现。
  3. 时间止损释放资金效率:对假突破和横盘沉闷行情果断设定离场倒计时,防范时间消耗与突发变盘。

📋 行动清单 (Action Checklist)

  • 运行风控方法测试代码,对比不同 ATR 乘数 kk(2.0 vs 3.5)对止损频繁度的影响;
  • 编写阶梯式分批止盈(Scaling-out Take Profit)代码模块;
  • 预习下一节,掌握止盈止损模块在策略引擎中的标准化工程实现。

—— 小象教研组

配套资料 · 直接下载

课件、代码、数据集等配套资料全部免费,点击即可直接下载,无需分享或解锁。

  • 第5章课件:量化体系中的风险控制
    PDF · 1.2MB
    下载