能写一个python量化代码吗?
时间: 2024-01-13 16:05:45 浏览: 149
当然可以,这里简单给出一个使用Python进行股票数据获取和简单的技术分析的示例代码:
```python
import pandas as pd
import pandas_datareader.data as web
import matplotlib.pyplot as plt
import talib
# 获取股票数据
start = '2010-01-01'
end = '2021-06-30'
stock_code = 'AAPL'
df = web.DataReader(stock_code, 'yahoo', start, end)
# 计算技术指标
df['MA20'] = talib.SMA(df['Close'], timeperiod=20)
df['MA60'] = talib.SMA(df['Close'], timeperiod=60)
df['RSI'] = talib.RSI(df['Close'], timeperiod=14)
df['MACD'], df['MACDsignal'], df['MACDhist'] = talib.MACD(df['Close'], fastperiod=12, slowperiod=26, signalperiod=9)
# 绘制K线图和技术指标图
fig = plt.figure(figsize=(16,8))
ax1 = fig.add_subplot(2,1,1)
ax1.set_title(stock_code + ' K-line')
ax1.set_xlabel('Date')
ax1.set_ylabel('Price')
ax1.grid(True)
candle_data = df.loc[:, ['Open', 'High', 'Low', 'Close']]
candle_data.index.name = 'Date'
candlestick_ohlc(ax1, candle_data.values, width=1, colorup='r', colordown='g')
ax2 = fig.add_subplot(2,1,2)
ax2.set_title(stock_code + ' Technical Indicators')
ax2.set_xlabel('Date')
ax2.set_ylabel('Indicator Value')
ax2.grid(True)
ax2.plot(df.index, df['MA20'], label='MA20')
ax2.plot(df.index, df['MA60'], label='MA60')
ax2.plot(df.index, df['RSI'], label='RSI')
ax2.plot(df.index, df['MACD'], label='MACD')
ax2.plot(df.index, df['MACDsignal'], label='MACDsignal')
ax2.bar(df.index, df['MACDhist']*2, label='MACDhist')
ax2.legend(loc='best')
plt.show()
```
这段代码可以获取苹果公司股票的历史数据,计算出移动平均线、相对强弱指数、移动平均收敛/发散指标等技术指标,并绘制出K线图和技术指标图。
阅读全文