帮我写一个可以才聚宽回测600519股票的量化程序,策略为“MACD+均线”。
时间: 2024-03-03 11:50:12 浏览: 160
【python股票量化】双均线策略编程实现
5星 · 资源好评率100%
好的,根据您的要求,我可以为您提供一个简单的量化程序,用于执行“MACD+均线”策略的回测。下面是代码实现:
```python
import jqdatasdk as jq
import talib
import numpy as np
import pandas as pd
# 初始化聚宽,登录账号
jq.auth('你的聚宽账号', '你的聚宽密码')
# 设置回测时间段
start_date = '2016-01-01'
end_date = '2021-07-01'
# 获取股票数据
security = '600519.XSHG'
df = jq.get_price(security, start_date=start_date, end_date=end_date, frequency='daily')
# 计算MACD指标
df['MACD'], df['MACDsignal'], df['MACDhist'] = talib.MACD(df['close'], fastperiod=12, slowperiod=26, signalperiod=9)
# 计算均线指标
df['MA20'] = talib.MA(df['close'], timeperiod=20)
df['MA60'] = talib.MA(df['close'], timeperiod=60)
# 定义回测策略
def strategy(df):
# 策略参数
buy_signal = 0.0 # 买入信号触发值
sell_signal = 0.0 # 卖出信号触发值
# 计算策略指标
df['position'] = np.where((df['MACD'] > df['MACDsignal']) & (df['close'] > df['MA20']) & (df['close'] > df['MA60']), 1, 0)
df['position'] = np.where((df['MACD'] < df['MACDsignal']) & (df['close'] < df['MA20']) & (df['close'] < df['MA60']), -1, df['position'])
df['position'] = df['position'].fillna(method='ffill')
df['position'] = df['position'].fillna(0)
# 计算策略收益
df['returns'] = df['close'].pct_change() * df['position'].shift(1)
df['cum_returns'] = (1 + df['returns']).cumprod()
return df
# 执行回测策略
df = strategy(df)
# 输出回测结果
print('累计收益:', round((df['cum_returns'][-1] - 1) * 100, 2), '%')
print('年化收益:', round((np.power(df['cum_returns'][-1], 252 / len(df)) - 1) * 100, 2), '%')
print('最大回撤:', round((1 - np.min(df['cum_returns']) / np.max(df['cum_returns'])) * 100, 2), '%')
```
请将代码中的聚宽账号和密码替换成您自己的账号和密码。此外,回测结果的输出为累计收益、年化收益和最大回撤。
阅读全文