利用python numpy+matplotlib繪制股票k線圖的方法
一、python numpy + matplotlib 畫股票k線圖
# -- coding: utf-8 --
import requests
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
fig = plt.figure(figsize=(8,6), dpi=72,facecolor="white")
axes = plt.subplot(111)
axes.set_title('Shangzheng')
axes.set_xlabel('time')
line, = axes.plot([], [], linewidth=1.5, linestyle='-')
alldata = []
def dapan(code):
url = 'http://hq.sinajs.cn/?list='+code
r = requests.get(url)
data = r.content[21:-3].decode('gbk').encode('utf8').split(',')
alldata.append(data[3])
axes.set_ylim(float(data[5]), float(data[4]))
return alldata
def init():
line.set_data([], [])
return line
def animate(i):
axes.set_xlim(0, i+10)
x = range(i+1)
y = dapan('sh000001')
line.set_data(x, y)
return line
anim=animation.FuncAnimation(fig, animate, init_func=init, frames=10000, interval=5000)
plt.show()
二、使用matplotlib輕松繪制股票K線圖
K線圖是看懂股票走勢的最基本知識,K線分為陰線和陽線,陰線和陽線都包含了最低價、開盤價、最高價和收盤價,一般都K線如下圖所示:

在使用Python進(jìn)行股票分析的過程中,我們可以很容易的對K線圖進(jìn)行繪制,下面介紹兩種情形下的K線圖繪制:
1. 股票數(shù)據(jù)來源于Matplotlib:
# 導(dǎo)入需要的庫
import tushare as ts
import matplotlib.pyplot as plt
import matplotlib.finance as mpf
%matplotlib inline
# 設(shè)置歷史數(shù)據(jù)區(qū)間
date1 = (2014, 12, 1) # 起始日期,格式:(年,月,日)元組
date2 = (2016, 12, 1) # 結(jié)束日期,格式:(年,月,日)元組
# 從雅虎財經(jīng)中獲取股票代碼601558的歷史行情
quotes = mpf.quotes_historical_yahoo_ohlc('601558.ss', date1, date2)
# 創(chuàng)建一個子圖
fig, ax = plt.subplots(facecolor=(0.5, 0.5, 0.5))
fig.subplots_adjust(bottom=0.2)
# 設(shè)置X軸刻度為日期時間
ax.xaxis_date()
# X軸刻度文字傾斜45度
plt.xticks(rotation=45)
plt.title("股票代碼:601558兩年K線圖")
plt.xlabel("時間")
plt.ylabel("股價(元)")
mpf.candlestick_ohlc(ax,quotes,width=1.2,colorup='r',colordown='green')
plt.grid(True)
繪制出來的K線圖如下:

2.股票數(shù)據(jù)來源于Tushare:
因為從Tushare中獲取到的數(shù)據(jù)為Pandas的DataFrame結(jié)構(gòu),需要將其轉(zhuǎn)換為matplotlib.finance.candlestick_ohlc()方法能夠處理的數(shù)據(jù)結(jié)構(gòu)。
from matplotlib.pylab import date2num
import datetime
# 對tushare獲取到的數(shù)據(jù)轉(zhuǎn)換成candlestick_ohlc()方法可讀取的格式
data_list = []
for dates,row in hist_data.iterrows():
# 將時間轉(zhuǎn)換為數(shù)字
date_time = datetime.datetime.strptime(dates,'%Y-%m-%d')
t = date2num(date_time)
open,high,low,close = row[:4]
datas = (t,open,high,low,close)
data_list.append(datas)
# 創(chuàng)建子圖
fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)
# 設(shè)置X軸刻度為日期時間
ax.xaxis_date()
plt.xticks(rotation=45)
plt.yticks()
plt.title("股票代碼:601558兩年K線圖")
plt.xlabel("時間")
plt.ylabel("股價(元)")
mpf.candlestick_ohlc(ax,data_list,width=1.5,colorup='r',colordown='green')
plt.grid()
同樣也能繪制會一樣的K線圖:

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python+unittest+requests實現(xiàn)接口自動化的方法
這篇文章主要介紹了python+unittest+requests實現(xiàn)接口自動化的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11
pandas中關(guān)于apply+lambda的應(yīng)用
本文主要介紹了pandas中關(guān)于apply+lambda的應(yīng)用,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02
人工神經(jīng)網(wǎng)絡(luò)算法知識點總結(jié)
在本篇內(nèi)容里小編給大家分享了人工神經(jīng)網(wǎng)絡(luò)算法的相關(guān)知識點以及原理介紹,需要的朋友們參考下。2019-06-06
Python attrs提高面向?qū)ο缶幊绦试敿?xì)
Python是面向?qū)ο蟮恼Z言,一般情況下使用面向?qū)ο缶幊虝沟瞄_發(fā)效率更高,軟件質(zhì)量更好,并且代碼更易于擴展,可讀性和可維護(hù)性也更高,但是Python的類寫起來是真的累,這是可以在創(chuàng)建類的時候自動添加上attrs模塊,下面文章我們就來介紹這個東西,需要的朋友可參考一下2021-09-09
Python如何從txt文件中提取特定數(shù)據(jù)
這篇文章主要給大家介紹了關(guān)于Python如何從txt文件中提取特定數(shù)據(jù)的相關(guān)資料,有時我們會遇到需要按行讀取文本的情況,我們要讀取txt文件獲得數(shù)據(jù),需要的朋友可以參考下2023-08-08

