使用python繪制股票k線圖,該例子從本地加載的數(shù)據(jù)
<pre>
import numpy as np
import matplotlib.pyplot as plt
引入finance模塊自帶的財(cái)經(jīng)數(shù)據(jù)
from matplotlib.finance import quotes_historical_yahoo_ohlc
from matplotlib.dates import YearLocator,MonthLocator,DateFormatter
引入時間
import time
引入finace中的k線繪制圖方法
from matplotlib.finance import candlestick_ohlc
從本地讀取數(shù)據(jù)
import pandas as pd
設(shè)置圖形樣式
plt.style.use('ggplot')
讀取數(shù)據(jù)
df = pd.read_excel('testdata.xlsx')
取得時間數(shù)據(jù)和成交量
dates=df["dates"][1:].values.tolist()
volumns = df["counts"][1:].values.tolist()
取得開盤,結(jié)束,最低,最高的股票數(shù)據(jù)
open=df["open"][1:].values.tolist()
close=df["close"][1:].values.tolist()
low=df["low"][1:].values.tolist()
high=df["high"][1:].values.tolist()
將時間數(shù)據(jù)轉(zhuǎn)換為數(shù)字,此處需要引入time模塊
timestamp = [time.mktime(date.timetuple()) for date in dates]
組合形成quotes,在繪制k線圖的時候需要
quotes = zip(timestamp,open,high,low,close)
定義坐標(biāo)系位置(左下角坐標(biāo)和長寬)
left,width = 0.1,0.8
rect_vol = [left,0.1,width,0.26]
rect_main = [left,0.4,width,0.5]
創(chuàng)建fig圖形框
fig = plt.figure()
添加坐標(biāo)系
ax_vol = fig.add_axes(rect_vol)
繪制成交量填充圖
ax_vol.fill_between(dates,volumns,color='y')
如果從finmance中導(dǎo)入的數(shù)據(jù),需要調(diào)整x軸時間的顯示
ax_vol.xaxis_date()
plt.setp(ax_vol,get_xticklabels(),rotation=30,horizontalalignment='right')
添加k線坐標(biāo)系
ax_main=fig.add_axes(rect_main)
繪制k線圖,此處是quotes為上訴生成的quotes
candlestick_ohlc(ax_main,quotes=quotes,width=0.6,colorup='r',colordown='g')
得到x坐標(biāo)軸設(shè)置x坐標(biāo)顯示為False
ax_main.axes.get_xaxis().set_visible(False)
設(shè)置title
ax_main.set_title('Stock INTC Price and Volume')
顯示圖形
plt.show()
</pre>