import pandas as pd import numpy as np def trade(stockfile): # 读取股票数据 stockdata = pd.read_csv(stockfile) # 计算5日均线和20日均线 stockdata['5MA'] = stockdata['close'].rolling(window=5).mean() stockdata['20MA'] = stockdata['close'].rolling(wind
时间: 2023-07-15 22:13:59 浏览: 149
ow=20).mean() # 计算MACD指标 stockdata['EMA12'] = stockdata['close'].ewm(span=12, adjust=False).mean() stockdata['EMA26'] = stockdata['close'].ewm(span=26, adjust=False).mean() stockdata['DIF'] = stockdata['EMA12'] - stockdata['EMA26'] stockdata['DEA'] = stockdata['DIF'].ewm(span=9, adjust=False).mean() stockdata['MACD'] = (stockdata['DIF'] - stockdata['DEA']) * 2 # 判断买卖信号 stockdata['signal'] = 0 for i in range(1, len(stockdata)): if (stockdata.loc[i, 'DIF'] > stockdata.loc[i, 'DEA']) and (stockdata.loc[i-1, 'DIF'] <= stockdata.loc[i-1, 'DEA']): stockdata.loc[i, 'signal'] = 1 elif (stockdata.loc[i, 'DIF'] < stockdata.loc[i, 'DEA']) and (stockdata.loc[i-1, 'DIF'] >= stockdata.loc[i-1, 'DEA']): stockdata.loc[i, 'signal'] = -1 # 计算收益率 stockdata['profit'] = stockdata['signal'] * stockdata['pct_chg'] # 计算累计收益率 stockdata['cum_profit'] = (stockdata['profit']/100 + 1).cumprod() return stockdata[['trade_date', 'close', '5MA', '20MA', 'DIF', 'DEA', 'MACD', 'signal', 'profit', 'cum_profit']]
这是一个简单的股票交易策略,通过计算均线和MACD指标来判断买卖信号,并计算收益率和累计收益率。你可以将股票数据放在一个csv文件中,然后传递给trade函数进行计算并返回结果。
阅读全文