布林带策略python
时间: 2023-07-05 20:32:14 浏览: 113
布林带策略是一种基于统计学原理的技术分析方法,常用于股票交易和其他金融市场。下面是一个简单的布林带策略的Python代码示例:
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 获取数据
df = pd.read_csv('data.csv')
# 计算布林带指标
n = 20 # 计算周期
std = 2 # 布林带宽度
ma = df['close'].rolling(n).mean()
std_dev = df['close'].rolling(n).std()
upper_band = ma + std * std_dev
lower_band = ma - std * std_dev
# 绘制布林带
plt.plot(df['close'])
plt.plot(upper_band)
plt.plot(lower_band)
# 判断买入和卖出信号
signals = pd.Series(np.zeros(len(df)))
for i in range(n, len(df)):
if df['close'][i] > upper_band[i-1]:
signals[i] = 1
elif df['close'][i] < lower_band[i-1]:
signals[i] = -1
# 绘制买卖信号
buy_signals = signals[signals == 1]
sell_signals = signals[signals == -1]
plt.scatter(buy_signals.index, df['close'][buy_signals.index], color='green', marker='^', s=100)
plt.scatter(sell_signals.index, df['close'][sell_signals.index], color='red', marker='v', s=100)
# 计算收益率
returns = pd.Series(np.zeros(len(df)))
for i in range(1, len(df)):
if signals[i-1] == 1:
returns[i] = (df['close'][i] - df['close'][i-1]) / df['close'][i-1]
elif signals[i-1] == -1:
returns[i] = (df['close'][i-1] - df['close'][i]) / df['close'][i-1]
# 绘制收益率曲线
cum_returns = (1 + returns).cumprod()
plt.figure()
plt.plot(cum_returns)
# 输出统计指标
win_rate = len(returns[returns > 0]) / len(returns[returns != 0])
print('总收益率:', cum_returns[-1])
print('年化收益率:', (cum_returns[-1] ** (250/len(df)) - 1))
print('胜率:', win_rate)
print('盈亏比:', abs(returns[returns > 0].mean() / returns[returns < 0].mean()))
```
在这个例子中,我们首先计算了布林带的上限和下限,然后根据收盘价与布林带的位置判断买卖信号。最后,我们计算了收益率并输出了一些统计指标。当然,这只是一个简单的示例,实际操作中还需要考虑一些细节问题,例如手续费、滑点等。
阅读全文