布林带策略python代码
时间: 2023-07-09 07:29:57 浏览: 100
以下是一个基于布林带的简单交易策略的Python代码示例:
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 读取股票历史数据
df = pd.read_csv('stock_data.csv')
# 计算布林带指标
def calculate_bollinger_bands(data, window_size, num_std):
rolling_mean = data['Close'].rolling(window=window_size).mean()
rolling_std = data['Close'].rolling(window=window_size).std()
upper_band = rolling_mean + (rolling_std * num_std)
lower_band = rolling_mean - (rolling_std * num_std)
return rolling_mean, upper_band, lower_band
# 计算20天的布林带指标
window_size = 20
num_std = 2
rolling_mean, upper_band, lower_band = calculate_bollinger_bands(df, window_size, num_std)
# 将指标数据添加到原始数据中
df['Rolling Mean'] = rolling_mean
df['Upper Band'] = upper_band
df['Lower Band'] = lower_band
# 策略:当价格从下轨突破到中轨时买入,当价格从上轨突破到中轨时卖出
df['Position'] = None
for i in range(window_size, len(df)):
if df['Close'][i] > df['Lower Band'][i]:
df['Position'][i] = 1
elif df['Close'][i] < df['Upper Band'][i]:
df['Position'][i] = -1
# 计算收益率
df['Returns'] = np.log(df['Close']/df['Close'].shift(1))
df['Strategy Returns'] = df['Position'].shift(1) * df['Returns']
# 绘制收益率曲线
df[['Returns', 'Strategy Returns']].cumsum().apply(np.exp).plot(figsize=(10, 6))
# 显示图表
plt.show()
```
请注意,这只是一个简单的示例代码,实际情况可能需要更复杂的策略和更多的数据处理。
阅读全文