布林带策略python代码
时间: 2023-07-09 12:29:58 浏览: 89
《量化交易入门(二十九)布林带指标实现和回测》配套源码
以下是一个简单的布林带策略的 Python 代码示例:
```python
import pandas as pd
import yfinance as yf
# 获取数据
df = yf.download("AAPL", start="2020-01-01", end="2021-01-01")
# 计算布林带指标
n = 20
sigma = 2
df['MA'] = df['Close'].rolling(n).mean()
df['STD'] = df['Close'].rolling(n).std()
df['Upper'] = df['MA'] + sigma * df['STD']
df['Lower'] = df['MA'] - sigma * df['STD']
# 策略信号
df['Signal'] = 0
df['Prev Signal'] = df['Signal'].shift(1)
df.loc[(df['Close'] > df['Upper']) & (df['Prev Signal'] != 1), 'Signal'] = 1
df.loc[(df['Close'] < df['Lower']) & (df['Prev Signal'] != -1), 'Signal'] = -1
# 计算收益
df['Return'] = df['Close'].pct_change()
df['Strategy Return'] = df['Return'] * df['Signal'].shift(1)
# 计算总收益
total_return = (df['Strategy Return'] + 1).cumprod()[-1]
# 打印结果
print(f"Total return: {total_return}")
df[['Close', 'MA', 'Upper', 'Lower']].plot(figsize=(10, 6))
```
这个代码使用了 Pandas 库和 yfinance 库,分别用于数据处理和获取股票数据。代码首先获取了苹果公司的股票数据,然后计算了布林带指标。接着根据布林带指标计算了策略信号,如果收盘价突破了上轨线就产生买入信号,如果收盘价跌破了下轨线就产生卖出信号。最后计算了收益并打印结果,同时画出了股价和布林带线的图表。
阅读全文