以下是一個(gè)使用Python獲取A股歷史股價(jià)數(shù)據(jù)、計(jì)算指標(biāo)并進(jìn)行分析的簡(jiǎn)單示例:
import tushare as ts
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 獲取股票歷史價(jià)格數(shù)據(jù)
symbol = '600036.SH' # 以招商銀行為例
start_date = '2010-01-01'
end_date = '2022-12-31'
df = ts.get_k_data(symbol, start=start_date, end=end_date)
# 計(jì)算移動(dòng)平均線
n = 20 # 移動(dòng)平均線周期
df['SMA'] = df['close'].rolling(n).mean()
# 計(jì)算指標(biāo)
df['RSI'] = talib.RSI(df['close'].values, timeperiod=14)
df['MACD'], df['MACDsignal'], df['MACDhist'] = talib.MACD(df['close'].values, fastperiod=12, slowperiod=26, signalperiod=9)
# 生成交易信號(hào)
df['Signal'] = np.where(df['MACD'] > df['MACDsignal'], 1, -1)
df['Trade'] = df['Signal'].diff()
# 計(jì)算收益
df['Ret'] = np.log(df['close'] / df['close'].shift(1))
df['Strategy Ret'] = df['Ret'] * df['Trade'].shift(1)
df['Cumulative Ret'] = np.exp(df['Strategy Ret'].cumsum())
# 繪制資產(chǎn)曲線和指標(biāo)圖表
fig, ax = plt.subplots(2, 1, figsize=[12, 8])
ax[0].plot(df['date'], df['close'], label='股票價(jià)格')
ax[0].plot(df['date'], df['SMA'], label='20日移動(dòng)平均線')
ax[1].plot(df['date'], df['RSI'], label='相對(duì)強(qiáng)弱指標(biāo)(RSI)')
ax[2].plot(df['date'], df['MACD'], label='移動(dòng)平均散度(MACD)')
ax[2].plot(df['date'], df['MACDsignal'], label='MACD信號(hào)線')
ax[2].bar(df['date'], df['MACDhist'], label='MACD柱狀圖')
ax[3].plot(df['date'], df['Cumulative Ret'], label='策略收益')
plt.legend()
plt.show()
這個(gè)代碼塊獲取了招商銀行的歷史價(jià)格數(shù)據(jù),并計(jì)算了幾個(gè)基本指標(biāo)(20日移動(dòng)平均線、相對(duì)強(qiáng)弱指標(biāo)、移動(dòng)平均散度)。最后,該示例以移動(dòng)平均散度指標(biāo)為依據(jù)進(jìn)行買賣決策,并繪制策略收益的資產(chǎn)曲線。請(qǐng)注意,這個(gè)示例僅僅是一個(gè)簡(jiǎn)單的演示,具體的交易策略需要更加復(fù)雜的算法以及對(duì)市場(chǎng)狀況的精確分析。
聯(lián)系客服