本文將使用Python來可視化股票數(shù)據(jù),比如繪制K線圖,并且探究各項(xiàng)指標(biāo)的含義和關(guān)系缸榛,最后使用移動(dòng)平均線方法初探投資策略吝羞。
相傳K線圖起源于日本德川幕府時(shí)代,當(dāng)時(shí)的商人用此圖來記錄米市的行情和價(jià)格波動(dòng)内颗,后來K線圖被引入到股票市場(chǎng)钧排。每天的四項(xiàng)指標(biāo)數(shù)據(jù)用如下蠟燭形狀的圖形來記錄,不同的顏色代表漲跌情況均澳。
Matplotlib.finance模塊提供了繪制K線圖的函數(shù)candlestick_ohlc()恨溜,但如果要繪制比較美觀的K線圖還是要下點(diǎn)功夫的。下面定義了pandas_candlestick_ohlc()函數(shù)來繪制適用于本文數(shù)據(jù)的K線圖找前,其中大部分代碼都是在設(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線圖
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í)繪制其他折線圖
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'])