本文将使用Python来可视化股票数据,比如绘制K线图,并且探究各项指标的含义和关系,最后使用移动平均线方法初探投资策略。
相传K线图起源于日本德川幕府时代,当时的商人用此图来记录米市的行情和价格波动,后来K线图被引入到股票市场。每天的四项指标数据用如下蜡烛形状的图形来记录,不同的颜色代表涨跌情况。
Matplotlib.finance模块提供了绘制K线图的函数candlestick_ohlc(),但如果要绘制比较美观的K线图还是要下点功夫的。下面定义了pandas_candlestick_ohlc()函数来绘制适用于本文数据的K线图,其中大部分代码都是在设置坐标轴的格式。
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):
# 设置绘图参数,主要是坐标轴
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)
# 创建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()
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