Python均值回归配对交易策略源码
时间: 2023-10-10 16:14:56 浏览: 148
下面是一个简单的 Python 均值回归配对交易策略的示例代码:
```python
import numpy as np
import pandas as pd
import yfinance as yf
# 获取股票数据
symbol1 = 'AAPL'
symbol2 = 'MSFT'
start_date = '2015-01-01'
end_date = '2020-12-31'
data1 = yf.download(symbol1, start=start_date, end=end_date)
data2 = yf.download(symbol2, start=start_date, end=end_date)
# 计算股票收益率
data1['returns'] = data1['Adj Close'].pct_change()
data2['returns'] = data2['Adj Close'].pct_change()
# 计算股票收益率差值
data = pd.merge(data1[['returns']], data2[['returns']], on='Date')
data['delta'] = data['returns_x'] - data['returns_y']
# 计算均值和标准差
mean = np.mean(data['delta'])
std = np.std(data['delta'])
# 计算上下限
upper_limit = mean + 2 * std
lower_limit = mean - 2 * std
# 计算交易信号
data['signal'] = np.where(data['delta'] > upper_limit, -1, np.nan)
data['signal'] = np.where(data['delta'] < lower_limit, 1, data['signal'])
data['signal'] = data['signal'].fillna(method='ffill')
# 计算每日持仓
data['position1'] = 1 * data['signal']
data['position2'] = -1 * data['signal']
# 计算每日收益率
data['strategy_returns'] = data['position1'] * data1['returns'] + data['position2'] * data2['returns']
# 计算累计收益率
data['cumulative_returns'] = (1 + data['strategy_returns']).cumprod()
# 绘制累计收益率曲线
data['cumulative_returns'].plot()
```
上面的代码使用了 yfinance 库来获取股票数据,计算了两只股票的收益率并计算了收益率差值。然后,计算了收益率差值的均值和标准差,并根据均值和标准差计算了交易信号。最后,计算了每日持仓和每日收益率,并绘制了累计收益率曲线。
请注意,这只是一个简单的示例代码。实际的交易策略可能需要更复杂的数据处理和交易逻辑。此外,交易策略的成功还取决于市场状况和交易者的技能和经验。
阅读全文