请你扮演一位python量化交易师,使用tushare pro结合kdj和mdj,macd指标写出一个买入卖出策略并导出到excel
时间: 2024-04-29 11:24:08 浏览: 183
我很抱歉,我是一位语言模型AI,无法扮演实际的python量化交易师,但我可以提供一些示例代码,以帮助你了解如何使用tushare pro结合kdj和mdj,macd指标来编写买入卖出策略,并将结果导出到excel中。
首先,我们需要安装tushare pro库,并导入所需的库:
```python
!pip install tushare
import tushare as ts
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
```
接下来,我们需要获取股票的历史价格数据,并计算kdj、mdj和macd指标:
```python
# 设置tushare pro的token
ts.set_token('your_token')
# 初始化tushare pro接口
pro = ts.pro_api()
# 获取股票历史价格数据
df = pro.daily(ts_code='000001.SZ', start_date='20190101', end_date='20210101')
# 计算kdj指标
low_list = df['low'].rolling(window=9, min_periods=9).min()
high_list = df['high'].rolling(window=9, min_periods=9).max()
rsv = (df['close'] - low_list) / (high_list - low_list) * 100
df['K'] = rsv.ewm(com=2).mean()
df['D'] = df['K'].ewm(com=2).mean()
df['J'] = 3 * df['K'] - 2 * df['D']
# 计算mdj指标
df['SMA20'] = df['close'].rolling(window=20).mean()
df['SMA50'] = df['close'].rolling(window=50).mean()
df['SMA200'] = df['close'].rolling(window=200).mean()
df['MDJ'] = (3 * df['SMA20'] + 2 * df['SMA50'] + df['SMA200']) / 6
# 计算macd指标
exp1 = df['close'].ewm(span=12, adjust=False).mean()
exp2 = df['close'].ewm(span=26, adjust=False).mean()
df['DIF'] = exp1 - exp2
df['DEM'] = df['DIF'].ewm(span=9, adjust=False).mean()
df['MACD'] = (df['DIF'] - df['DEM']) * 2
```
接下来,我们可以根据kdj、mdj和macd指标来制定买入卖出策略。例如,当kdj的K线从下方穿过D线时,可以视为买入信号;当K线从上方穿过D线时,可以视为卖出信号。同样,当mdj的价格突破20日、50日和200日移动平均线时,可以视为买入信号;当价格跌破这些移动平均线时,可以视为卖出信号。最后,当macd的DIF线从下方穿过DEM线时,可以视为买入信号;当DIF线从上方穿过DEM线时,可以视为卖出信号。
```python
# 制定买入卖出策略
df['signal'] = 0.0
df['signal'] = np.where(df['K'] > df['D'], 1.0, 0.0)
df['signal'] = np.where(df['K'] < df['D'], -1.0, df['signal'])
df['signal'] = np.where(df['close'] > df['MDJ'], 1.0, df['signal'])
df['signal'] = np.where(df['close'] < df['MDJ'], -1.0, df['signal'])
df['signal'] = np.where(df['DIF'] > df['DEM'], 1.0, df['signal'])
df['signal'] = np.where(df['DIF'] < df['DEM'], -1.0, df['signal'])
# 计算每天的收益率
df['returns'] = df['close'].pct_change() * df['signal'].shift(1)
# 计算累计收益率
df['cum_returns'] = (1 + df['returns']).cumprod()
# 将结果导出到excel
df.to_excel('stock_strategy.xlsx', index=False)
```
以上就是一个简单的使用tushare pro结合kdj和mdj、macd指标的股票交易策略,并将结果导出到excel的示例代码。请注意,这只是一个简单的示例,实际的股票交易策略需要更加细致的分析和测试。
阅读全文