帮我用python写一个策略为“MACD+均线”的量化系统,可以回测的,写出入场和出场原则
时间: 2024-03-03 10:50:15 浏览: 78
好的,我可以为您提供一个简单的量化系统,用于执行“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, capital):
# 策略参数
buy_signal = 0.0 # 买入信号触发值
sell_signal = 0.0 # 卖出信号触发值
position = 0 # 仓位
buy_price = 0 # 买入价格
sell_price = 0 # 卖出价格
trade_records = [] # 交易记录
# 计算策略指标
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)
# 执行交易
for i in range(len(df)):
if df['position'][i] == 1 and position == 0:
position = 1
buy_price = df['close'][i]
shares = capital / buy_price
trade_records.append(('buy', buy_price, shares))
elif df['position'][i] == -1 and position == 1:
position = 0
sell_price = df['close'][i]
capital = shares * sell_price
trade_records.append(('sell', sell_price, shares))
else:
trade_records.append(('hold', np.nan, np.nan))
# 计算策略收益
df['returns'] = df['close'].pct_change() * df['position'].shift(1)
df['cum_returns'] = (1 + df['returns']).cumprod()
return df, trade_records
# 执行回测策略
capital = 100000
df, trade_records = strategy(df, capital)
# 输出回测结果
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), '%')
print('交易记录:\n', pd.DataFrame(trade_records, columns=['操作', '价格', '数量']))
```
请将代码中的聚宽账号和密码替换成您自己的账号和密码。此外,回测结果的输出为累计收益、年化收益、最大回撤和交易记录。入场原则为MACD指标上穿信号线,并且收盘价在20日均线和60日均线之上;出场原则为MACD指标下穿信号线,并且收盘价在20日均线和60日均线之下。
阅读全文