Backtrader 策略实例
- [Backtrader]实例:均线策略[Backtrader] 实例:MACD策略[Backtrader] 实例:KDJ 策略
- [Backtrader] 实例:RSI 与 EMA 结合
- [Backtrader] 实例:SMA自定义数据源
- [Backtrader] 实例:海龟策略[Backtrader] 实例:网格交易[Backtrader] 实例: 配对交
- [Backtrader] 机器学习预测市场走势与回测
波动率类,用来衡量资产价格变动的大小。常见的波动类指标有 ATR、BBANDS、DC 等。
- 波动策略指标-ATR
- 波动策略指标-BOLL
- 波动策略指标-DC
- 波动策略指标-ACCBANDS
- 波动策略指标-MASSI
- 波动策略指标-RVI
- 波动策略指标-UDVD
- 波动策略指标-EMV
波动性是金融市场的一个关键方面,反映了金融工具价格随时间的变化程度。投资者和交易者使用波动率指标来衡量市场不确定性并识别交易机会。
1. Chaikin Volatility (CHV)
Chaikin Volatility (CHV) 指标是由 Marc Chaikin 开发的一种技术分析工具,用于衡量资产价格的波动性。它通过比较一段时间内最高价与最低价之间的价差变化来反映市场波动性的变化。CHV 指标不直接预测价格方向,而是专注于波动性的变化,帮助交易者识别潜在的市场突破或趋势反转。
Chaikin Volatility (CHV)指标衡量给定时期内最高价和最低价之间的价差,有助于评估市场波动性。利差扩大表明波动性增加,而利差缩小表明波动性降低。
- 计算方法
CHV 指标的计算基于以下步骤:
1). 计算价差范围 (High - Low):
2). 计算价差的指数移动平均 (EMA):
3). 计算波动率变化:
-
- 比较当前 EMA 与 n 周期前的 EMA,计算百分比变化:
- 对价差范围进行指数移动平均计算,通常使用 10 周期 EMA:
。
-
- 每个周期的价差范围为最高价与最低价之差:
。
- 指标解读
1). 波动性增加:
- CHV 值上升表明市场波动性增加,通常出现在价格大幅波动或市场情绪剧烈变化时。这可能预示着潜在的市场突破或趋势反转。
2). 波动性下降: - CHV 值下降表明市场波动性降低,通常出现在价格盘整或市场情绪平稳时。这可能预示着市场即将进入盘整或趋势反转。
3). 市场顶部与底部: - 在市场顶部,波动性通常会增加,随后可能伴随价格反转。
- 在市场底部,波动性可能突然增加(如恐慌性抛售),随后可能伴随价格反弹。
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots
ticker = "^GSPC" # S&P 500 index symbol
# Define the Chaikin Volatility function
def chaikin_volatility(data, period=10):
data['HL'] = data['High'] - data['Low']
data['CHV'] = data['HL'].ewm(span=period, adjust=False).mean()
data['ChaikinVolatility'] = data['CHV'].pct_change(periods=period) * 100
return data
# Apply the Chaikin Volatility function to the data
data = chaikin_volatility(data)
# Create the subplot figure
fig = make_subplots(rows=1, cols=1, shared_xaxes=True, vertical_spacing=0.3)
# Plot the Chaikin Volatility indicator
fig.add_trace(go.Scatter(x=data.index, y=data['CHV'], mode='lines', name='Chaikin Volatility', line=dict(color='orange')), row=1, col=1)
# Update layout for better presentation
fig.update_layout(
title="Chaikin Volatility Indicator (S&P 500)",
xaxis_title="Date",
yaxis_title="Chaikin Volatility",
template="plotly_dark"
)
# Show the plot
fig.show()
Chaikin Volatility Indicator (S&P 500)
观察 CHV 的急剧增加或减少;它们可以指示即将到来的价格变动。高峰和低谷通常先于重大市场变化。
2. Donchian Channels
Donchian Channels(唐奇安通道)是由 Richard Donchian 开发的一种技术分析工具,用于识别价格趋势和波动性。它通过计算一定周期内的最高价和最低价,形成一个价格通道,帮助交易者判断市场的支撑位、阻力位以及趋势方向。
参考以往文章【策略篇】常用技术指标-唐奇安、BOLL
# Define the Donchian Channels function
def donchian_channels(data, period=20):
data['Upper'] = data['High'].rolling(window=period).max()
data['Lower'] = data['Low'].rolling(window=period).min()
data['Middle'] = (data['Upper'] + data['Lower']) / 2
return data
# Apply the Donchian Channels function to the data
data = donchian_channels(data)
# Create the subplot figure
fig = make_subplots(rows=1, cols=1, shared_xaxes=True, vertical_spacing=0.3,
subplot_titles=["Donchian Channels with Candlestick"],
row_heights=[0.7],
row_width=[0.3])
# Plot the Candlestick chart
fig.add_trace(go.Candlestick(x=data.index,
open=data['Open'],
high=data['High'],
low=data['Low'],
close=data['Close'],
name="Candlestick",
increasing_line_color='green',
decreasing_line_color='red'), row=1, col=1)
# Plot the Donchian Channels
fig.add_trace(go.Scatter(x=data.index, y=data['Upper'], mode='lines', name='Upper Channel', line=dict(color='green')), row=1, col=1)
fig.add_trace(go.Scatter(x=data.index, y=data['Lower'], mode='lines', name='Lower Channel', line=dict(color='red')), row=1, col=1)
fig.add_trace(go.Scatter(x=data.index, y=data['Middle'], mode='lines', name='Middle Channel', line=dict(color='blue', dash='dot')), row=1, col=1)
# Update layout for better presentation
fig.update_layout(
title="Donchian Channels with Candlestick (S&P 500)",
xaxis_title="Date",
yaxis_title="Price",
template="plotly_dark",
xaxis_rangeslider_visible=False
)
# Show the plot
fig.show()
Donchian Channels with Candlestick (S&P 500)
价格突破通道上方或下方可能预示着强劲的趋势。使用 volume 进行确认以评估 breakout 的可靠性。
3. Keltner Channels
Keltner 通道使用平均真实范围 (ATR) 来创建波动率包络线。它们由三条线组成:一条中央移动平均线和其上方和下方的两条外线,由 ATR 的倍数偏移。
参考以往文章在 Python 中使用 ADX 进行算法交易
# Define the Keltner Channels function
def keltner_channels(data, period=20, atr_multiplier=2):
data['TR'] = data[['High', 'Low', 'Close']].apply(
lambda x: max(
x['High'] - x['Low'],
abs(x['High'] - x['Close']),
abs(x['Low'] - x['Close'])
), axis=1
)
data['ATR'] = data['TR'].rolling(window=period).mean()
data['Middle'] = data['Close'].rolling(window=period).mean()
data['Upper'] = data['Middle'] + atr_multiplier * data['ATR']
data['Lower'] = data['Middle'] - atr_multiplier * data['ATR']
return data
# Apply the Keltner Channels function to the data
data = keltner_channels(data)
# Create the subplot figure
fig = make_subplots(
rows=1, cols=1, shared_xaxes=True, vertical_spacing=0.3,
subplot_titles=["Keltner Channels with Candlestick"],
row_heights=[0.7],
row_width=[0.3]
)
# Plot the Candlestick chart
fig.add_trace(go.Candlestick(
x=data.index,
open=data['Open'],
high=data['High'],
low=data['Low'],
close=data['Close'],
name="Candlestick",
increasing_line_color='green',
decreasing_line_color='red'
), row=1, col=1)
# Plot the Keltner Channels
fig.add_trace(go.Scatter(x=data.index, y=data['Upper'], mode='lines', name='Upper Channel', line=dict(color='green')), row=1, col=1)
fig.add_trace(go.Scatter(x=data.index, y=data['Lower'], mode='lines', name='Lower Channel', line=dict(color='red')), row=1, col=1)
fig.add_trace(go.Scatter(x=data.index, y=data['Middle'], mode='lines', name='Middle Channel', line=dict(color='blue', dash='dot')), row=1, col=1)
# Update layout for better presentation
fig.update_layout(
title="Keltner Channels with Candlestick (S&P 500)",
xaxis_title="Date",
yaxis_title="Price",
template="plotly_dark",
xaxis_rangeslider_visible=False
)
# Show the plot
fig.show()
Keltner Channels with Candlestick (S&P 500)
价格在 Keltner 通道之外的移动表明存在强劲势头或趋势反转的可能性。请等待确认。
4. Relative Volatility Index (RVI)
Relative Volatility Index (RVI) 是一种技术分析工具,用于衡量金融市场价格波动的方向和强度。它由 Donald Dorsey 于 1993 年开发,是相对强弱指数(RSI)的变体,但 RVI 更侧重于波动性而非价格动量。
- RVI 的计算方法
RVI 的计算基于价格的标准差(Standard Deviation),而不是简单的价格变化。其公式与 RSI 类似,但使用标准差来衡量波动性。以下是简化版的 RVI 计算公式:
1). 计算标准差:
2). 计算 RVI:
- 计算正标准差和负标准差的平均值(Usum 和 Dsum)。
- 使用以下公式计算 RVI:
-
- RVI 的值范围在 0 到 100 之间。
- 计算选定周期内收盘价的标准差(STD)。
- 对于每个交易日,如果收盘价高于前一日收盘价,则记录为正标准差(u = STD(n));否则为 0。
- 如果收盘价低于前一日收盘价,则记录为负标准差(d = STD(n));否则为 0。
- RVI 的解读
- RVI > 50:表明市场波动性较高,通常与价格上涨趋势相关,可能预示着买入机会。
- RVI < 50:表明市场波动性较低,通常与价格下跌趋势相关,可能预示着卖出机会。
- RVI > 70:表明市场处于超买状态,可能预示着价格反转。
- RVI < 30:表明市场处于超卖状态,可能预示着价格反弹。
总结
Relative Volatility Index (RVI) 是一种强大的技术分析工具,能够帮助交易者识别市场波动性和趋势强度。尽管其计算复杂且存在一定滞后性,但结合其他指标使用时,RVI 可以提供更全面的市场洞察,帮助交易者做出更明智的决策。
import numpy as np
# Define the Relative Volatility Index (RVI) function
def relative_volatility_index(data, period=14):
# Calculate the difference between the Close and Open prices
data['Upward Volatility'] = np.where(data['Close'] > data['Open'], data['Close'] - data['Open'], 0)
data['Total Volatility'] = abs(data['Close'] - data['Open'])
# Calculate the rolling sum of Upward Volatility and Total Volatility
data['Upward Volatility Sum'] = data['Upward Volatility'].rolling(window=period).sum()
data['Total Volatility Sum'] = data['Total Volatility'].rolling(window=period).sum()
# Calculate RVI as the ratio of Upward Volatility to Total Volatility
data['RVI'] = data['Upward Volatility Sum'] / data['Total Volatility Sum'] * 100
return data
# Apply the Relative Volatility Index (RVI) function to the data
data = relative_volatility_index(data)
# Create the subplot figure
fig = make_subplots(rows=1, cols=1, shared_xaxes=True, vertical_spacing=0.3)
# Plot the RVI indicator
fig.add_trace(go.Scatter(x=data.index, y=data['RVI'], mode='lines', name='Relative Volatility Index', line=dict(color='orange')), row=1, col=1)
# Update layout for better presentation
fig.update_layout(
title="Relative Volatility Index (RVI) Indicator (S&P 500)",
xaxis_title="Date",
yaxis_title="RVI Value",
template="plotly_dark"
)
# Show the plot
fig.show()
Relative Volatility Index (RVI) Indicator (S&P 500)
上升的 RVI 表明走强的趋势,而下降的 RVI 表明势头减弱。交叉和背离可以确定进入或退出机会。
5. Standard Deviation
标准差是一种简单而有效的价格离散度衡量标准。高标准差表示高波动性,而低标准差表示稳定性。
# Define the standard deviation function
def standard_deviation(data, period=20):
data['Std_Dev'] = data['Close'].rolling(window=period).std()
return data
# Apply the standard deviation function to the data
data = standard_deviation(data)
# Create the subplot figure
fig = make_subplots(rows=1, cols=1, shared_xaxes=True, vertical_spacing=0.3)
# Plot the standard deviation indicator
fig.add_trace(go.Scatter(x=data.index, y=data['Std_Dev'], mode='lines', name='Standard Deviation', line=dict(color='orange')), row=1, col=1)
# Update layout for better presentation
fig.update_layout(
title="Standard Deviation Indicator (S&P 500)",
xaxis_title="Date",
yaxis_title="Standard Deviation",
template="plotly_dark"
)
# Show the plot
fig.show()
Standard Deviation Indicator (S&P 500)
标准差的飙升表明波动性增加。调整策略以应对不断变化的市场条件。
波动率指标提供对市场动态的宝贵见解,并帮助交易者做出明智的决策。使用 Python,您可以有效地实施这些指标并针对特定的交易策略对其进行自定义。开始尝试这些指标,以增强您的交易工具包并更好地了解市场行为。