请你作为一个python量化交易师,利用tushare的pro版本,结合kdj和mdj和移动平均线,macd指标,进行输出买入和卖出信号并导出到excel表中
时间: 2024-05-09 16:19:37 浏览: 115
以下是一个简单的示例代码,它使用tushare的pro版本来计算KDJ和MDJ指标以及移动平均线和MACD指标,并根据这些指标生成买入和卖出信号,并将其输出到Excel表中:
```python
import tushare as ts
import pandas as pd
import numpy as np
from openpyxl import Workbook
# 设置tushare的token,用于获取数据
ts.set_token('your_token_here')
pro = ts.pro_api()
# 股票代码和时间范围
stock_code = '600519.SH'
start_date = '20150101'
end_date = '20201231'
# 获取股票数据
df_stock = pro.daily(ts_code=stock_code, start_date=start_date, end_date=end_date)
# 转换日期格式
df_stock['trade_date'] = pd.to_datetime(df_stock['trade_date'], format='%Y%m%d')
# 计算KDJ和MDJ指标
high_prices = np.array(df_stock['high'])
low_prices = np.array(df_stock['low'])
close_prices = np.array(df_stock['close'])
df_stock['K'], df_stock['D'], df_stock['J'] = talib.STOCH(high_prices, low_prices, close_prices)
df_stock['M'], df_stock['D1'], df_stock['D2'] = talib.MOM(close_prices)
# 计算移动平均线
df_stock['MA5'] = df_stock['close'].rolling(window=5).mean()
df_stock['MA10'] = df_stock['close'].rolling(window=10).mean()
df_stock['MA20'] = df_stock['close'].rolling(window=20).mean()
# 计算MACD指标
df_stock['ema12'] = df_stock['close'].ewm(span=12).mean()
df_stock['ema26'] = df_stock['close'].ewm(span=26).mean()
df_stock['DIF'] = df_stock['ema12'] - df_stock['ema26']
df_stock['DEA'] = df_stock['DIF'].ewm(span=9).mean()
df_stock['MACD'] = (df_stock['DIF'] - df_stock['DEA']) * 2
# 生成买入和卖出信号
df_stock['signal'] = 0
df_stock.loc[(df_stock['K'] < df_stock['D']) & (df_stock['K'].shift(1) > df_stock['D'].shift(1)), 'signal'] = 1
df_stock.loc[(df_stock['K'] > df_stock['D']) & (df_stock['K'].shift(1) < df_stock['D'].shift(1)), 'signal'] = -1
df_stock.loc[(df_stock['M'] > 0) & (df_stock['M'].shift(1) < 0), 'signal'] = 1
df_stock.loc[(df_stock['M'] < 0) & (df_stock['M'].shift(1) > 0), 'signal'] = -1
df_stock.loc[(df_stock['MACD'] > 0) & (df_stock['MACD'].shift(1) < 0), 'signal'] = 1
df_stock.loc[(df_stock['MACD'] < 0) & (df_stock['MACD'].shift(1) > 0), 'signal'] = -1
# 将结果输出到Excel表中
wb = Workbook()
ws = wb.active
ws.append(['日期', '开盘价', '最高价', '最低价', '收盘价', '成交量', 'K', 'D', 'J', 'M', 'D1', 'D2',
'MA5', 'MA10', 'MA20', 'DIF', 'DEA', 'MACD', '信号'])
for idx, row in df_stock.iterrows():
ws.append([row['trade_date'], row['open'], row['high'], row['low'], row['close'], row['vol'],
row['K'], row['D'], row['J'], row['M'], row['D1'], row['D2'],
row['MA5'], row['MA10'], row['MA20'], row['DIF'], row['DEA'], row['MACD'], row['signal']])
wb.save('output.xlsx')
```
这个示例代码中,我们使用了tushare的pro版本来获取指定股票的日线数据。然后,我们使用talib库计算KDJ和MDJ指标以及移动平均线和MACD指标。接着,我们生成买入和卖出信号,并将结果输出到Excel表中。注意,这里我们使用了openpyxl库来将结果写入Excel表中。
当然,这只是一个简单的示例代码,实际应用中还需要根据具体情况进行调整和完善。例如,我们可能需要加入更多的指标或参数来提高交易策略的准确性和稳定性。同时,我们还需要考虑交易成本、滑点等因素,以便更好地模拟实际交易情况。
阅读全文