用python编写一个均线策略?
时间: 2023-07-01 20:08:30 浏览: 106
均线策略是一种常见的股票交易策略,它基于股票价格的均线(moving average)来进行买卖决策。具体来说,当股票价格从下方突破均线时,我们认为这是一个买入信号;当股票价格从上方跌破均线时,我们认为这是一个卖出信号。
下面是一个用 Python 编写的简单均线策略示例:
```python
import pandas as pd
import yfinance as yf
# 下载股票价格数据
symbol = 'AAPL' # Apple Inc.
start_date = '2015-01-01'
end_date = '2021-12-31'
stock_data = yf.download(symbol, start=start_date, end=end_date)
# 计算20日均线和50日均线
ma_20 = stock_data['Close'].rolling(window=20).mean()
ma_50 = stock_data['Close'].rolling(window=50).mean()
# 判断买卖信号
signals = pd.DataFrame(index=stock_data.index)
signals['signal'] = 0.0
signals['short_ma'] = ma_20
signals['long_ma'] = ma_50
signals['signal'][20:] = np.where(signals['short_ma'][20:] > signals['long_ma'][20:], 1.0, 0.0)
signals['positions'] = signals['signal'].diff()
# 可视化策略表现
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10, 6))
ax1 = fig.add_subplot(111, ylabel='Price in $')
stock_data['Close'].plot(ax=ax1, color='b', lw=2.)
ma_20.plot(ax=ax1, color='r', lw=2.)
ma_50.plot(ax=ax1, color='g', lw=2.)
# 在买入和卖出信号处标记
buy_signals = signals[signals['positions'] == 1.0]
sell_signals = signals[signals['positions'] == -1.0]
ax1.plot(buy_signals.index, stock_data['Close'][buy_signals.index], '^', markersize=10, color='m')
ax1.plot(sell_signals.index, stock_data['Close'][sell_signals.index], 'v', markersize=10, color='k')
plt.show()
```
这段代码首先使用 `yfinance` 模块下载股票价格数据,然后计算了 20 日均线和 50 日均线,接着根据均线的交叉情况判断买卖信号。最后使用 `matplotlib` 可视化了策略的表现,并在买入和卖出信号处进行了标记。
阅读全文