用python写一个“KDJ+DMI”的量化策略,从tushare下载数据,可以在pycharm运行。
时间: 2024-02-19 16:57:53 浏览: 142
好的,我可以为您提供一个基于Python的“KDJ+DMI”量化策略的代码实现,可以使用tushare下载数据,可以在PyCharm运行。以下是代码实现:
```python
import tushare as ts
import pandas as pd
import numpy as np
# 下载数据
df = ts.get_k_data('600519', start='2010-01-01', end='2021-05-31')
# 计算KDJ指标
def cal_KDJ(data, n=9, m1=3, m2=3):
high_list = data['high'].rolling(window=n, min_periods=1).max()
low_list = data['low'].rolling(window=n, min_periods=1).min()
rsv = (data['close'] - low_list) / (high_list - low_list) * 100
data['KDJ_K'] = pd.DataFrame(rsv).ewm(com=m1).mean()
data['KDJ_D'] = data['KDJ_K'].ewm(com=m2).mean()
data['KDJ_J'] = 3 * data['KDJ_K'] - 2 * data['KDJ_D']
return data
# 计算DMI指标
def cal_DMI(data, n=14, m=6):
i = 0
UpI = [0]
DoI = [0]
while i + 1 <= data.index[-1]:
UpMove = data.loc[i + 1, 'high'] - data.loc[i, 'high']
DoMove = data.loc[i, 'low'] - data.loc[i + 1, 'low']
if UpMove > DoMove and UpMove > 0:
UpD = UpMove
else:
UpD = 0
UpI.append(UpD)
if DoMove > UpMove and DoMove > 0:
DoD = DoMove
else:
DoD = 0
DoI.append(DoD)
i = i + 1
UpI = pd.Series(UpI)
DoI = pd.Series(DoI)
PosDI = pd.Series(UpI.ewm(span=n, min_periods=n - 1).mean())
NegDI = pd.Series(DoI.ewm(span=n, min_periods=n - 1).mean())
data['PosDI'] = PosDI
data['NegDI'] = NegDI
data['ADX'] = pd.Series((100 * np.abs(PosDI - NegDI) / (PosDI + NegDI)).ewm(span=m, min_periods=m - 1).mean())
data['ADXR'] = ((data['ADX'] + data['ADX'].shift(m - 1)) / 2)
return data
# 运行策略
df = cal_KDJ(df)
df = cal_DMI(df)
df = df.dropna()
df['signal'] = 0
df.loc[(df['KDJ_K'] < df['KDJ_D']) & (df['KDJ_D'] < df['KDJ_J']) & (df['PosDI'] > df['NegDI']) & (df['ADX'] > df['ADXR']), 'signal'] = 1
df.loc[(df['KDJ_K'] > df['KDJ_D']) & (df['KDJ_D'] > df['KDJ_J']) & (df['PosDI'] < df['NegDI']) & (df['ADX'] > df['ADXR']), 'signal'] = -1
# 计算收益
df['pct_change'] = df['close'].pct_change()
df['strategy_return'] = df['pct_change'] * df['signal'].shift(1)
df['accumulative_return'] = (1 + df['strategy_return']).cumprod()
# 输出结果
print(df.tail())
```
该代码首先使用tushare下载股票代码为“600519”的K线数据,时间范围为2010年1月1日到2021年5月31日。接着定义了两个函数分别用于计算KDJ和DMI指标,并在主函数中调用这两个函数计算指标。然后定义了一个简单的策略,根据KDJ和DMI指标产生交易信号,如果KDJ指标出现“金叉”且DMI指标出现多头信号,则产生买入信号,如果KDJ指标出现“死叉”且DMI指标出现空头信号,则产生卖出信号。最后,计算策略的收益率并输出结果。
阅读全文