MACD策略实训有代码的
时间: 2024-03-20 16:41:44 浏览: 18
当然可以,以下是Python代码实现MACD策略:
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 读取股票数据,以中国平安为例
df = pd.read_csv('601318.csv')
df = df.iloc[::-1]
df.reset_index(inplace=True)
df['EMA12'] = df['close'].ewm(span=12).mean()
df['EMA26'] = df['close'].ewm(span=26).mean()
df['DIF'] = df['EMA12'] - df['EMA26']
df['DEA'] = df['DIF'].ewm(span=9).mean()
df['MACD'] = 2 * (df['DIF'] - df['DEA'])
# 绘制股票价格和MACD指标线
fig, ax = plt.subplots(2, sharex=True)
ax[0].plot(df['date'], df['close'])
ax[1].bar(df['date'], df['MACD'])
plt.show()
# 判断买入或卖出信号
df['signal'] = np.where((df['DIF'] > df['DEA']) & (df['DIF'].shift() < df['DEA'].shift()), 'buy', '')
df['signal'] = np.where((df['DIF'] < df['DEA']) & (df['DIF'].shift() > df['DEA'].shift()), 'sell', df['signal'])
# 绘制股票价格和买卖信号
fig, ax = plt.subplots()
ax.plot(df['date'], df['close'])
ax.plot(df.loc[df['signal'] == 'buy', 'date'], df.loc[df['signal'] == 'buy', 'close'], 'o', color='green')
ax.plot(df.loc[df['signal'] == 'sell', 'date'], df.loc[df['signal'] == 'sell', 'close'], 'o', color='red')
plt.show()
```
代码实现了以下功能:
1. 读取股票数据,并计算出MACD指标和信号线;
2. 绘制股票价格和MACD指标线的图表;
3. 判断买入或卖出信号,并在图表上绘制出买卖点。
需要注意的是,这里的股票数据需要包含日期、开盘价、最高价、最低价、收盘价等信息。如果没有这些信息,需要在代码中进行相应的修改。