写一个简单的CTA策略回测代码,其中有多个技术指标
时间: 2024-02-13 10:06:18 浏览: 270
基于技术指标的单信号策略回测-西门子tdc控制器编程手册
以下是一个简单的CTA策略回测代码,其中包含了多个技术指标:
```python
import pandas as pd
import numpy as np
import talib
# 读取数据
data = pd.read_csv('data.csv')
data['datetime'] = pd.to_datetime(data['datetime'])
data.set_index('datetime', inplace=True)
# 计算技术指标
data['ma5'] = talib.MA(data['close'], timeperiod=5)
data['ma10'] = talib.MA(data['close'], timeperiod=10)
data['rsi'] = talib.RSI(data['close'], timeperiod=14)
data['macd'], data['macdsignal'], data['macdhist'] = talib.MACD(data['close'], fastperiod=12, slowperiod=26, signalperiod=9)
# 设定策略参数
ma_short = 5
ma_long = 10
rsi_buy = 30
rsi_sell = 70
macd_buy = 0
macd_sell = 0
# 计算交易信号
data['signal'] = 0
data['signal'] = np.where(data['ma5'] > data['ma10'], 1, data['signal'])
data['signal'] = np.where((data['rsi'] < rsi_buy) & (data['signal'] == 1), 1, data['signal'])
data['signal'] = np.where((data['rsi'] > rsi_sell) & (data['signal'] == -1), -1, data['signal'])
data['signal'] = np.where((data['macd'] > macd_buy) & (data['macdsignal'] > macd_buy) & (data['signal'] == 1), 1, data['signal'])
data['signal'] = np.where((data['macd'] < macd_sell) & (data['macdsignal'] < macd_sell) & (data['signal'] == -1), -1, data['signal'])
# 计算持仓情况
data['position'] = data['signal'].shift(1)
# 计算收益率
data['pct_change'] = data['close'].pct_change()
data['strategy_returns'] = data['position'] * data['pct_change']
# 计算累计收益率
data['cum_returns'] = (1 + data['strategy_returns']).cumprod()
# 输出结果
print(data.tail())
```
该代码首先读取数据,然后使用TA-Lib计算多个技术指标,接着设定策略参数,并基于技术指标计算交易信号,计算持仓情况和收益率,最后计算累计收益率。请注意,此代码只是用于演示目的,实际交易中需要根据个人情况进行调整和优化。
阅读全文