在大數(shù)據(jù)時(shí)代對(duì)數(shù)據(jù)按自己理解的進(jìn)行可視化是非常關(guān)鍵的一部脐嫂。我們以科大訊飛這一股票從14-11至17-11的數(shù)據(jù)進(jìn)行可視化。我們還是以最簡(jiǎn)單的均線系統(tǒng)規(guī)律來(lái)確立簡(jiǎn)單的買賣點(diǎn)紊遵。版本python3账千。經(jīng)歷的步驟有:
1、提取數(shù)據(jù)暗膜;
2匀奏、解析數(shù)據(jù),得到我們想要的數(shù)據(jù)学搜;
3娃善、對(duì)數(shù)據(jù)進(jìn)行一定處理,便于可視化瑞佩;
4聚磺、可視化;以下是代碼:
# !/usr/bin/env python
# -*- encoding: utf-8 -*-
import sys
import importlib
importlib.reload(sys)
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
def rowIndex(row):
"""添加需要的標(biāo)記和標(biāo)記位置"""
global plt
if row.signal > 0:
#標(biāo)圖示annotate
plt.annotate(u'b', xy=(row.date_o, row.signal), #xy表示被標(biāo)注的位置
arrowprops=dict(facecolor='red', shrink=0.05))
if row.signal < 0:
plt.annotate(u's', xy=(row.date_o, row.signal))
if __name__ == '__main__':
#用lambda表達(dá)式將日期轉(zhuǎn)換為字符格式
daterparse1 = lambda dates: pd.datetime.strptime(dates, "%Y-%m-%d")
#以特定格式和方式讀取csv文件,pandas讀取文件成為DataFrame對(duì)象或者Series對(duì)象
s_list = pd.read_csv('kd.csv', skiprows=0, encoding='utf-8',
index_col='date', parse_dates=True,
date_parser=daterparse1)
s_list['date_o'] = s_list.index #將DataFrame對(duì)象(本身就是字典)的索引存為 原日期的字典
s_list['ma_sub'] = s_list['ma5'] - s_list['ma20']
s_list['diff'] = np.sign(s_list['ma_sub']) #返回?cái)?shù)組中的正負(fù)號(hào)炬丸,分別用1和-1表示
#shift為對(duì)齊操作
s_list['signal'] = np.sign(s_list['diff'] - s_list['diff'].shift(1))
s_list['signal'].plot(ylim=(-2, 2))
(s_list['close']/40).plot(ylim=(-2, 2))
s_list.apply(rowIndex, axis=1) #對(duì)DataFrame對(duì)象的行(axis=1)使用apply方法#返回行索引對(duì)應(yīng)的Series對(duì)象
plt.legend(loc='upper right') #設(shè)置圖例顯示的位置
# plt.legend(loc=4) #upper right/left=1/2;lower left/right=3/4
plt.grid(b=True)
plt.title(u'Ma5--Ma20 to When Buy Or Sell', fontsize=18)
plt.show()
# plt.savefig('002230_mod.png', bbox_inches='tight')
代碼解析:
1瘫寝、需要用到的包,sys稠炬,matplotlib焕阿,pandas,numpy酸纲;
2捣鲸、提取數(shù)據(jù),我們用到的是csv格式數(shù)據(jù)闽坡,相應(yīng)代碼的功能在代碼中已注釋栽惶,首先以自定義方式讀取數(shù)據(jù),我們需要用到日期疾嗅,收盤價(jià)外厂,5日平均及20日平均價(jià)格;其中index_col關(guān)鍵字為指定以哪列數(shù)據(jù)為索引構(gòu)建DataFrame數(shù)據(jù)代承;我們首先看看數(shù)據(jù)是什么樣的:
對(duì)其提取之前先要對(duì)日期格式做一個(gè)調(diào)整汁蝶;lambda可實(shí)現(xiàn)這一功能。parse_dates是對(duì)時(shí)間序列進(jìn)行解析(為真);data_parser為解析日期的函數(shù)——有一個(gè)默認(rèn)函數(shù)掖棉,但使用我們自己定義的函數(shù)墓律;
3、對(duì)數(shù)據(jù)進(jìn)行一系列處理幔亥,提取日期數(shù)據(jù)耻讽;求出均線差值:得出變化范圍的標(biāo)志;得出標(biāo)記信號(hào)帕棉;限制繪圖數(shù)據(jù)范圍针肥,避免溢出看不出趨勢(shì)。
4香伴、定義標(biāo)記函數(shù):用annotate函數(shù)實(shí)現(xiàn)按預(yù)期指定標(biāo)記——標(biāo)記符號(hào)慰枕,位置,箭頭顏色和大屑锤佟具帮;按照行的信號(hào)大小來(lái)標(biāo)記;大于0崇裁,標(biāo)為買匕坯,小余0,標(biāo)為賣拔稳;
5葛峻、可視化,利用定義的信號(hào)及收盤價(jià)巴比、日期來(lái)繪制圖表术奖。以下是輸出結(jié)果:
投資時(shí)點(diǎn)是一個(gè)極其重要的參考指標(biāo),為使買賣信號(hào)更清晰轻绞,便于提示我們什么時(shí)候進(jìn)行買賣采记,我們可以把出現(xiàn)轉(zhuǎn)機(jī)的時(shí)點(diǎn)作為文本,標(biāo)在圖上政勃。
# !/usr/bin/env python
# -*- encoding:utf-8 -*-
import sys
import importlib
#importlib.reload(sys)
#Python3不同唧龄,使用上述語(yǔ)句替代,但不建議使用
#sys.setdefaultencoding('utf-8')
import matplotlib as mpl
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
#交錯(cuò)標(biāo)注日期的轉(zhuǎn)換標(biāo)志
cn = 1
cnb = 1
def rowIndex(row):
"""根據(jù)指示繪制買賣信號(hào)的標(biāo)志"""
global plt, cn, cnb
#交錯(cuò)標(biāo)注日期的位置常數(shù)
buyt = 0.5
buyb = 0.5
if row.signal > 0:
#xy表示被注釋的位置坐標(biāo)
plt.annotate(u'B', xy=(row.date_o, row.signal),
arrowprops=dict(facecolor='red', shrink=0.05))
if cn == 1:
buyt = 1
cn = -1
else:
buyt = 0.5
cn = 1
plt.annotate(str(row.date_o).replace("-", "")[2:8], #日期字符化奸远、替代既棺、切片
xytext=(row.date_o, row.signal + buyt), #文本標(biāo)注的位置
xy = (row.date_o, row.signal + 0.5), #指示標(biāo)志的位置
arrowprops=dict(facecolor='red', shrink=0.5))
if row.signal < 0:
plt.annotate(u'S', xy=(row.date_o, row.signal))
if cnb == 1:
buyb = 1
cnb = -1
else:
buyb = 0.5
cnb = 1
plt.annotate(str(row.date_o).replace("-", "")[2:8],
xytext = (row.date_o, row.signal - buyb),
xy = (row.date_o, row.signal + 0.5),
arrowprops=dict(facecolor='red', shrink=0.5))
if __name__ =="__main__":
mpl.rcParams['font.sans-serif'] = ['Arial Unicode MS'] #正常顯示中文標(biāo)簽
mpl.rcParams['axes.unicode_minus'] = False #正常顯示負(fù)號(hào)
dateparse1 = lambda dates: pd.datetime.strptime(dates, '%Y-%m-%d')
s_list = pd.read_csv("kd.csv", skiprows=0, encoding='utf-8',
index_col='date', parse_dates=True,
date_parser=dateparse1)
s_list['date_o'] = s_list.index
s_list['ma_sub'] = s_list['ma5'] - s_list['ma20']
s_list['diff'] = np.sign(s_list['ma_sub'])
s_list['signal'] = np.sign(s_list['diff'] - s_list['diff'].shift(1))
s_list['signal'].plot(ylim=(-2, 2))
(s_list['close']/40).plot(ylim=(-2, 2))
s_list.apply(rowIndex, axis=1)
plt.legend(loc='upper right')
plt.grid(b=True)
#打開(kāi)matplotlib查看器查看圖形
plt.show()
其中精妙之處在于,使用一個(gè)轉(zhuǎn)換標(biāo)志來(lái)交錯(cuò)的在圖上標(biāo)示提示信息懒叛,避免重疊丸冕,包括距離轉(zhuǎn)換。以下是結(jié)果:
注意的是:
1薛窥、提示標(biāo)志和提示信息是兩塊圖層內(nèi)容胖烛,需要分別繪制眼姐;
2、繪制提示信息時(shí)佩番,需要用到條件語(yǔ)句進(jìn)行限制丽焊,并隨之變更轉(zhuǎn)換標(biāo)志剪菱,將提示信息交錯(cuò)繪制蕴侣;
3产捞、row在python中是一關(guān)鍵字覆致,可以直接應(yīng)用于對(duì)數(shù)據(jù)的相關(guān)處理(定義函數(shù))路捧,調(diào)用函數(shù)時(shí)荒适,程序自動(dòng)按行查找玉转,不需要傳遞實(shí)參持际。
要顯示漢字沃琅,請(qǐng)參考!c12-4.