惊险!我用三重屏障策略躲过多次暴跌,现在手把手教你精准止盈止损

305 阅读7分钟

在当今复杂多变的金融市场中,量化交易凭借其科学性和系统性,逐渐成为投资者们追求高效、精准交易的重要手段。而众多量化交易策略中,三重屏障策略(Triple Barrier Method)以其独特的优势脱颖而出,备受大家的青睐。本文将深入剖析三重屏障策略的原理与应用,并结合比特币行情数据,详细阐述如何运用该策略精准确定买入和卖出点,同时提供一个基于Python的实现方案,帮助大家更好地理解和运用这一策略。

1. 什么是三重屏障策略?

三重屏障策略是一种基于事件驱动的交易方法,最初由Marcos López de Prado在其著作《Advances in Financial Machine Learning》中提出。它通过设定三个明确的退出条件(屏障)来管理交易的风险和收益。这三个屏障分别是:

  • • 止盈线(上屏障):当资产价格达到设定的止盈水平时,投资者立即卖出资产以锁定利润。例如,设定止盈线为10%,即当比特币价格较买入价上涨10%时,触发止盈条件。
  • • 止损线(下屏障):若资产价格下跌至止损水平,投资者则果断止损卖出,避免亏损进一步扩大。比如设定止损线为5%,一旦比特币价格较买入价下跌5%,即触发止损条件。
  • • 时间限制(垂直屏障):无论资产价格涨跌,只要达到设定的持仓时间上限,投资者便结束交易。例如,设定持仓时间为7天,即使在这7天内比特币价格未触及止盈或止损线,也将在第7天结束时强制平仓。

相较于传统的固定时间或固定价格的交易策略,三重屏障策略更具灵活性和适应性。它不仅考虑了价格波动,还纳入了时间因素,避免了无限期持有头寸的风险。在比特币这样波动性极高的市场中,三重屏障策略尤其适用,因为它能帮助大家在快速变化的行情中捕捉机会,有效管理风险并锁定收益。

2. 确定买入和卖出点

比特币作为一种极具代表性的加密货币,其价格波动之大、交易活跃度之高,为量化交易提供了丰富的实践场景。以下将结合比特币行情数据,详细说明如何运用三重屏障策略确定买入和卖出点。

2.1 数据准备

  • • 使用ccxt从交易所(如Binance)获取比特币的K线数据(例如1小时K线)。
  • • 计算价格的波动性(如标准差或ATR),以动态设置屏障的宽度。

2.2 买入点确定

  • • 基于技术指标(如移动平均线、RSI)或价格突破信号,识别潜在的买入点。例如,当价格突破20周期简单移动平均线(SMA)并伴随成交量增加时,可以视为买入信号。

2.3 设置三重屏障

  • • 盈利目标:根据历史波动性,设定一个合理的上行目标,例如当前价格的+2倍标准差。
  • • 止损点:设定一个下行止损,例如当前价格的-1倍标准差。
  • • 时间屏障:根据交易周期设置,例如10根K线(对于1小时K线即10小时)。

2.4 卖出点确定

当价格触及任一屏障时,触发卖出:

  • • 若达到盈利目标,则获利平仓。
  • • 若触及止损点,则止损离场。
  • • 若时间耗尽,则按当前市场价格平仓。

2.5 可视化与优化

  • • 使用plotly绘制价格走势和屏障位置,观察策略效果。
  • • 通过回测调整参数(如屏障宽度、时间长度),优化收益与风险比。

3. Python实现

#!/usr/bin/env python  # encoding: utf-8  
  
# @version: v1.0  
# @author:  Kandy.Ye  
# @contact: Kandy.Ye@outlook.com  
# @file:    TripleBarrier.py  
# @time:    星期三 2025/4/9 20:27

import ccxt  
import pandas as pd  
import plotly.graph_objects as go  
from plotly.subplots import make_subplots  
from datetime import datetime  
from tools.download_data import fetch_ohlcv_batch  
  
class TripleBarrierStrategy:  
    def __init__(self, symbol='BTC/USDT', timeframe='1h', limit=500, exchange_name='binance'):  
        """初始化策略,设置交易对、时间框架和数据限制"""  
        self.symbol = symbol  
        self.timeframe = timeframe  
        self.limit = limit  
        self.exchange = getattr(ccxt, exchange_name)()  
        self.data = None  
  
    def fetch_data(self):  
        """从交易所获取OHLCV数据"""  
        ohlcv = fetch_ohlcv_batch(self.exchange, self.symbol, self.timeframe, total_needed=self.limit)  
        df = pd.DataFrame(ohlcv, columns=['timestamp''open''high''low''close''volume'])  
        df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')  
        df.set_index('timestamp', inplace=True)  
        self.data = df  
        return df  
  
    def calculate_signals(self, sma_period=20, vol_multiplier=2, stop_multiplier=1, time_barrier=10):  
        """计算买入信号和三重屏障"""  
        df = self.data.copy()  
  
        # 计算简单移动平均线  
        df['sma'] = df['close'].rolling(window=sma_period).mean()  
        # 计算波动性(标准差)  
        df['volatility'] = df['close'].rolling(window=sma_period).std()  
  
        # 买入信号:价格突破SMA  
        df['buy_signal'] = (df['close'] > df['sma']) & (df['close'].shift(1) <= df['sma'].shift(1))  
  
        # 设置三重屏障  
        df['profit_target'] = df['close'] + df['volatility'] * vol_multiplier  
        df['stop_loss'] = df['close'] - df['volatility'] * stop_multiplier  
        df['time_barrier'] = df.index + pd.Timedelta(hours=time_barrier)  
  
        return df  
  
    def simulate_trades(self):  
        """模拟交易,确定买卖点"""  
        df = self.calculate_signals()  
        trades = []  
  
        for i in range(len(df)):  
            if df['buy_signal'].iloc[i]:  
                entry_price = df['close'].iloc[i]  
                profit_target = df['profit_target'].iloc[i]  
                stop_loss = df['stop_loss'].iloc[i]  
                time_barrier = df['time_barrier'].iloc[i]  
  
                # 检查后续K线,判断哪个屏障先被触及  
                for j in range(i, len(df)):  
                    high = df['high'].iloc[j]  
                    low = df['low'].iloc[j]  
                    exit_time = df.index[j]  
  
                    if high >= profit_target:  
                        trades.append({  
                            'entry_time': df.index[i], 'entry_price': entry_price,  
                            'exit_time': exit_time, 'exit_price': profit_target,  
                            'profit_target': profit_target, 'stop_loss': stop_loss,  
                            'time_barrier': time_barrier, 'result''profit'  
                        })  
                        break  
                    elif low <= stop_loss:  
                        trades.append({  
                            'entry_time': df.index[i], 'entry_price': entry_price,  
                            'exit_time': exit_time, 'exit_price': stop_loss,  
                            'profit_target': profit_target, 'stop_loss': stop_loss,  
                            'time_barrier': time_barrier, 'result''stop_loss'  
                        })  
                        break  
                    elif exit_time >= time_barrier:  
                        trades.append({  
                            'entry_time': df.index[i], 'entry_price': entry_price,  
                            'exit_time': exit_time, 'exit_price': df['close'].iloc[j],  
                            'profit_target': profit_target, 'stop_loss': stop_loss,  
                            'time_barrier': time_barrier, 'result''time_exit'  
                        })  
                        break  
  
        return pd.DataFrame(trades)  
  
    def plot_results(self):  
        """使用Plotly绘制价格走势、三重屏障线和交易量柱状图"""  
        df = self.calculate_signals()  
        trades = self.simulate_trades()  
  
        # 创建图表  
        fig = go.Figure()  
  
        # 绘制K线图  
        fig.add_trace(go.Candlestick(x=df.index,  
                                     open=df['open'], high=df['high'],  
                                     low=df['low'], close=df['close'],  
                                     name='Candlestick'))  
  
        # 绘制SMA  
        fig.add_trace(go.Scatter(x=df.index, y=df['sma'], name='SMA', line=dict(color='blue')))  
  
        # 绘制买卖点  
        buy_times = trades['entry_time']  
        buy_prices = trades['entry_price']  
        fig.add_trace(go.Scatter(x=buy_times, y=buy_prices, mode='markers', name='Buy',  
                                 marker=dict(color='green', size=10)))  
  
        exit_times = trades['exit_time']  
        exit_prices = trades['exit_price']  
        fig.add_trace(go.Scatter(x=exit_times, y=exit_prices, mode='markers', name='Exit',  
                                 marker=dict(color='red', size=10)))  
  
        # 绘制三重屏障线  
        for _, trade in trades.iterrows():  
            # 盈利目标线  
            fig.add_shape(type="line", x0=trade['entry_time'], x1=trade['time_barrier'],  
                          y0=trade['profit_target'], y1=trade['profit_target'],  
                          line=dict(color="green", dash="dash"))  
            # 止损线  
            fig.add_shape(type="line", x0=trade['entry_time'], x1=trade['time_barrier'],  
                          y0=trade['stop_loss'], y1=trade['stop_loss'],  
                          line=dict(color="red", dash="dash"))  
            # 时间屏障垂直线  
            fig.add_shape(type="line", x0=trade['time_barrier'], x1=trade['time_barrier'],  
                          y0=trade['stop_loss'], y1=trade['profit_target'],  
                          line=dict(color="yellow", dash="dash"))  
  
        # 绘制交易量柱状图(使用次坐标轴)  
        fig.add_trace(go.Bar(x=df.index, y=df['volume'], name='Volume', marker_color='gray',  
                             opacity=0.5, yaxis='y2'))  
  
        # 更新布局,添加次坐标轴  
        fig.update_layout(  
            title=f'{self.symbol} Triple Barrier Strategy',  
            xaxis_title='Time',  
            yaxis_title='Price',  
            yaxis2=dict(title='Volume', overlaying='y', side='right', showgrid=False),  
            template='plotly_dark',  
            height=800  
        )  
        fig.update_xaxes(rangeslider_visible=False)  
        fig.show()  
  
# 使用示例  
if __name__ == "__main__":  
    strategy = TripleBarrierStrategy(symbol='BTC/USDT', timeframe='1h', limit=500)  
    strategy.fetch_data()  
    strategy.plot_results()

5. 运行结果

Pasted image 20250409210224.png

运行代码后,你将看到三重屏障线:每次交易的盈利目标(绿色)、止损(红色)和时间屏障(黄色)以虚线形式清晰显示。 通过调整参数(如sma_period、vol_multiplier、time_barrier),你可以优化策略以适应不同的市场条件。

6. 总结

三重屏障策略通过结合价格目标和时间限制,为比特币交易提供了一个结构化的风险管理框架。在实际应用中,大家可以根据市场波动性和个人风险偏好调整屏障参数,并通过回测验证策略的有效性。

7. 联系方式

感谢你看到这里,如果觉得文章对你有所收获,请在文末为我点个【赞】+【推荐】,或者【转发】给身边更多有需要的人看,你的点赞就是对我莫大的支持与动力!