以下是一个简单的双均线策略的示例代码,用于说明如何设计和实现量化交易策略:
import pandas as pd
import numpy as np
import talib
# 读取历史数据
data = pd.read_csv('stock_data.csv') 【完整源码搭建开发可看我昵称】
# 计算均线
short_mavg = talib.SMA(data['Close'], timeperiod=5)
long_mavg = talib.SMA(data['Close'], timeperiod=30)
# 生成交易信号
signal = np.where(short_mavg > long_mavg, 1, 0)
# 计算持仓和收益
position = np.zeros(len(data))
returns = np.zeros(len(data))
for i in range(1, len(data)): 【完整源码搭建开发可看我昵称】
if signal[i] == 1:
position[i] = 1
returns[i] = data['Close'][i] / data['Close'][i-1] - 1
else:
position[i] = 0
returns[i] = 0
# 计算累计收益
cum_returns = np.cumprod(returns)
# 输出结果
print('累计收益:', cum_returns[-1])
有疑问加站长微信联系(非本文作者)