用Python 畫(huà)K線(xiàn)

本文將使用Python來(lái)可視化股票數(shù)據(jù),比如繪制K線(xiàn)圖,并且探究各項(xiàng)指標(biāo)的含義和關(guān)系,最后使用移動(dòng)平均線(xiàn)方法初探投資策略。

相傳K線(xiàn)圖起源于日本德川幕府時(shí)代,當(dāng)時(shí)的商人用此圖來(lái)記錄米市的行情和價(jià)格波動(dòng),后來(lái)K線(xiàn)圖被引入到股票市場(chǎng)。每天的四項(xiàng)指標(biāo)數(shù)據(jù)用如下蠟燭形狀的圖形來(lái)記錄,不同的顏色代表漲跌情況。

Matplotlib.finance模塊提供了繪制K線(xiàn)圖的函數(shù)candlestick_ohlc(),但如果要繪制比較美觀的K線(xiàn)圖還是要下點(diǎn)功夫的。下面定義了pandas_candlestick_ohlc()函數(shù)來(lái)繪制適用于本文數(shù)據(jù)的K線(xiàn)圖,其中大部分代碼都是在設(shè)置坐標(biāo)軸的格式。

from matplotlib.finance import candlestick_ohlc
from matplotlib.dates import DateFormatter, WeekdayLocator, DayLocator, MONDAY, date2num
import pandas as pd
import numpy as np
import talib as ta
import tushare as ts
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')
import seaborn as sns
sns.set_style('white')
from matplotlib import dates
import matplotlib as mpl
%matplotlib inline
myfont =mpl.font_manager.FontProperties(fname=r"c:\windows\fonts\simsun.ttc",size=14)
plt.rcParams["figure.figsize"] = (20,10)

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)
    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線(xiàn)圖   
    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)


    # 可同時(shí)繪制其他折線(xiàn)圖
    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()
stock_data = ts.get_k_data("600600")
stock_data = stock_data[:300]
stock_data.index =pd.to_datetime(stock_data.date)
del stock_data["date"]
stock_data["ma5"] = np.round(stock_data["close"].rolling(window = 5, center = False).mean(), 2)
stock_data["ma20"] = np.round(stock_data["close"].rolling(window = 20, center = False).mean(), 2)
pandas_candlestick_ohlc(stock_data, ['ma5','ma20'])
image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容