首先鸠删,強烈推薦關(guān)注Dr. Fish, 每篇文章都很有深度。因為受到她《用Python淺析股票數(shù)據(jù)》文章的啟發(fā)习贫,所以分享下最近幾天學(xué)習(xí)獲取股票交易歷史數(shù)據(jù)的總結(jié).
pandas 官方文檔
matplotlib 官方文檔
上證指數(shù)
首先略贮,需要引入相應(yīng)的包
import pandas as pd
import numpy as np
from pandas_datareader import data, wb # 需要安裝 pip install pandas_datareader
import datetime
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
%matplotlib inline
%pylab inline
%config InlineBackend.figure_format = 'retina'
如果采用anaconda,安裝辦法參考: 檢索和安裝package
如果是pycharm等其他開發(fā)環(huán)境付材,請
pip install pandas_datareader
利用DataReader獲取數(shù)據(jù),今天是20170420,獲取從4月1日到19日的數(shù)據(jù)
# 定義獲取數(shù)據(jù)的時間段
start = datetime.datetime(2017, 4, 1)
end = datetime.date.today()
# 獲取股票信息 ex: 中國石油
# 如果要看上證指數(shù)請參考換成600000.ss
# 如果要看深成指請換成000001.sz
cnpc = data.DataReader("601857.SS", 'yahoo', start, end)
cnpc.head(5)
Open | High | Low | Close | Volume | Adj Close | |
---|---|---|---|---|---|---|
Date | ||||||
2017-04-03 | 7.87 | 7.87 | 7.87 | 7.87 | 0 | 7.87 |
2017-04-04 | 7.87 | 7.87 | 7.87 | 7.87 | 0 | 7.87 |
2017-04-05 | 7.87 | 7.98 | 7.85 | 7.97 | 54742900 | 7.97 |
2017-04-06 | 7.94 | 7.99 | 7.93 | 7.98 | 40905400 | 7.98 |
2017-04-07 | 8.00 | 8.13 | 7.98 | 8.05 | 81109300 | 8.05 |
獲取統(tǒng)計信息
cnpc.describe() # 數(shù)據(jù)整體概覽
Open | High | Low | Close | Volume | Adj Close | |
---|---|---|---|---|---|---|
count | 13.000000 | 13.000000 | 13.000000 | 13.000000 | 1.300000e+01 | 13.000000 |
mean | 7.978462 | 8.025385 | 7.931538 | 7.984615 | 3.532568e+07 | 7.984615 |
std | 0.078830 | 0.091526 | 0.078299 | 0.089220 | 2.115596e+07 | 0.089220 |
min | 7.870000 | 7.870000 | 7.750000 | 7.800000 | 0.000000e+00 | 7.800000 |
25% | 7.900000 | 7.980000 | 7.870000 | 7.960000 | 2.729580e+07 | 7.960000 |
50% | 8.000000 | 8.060000 | 7.950000 | 8.020000 | 3.735440e+07 | 8.020000 |
75% | 8.040000 | 8.080000 | 7.980000 | 8.050000 | 4.342920e+07 | 8.050000 |
max | 8.080000 | 8.130000 | 8.030000 | 8.100000 | 8.110930e+07 | 8.100000 |
#修改索引和列的名稱
cnpc.rename(columns={'Open':'open', 'High':'high', 'Low':'low', 'Close':'close','Volume':'volumne','Adj Close':'adj close'}, inplace=True)
cnpc.index.rename('date', inplace=True)
open | high | low | close | volume | adj close | |
---|---|---|---|---|---|---|
date | ||||||
2017-04-03 | 7.87 | 7.87 | 7.87 | 7.87 | 0 | 7.87 |
2017-04-04 | 7.87 | 7.87 | 7.87 | 7.87 | 0 | 7.87 |
2017-04-05 | 7.87 | 7.98 | 7.85 | 7.97 | 54742900 | 7.97 |
2017-04-06 | 7.94 | 7.99 | 7.93 | 7.98 | 40905400 | 7.98 |
因為實驗數(shù)據(jù)太少圃阳,現(xiàn)將20170401 改成20170301
cnpc.columns
# outputs: Index(['open', 'high', 'low', 'close', 'volumne', 'adj close', 'change','pct_change'],dtype='object')
試做收盤價曲線
cnpc['close'].plot(grid=True)
我們看到由于清明節(jié)放假原因4月3號,4號休市璧帝。剔除volume為空的行
cnpc[cnpc.volume != 0]
計算漲跌值
# 利用 diff 函數(shù)快速計算漲跌幅
change=cnpc.close.diff()
#插入列
cnpc.insert(6,'change', change)
cnpc.tail(5)
||open|high|low|close|volumne|adj close|change|
| ------------- |:-------------:| -----:|-----:|-----:|-----:|-----:|
|date||||||||
|2017-04-13|8.08|8.11|8.03|8.06|29579200|8.06|-0.04|
|2017-04-14|8.05|8.07|8.00|8.02|27295800|8.02|-0.04|
|2017-04-17|7.99|8.07|7.95|8.05|34244900|8.05|0.03|
|2017-04-18|8.02|8.05|7.95|7.96|25706900|7.96|-0.09|
|2017-04-19|7.90|7.92|7.75|7.80|37354400|7.80|-0.16 |
計算漲跌幅
# 用shift方法錯位
# cnpc['pct_change'] = ((cnpc['Change'] - sh['Change'].shift(1)) / sh['Change'])
# 或用pct_Change函數(shù)
cnpc.change.pct_change()
cnpc.insert(7,'pct_change', cnpc.change.pct_change())
cnpc.tail(5)
||open|high|low|close|volume|adj close|change|pct_change|
| ------------- |:-------------:| -----:|-----:|-----:|-----:|-----:|-----:|
|date||||||||
|2017-04-13|8.08|8.11|8.03|8.06|29579200|8.06|-0.04|-1.500000e+00|
|2017-04-14|8.05|8.07|8.00|8.02|27295800|8.02|-0.04|4.440892e-14|
|2017-04-17|7.99|8.07|7.95|8.05|34244900|8.05|0.03|-1.750000e+00|
|2017-04-18|8.02|8.05|7.95|7.96|25706900|7.96|-0.09|-4.000000e+00|
|2017-04-19|7.90|7.92|7.75|7.80|37354400|7.80|-0.16|7.777778e-01|
shift的用法
shift函數(shù)是對數(shù)據(jù)進(jìn)行移動的操作捍岳,假如現(xiàn)在有一個DataFrame數(shù)據(jù)df
| index | value1 |
| ------------- | -----:||
| A| 0 |
| B| 1 |
| C | 2 |
| D | 3 |
df.shift()
| index | value1 |
| ------------- | -----:||
| A| NaN |
| B| 0|
| C | 1 |
| D | 2 |
函數(shù)原型:
DataFrame.shift(periods=1, freq=None, axis=0)
#periods:類型為int,表示移動的幅度睬隶,可以是正數(shù)锣夹,也可以是負(fù)數(shù),默認(rèn)值是1,1就表示移動一次苏潜,注意這里移動的都是數(shù)據(jù)银萍,而索引是不移動的,移動之后沒有對應(yīng)值的恤左,就賦值為NaN贴唇。
執(zhí)行以下代碼:
df.shift(2)
| index | value1 |
| ------------- | -----:||
| A| NaN |
| B| NaN|
| C | 0|
| D | 1 |
df.shift(-1)
| index | value1 |
| ------------- | -----:||
| A| 1|
| B| 2|
| C | 3|
| D | NaN |
計算5日,20日均線
cnpc["ma5"] = np.round(cnpc["close"].rolling(window = 5, center = False).mean(), 2)
cnpc["ma20"] = np.round(cnpc["close"].rolling(window = 20, center = False).mean(), 2)
用matplotlib圖形化顯示價格信息以及變動
rom datetime import datetime
from dateutil.parser import parse
from matplotlib.dates import AutoDateLocator, DateFormatter,DayLocator
# date = cnpc['date']
# date = pd.to_datetime(date)
date = cnpc.index
high = cnpc['high'].values
low = cnpc['low'].values
open= cnpc['open'].values
close = cnpc['close'].values
ma5 = cnpc['ma5'].values
ma10 = cnpc['ma10'].values
ma20 = cnpc['ma20'].values
# turnover=stock_data['turnover'].values
fig = plt.figure(figsize = (15,15))
ax = fig.add_subplot(211)
ax.set_title("Stock price")
ax.plot(date,open,label='open')
ax.plot(date,high,label='high')
ax.plot(date,low,label = 'low')
ax.plot(date,close,label = 'close')
ax.plot(date,ma5,label = 'ma5')
ax.plot(date,ma10,label = 'ma10')
ax.plot(date,ma20,label = 'ma20')
# ax.plot(date,turnover,label='turnover')
ax.set_xlabel("date")
ax.set_ylabel("values")
ax.xaxis.set_major_locator(DayLocator(bymonthday=range(1,32), interval=1))
ax.xaxis.set_major_formatter(DateFormatter('%Y%m%d'))
plt.xticks(rotation=60)
plt.legend(loc='upper left')
plt.grid(True)
plt.show()
假設(shè)5日均線與20日均線的交叉點飞袋,是交易的時機戳气。移動平均線策略,最簡單的方式就是:當(dāng)5日均線從下方超越20日均線時巧鸭,買入股票瓶您,當(dāng)5日均線從上方越到20日均線之下時,賣出股票纲仍。
為了找出交易的時機呀袱,我們計算5日均價和20日均價的差值,并取其正負(fù)號郑叠,作于下圖夜赵。當(dāng)圖中水平線出現(xiàn)跳躍的時候就是交易時機。
cnpc['ma5-20'] = cnpc['ma5'] - cnpc['ma20']
cnpc['Diff'] = np.sign(cnpc['ma5-20']) # sign是取+-
cnpc['Diff'].dropna().plot(ylim=(-2,2)).axhline(y=0, color='black', lw=2)
K線圖
首先非常感謝DrFish提供的思路锻拘,K線圖可以將最高價油吭、最低價击蹲、開盤價、收盤價四個價格指標(biāo)很好的顯示出來
如下代碼引用自DrFish的文章:
from matplotlib.finance import candlestick_ohlc
from matplotlib.dates import DateFormatter, WeekdayLocator, DayLocator, MONDAY
# TUESDAY 僅僅在X粥主軸上顯示周二的日期
def pandas_candlestick_ohlc(stock_data, otherseries=None):
# 設(shè)置繪圖參數(shù)婉宰,主要是坐標(biāo)軸
mondays = WeekdayLocator(MONDAY)
alldays = DayLocator()
dayFormatter = DateFormatter('%d')
fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)
print(stock_data.index)
print(stock_data.index[-1])
print(stock_data.index[0])
if stock_data.index[-1] - stock_data.index[0] < pd.Timedelta('730 days'):
weekFormatter = DateFormatter('%b %d')
ax.xaxis.set_major_locator(mondays)
ax.xaxis.set_minor_locator(alldays)
else:
weekFormatter = DateFormatter('%b %d, %Y')
ax.xaxis.set_major_formatter(weekFormatter)
ax.grid(True)
# 創(chuàng)建K線圖
stock_array = np.array(stock_data.reset_index()[['date','open','high','low','close']])
stock_array[:,0] = date2num(stock_array[:,0])
candlestick_ohlc(ax, stock_array, colorup = "red", colordown="green", width=0.4)
# 可同時繪制其他折線圖
if otherseries is not None:
for each in otherseries:
plt.plot(stock_data[each], label=each)
plt.legend()
ax.xaxis_date()
ax.autoscale_view()
plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
plt.show()
相關(guān)系數(shù)展示
前一篇文章中歌豺,我只是通過循環(huán)print出各自的相關(guān)系數(shù),但是沒有進(jìn)行圖形化的展示心包,通過DrFish的講解, 此處引用當(dāng)做筆記
part=cnpc[['open', 'high', 'low', 'close', 'volumne', 'adj close']]
cov = np.corrcoef(part.T) # 通過矩陣的轉(zhuǎn)置
cov
#array([[ 1. , 0.93329891, 0.91815383, 0.81640801, -0.12577619,
0.81640801],
[ 0.93329891, 1. , 0.938317 , 0.92304648, -0.00264197,
0.92304648],
[ 0.91815383, 0.938317 , 1. , 0.9365154 , -0.21158285,
0.9365154 ],
[ 0.81640801, 0.92304648, 0.9365154 , 1. , -0.10726339,
1. ],
[-0.12577619, -0.00264197, -0.21158285, -0.10726339, 1. ,
-0.10726339],
[ 0.81640801, 0.92304648, 0.9365154 , 1. , -0.10726339,
1. ]])
如果覺得看數(shù)字還是不夠方便类咧,我們繼續(xù)將上述相關(guān)性矩陣轉(zhuǎn)換成圖形,如下圖所示蟹腾,其中用顏色來代表相關(guān)系數(shù)痕惋。
img = plt.matshow(cov,cmap=plt.cm.winter)
plt.colorbar(img, ticks=[-1,0,1])
plt.show()
本文主要是為了熟悉pandas, matplotlib使用,供自己和大家學(xué)習(xí)參考.