用Python做股市數(shù)據(jù)分析(一)
這篇博文是用Python分析股市數(shù)據(jù)系列兩部中的第一部,內(nèi)容基于我猶他大學(xué) 數(shù)學(xué)3900 (數(shù)據(jù)科學(xué))的課程。在這些博文中,我會(huì)討論一些基礎(chǔ)知識(shí)。比如如何用pandas從雅虎財(cái)經(jīng)獲得數(shù)據(jù), 可視化股市數(shù)據(jù),平局?jǐn)?shù)指標(biāo)的定義,設(shè)計(jì)移動(dòng)平均交匯點(diǎn)分析移動(dòng)平均線的方法,回溯測(cè)試, 基準(zhǔn)分析法。最后一篇博文會(huì)包含問題以供練習(xí)。第一篇博文會(huì)包含平局?jǐn)?shù)指標(biāo)以及之前的內(nèi)容。
注意:本文僅代表作者本人的觀點(diǎn)。文中的內(nèi)容不應(yīng)該被當(dāng)做經(jīng)濟(jì)建議。我不對(duì)文中代碼負(fù)責(zé),取用者自己負(fù)責(zé)。
引言
金融業(yè)使用高等數(shù)學(xué)和統(tǒng)計(jì)已經(jīng)有段時(shí)日。早在八十年代以前,銀行業(yè)和金融業(yè)被認(rèn)為是“枯燥”的;投資銀行跟商業(yè)銀行是分開的,業(yè)界主要的任務(wù)是處理“簡(jiǎn)單的”(跟當(dāng)今相比)的金融職能,例如貸款。里根政府的減少調(diào)控和數(shù)學(xué)的應(yīng)用,使該行業(yè)從枯燥的銀行業(yè)變?yōu)榻裉斓哪印T谀侵?,金融躋身科學(xué),成為推動(dòng)數(shù)學(xué)研究和發(fā)展的力量。例如數(shù)學(xué)上一個(gè)重大進(jìn)展是布萊克-舒爾斯公式的推導(dǎo)。它被用來股票定價(jià) (一份賦予股票持有者以一定的價(jià)格從股票發(fā)行者手中買入和賣出的合同)。但是, 不好的統(tǒng)計(jì)模型,包括布萊克-舒爾斯模型, 背負(fù)了部分導(dǎo)致2008金融危機(jī)的罵名。
近年來,計(jì)算機(jī)科學(xué)加入了高等數(shù)學(xué)的陣營(yíng),為金融和證券交易(為了盈利而進(jìn)行的金融產(chǎn)品買入賣出行為)帶來了革命性的變化。如今交易主要由計(jì)算機(jī)來完成:算法能以人類難以達(dá)到的速度做出交易決策(參看光速的限制已經(jīng)成為系統(tǒng)設(shè)計(jì)中的瓶頸)。機(jī)器學(xué)習(xí)和數(shù)據(jù)挖掘也被越來越廣泛的用到金融領(lǐng)域中,目測(cè)這個(gè)勢(shì)頭會(huì)保持下去。事實(shí)上很大一部分的算法交易都是高頻交易(HFT)。雖然算法比人工快,但這些技術(shù)還是很新,而且被應(yīng)用在一個(gè)以不穩(wěn)定,高風(fēng)險(xiǎn)著稱的領(lǐng)域。據(jù)一條被黑客曝光的白宮相關(guān)媒體推特表明HFT應(yīng)該對(duì)2010 閃電式崩盤 and a 2013 閃電式崩盤 負(fù)責(zé)。
不過這節(jié)課不是關(guān)于如何利用不好的數(shù)學(xué)模型來摧毀證券市場(chǎng)。相反的,我將提供一些基本的Python工具來處理和分析股市數(shù)據(jù)。我會(huì)講到移動(dòng)平均值,如何利用移動(dòng)平均值來制定交易策略,如何制定進(jìn)入和撤出股市的決策,記憶如何利用回溯測(cè)試來評(píng)估一個(gè)決策。
免責(zé)申明:這不是投資建議。同時(shí)我私人完全沒有交易經(jīng)驗(yàn)(文中相關(guān)的知識(shí)大部分來自我在鹽湖城社區(qū)大學(xué)參加的一個(gè)學(xué)期關(guān)于股市交易的課程)!這里僅僅是基本概念知識(shí),不足以用于實(shí)際交易的股票。股票交易可以讓你受到損失(已有太多案例),你要為自己的行為負(fù)責(zé)。
獲取并可視化股市數(shù)據(jù)
從雅虎金融獲取數(shù)據(jù)
在分析數(shù)據(jù)之前得先得到數(shù)據(jù)。股市數(shù)據(jù)可以從Yahoo! Finance、 Google Finance以及其他的地方拿到。同時(shí),pandas包提供了輕松從以上網(wǎng)站獲取數(shù)據(jù)的方法。這節(jié)課我們使用雅虎金融的數(shù)據(jù)。
下面的代碼展示了如何直接創(chuàng)建一個(gè)含有股市數(shù)據(jù)的DataFrame。(更多關(guān)于遠(yuǎn)程獲取數(shù)據(jù)的信息,點(diǎn)擊這里(http://pandas.pydata.org/pandas-docs/stable/remote_data.html))
- import pandas as pd
- import pandas.io.data as web # Package and modules for importing data; this code may change depending on pandas version
- import datetime
- # We will look at stock prices over the past year, starting at January 1, 2016
- start = datetime.datetime(2016,1,1)
- end = datetime.date.today()
- # Let's get Apple stock data; Apple's ticker symbol is AAPL
- # First argument is the series we want, second is the source ("yahoo" for Yahoo! Finance), third is the start date, fourth is the end date
- apple = web.DataReader("AAPL", "yahoo", start, end)
- type(apple)
- C:\Anaconda3\lib\site-packages\pandas\io\data.py:35: FutureWarning:
- The pandas.io.data module is moved to a separate package (pandas-datareader) and will be removed from pandas in a future version.
- After installing the pandas-datareader package (https://github.com/pydata/pandas-datareader), you can change the import ``from pandas.io import data, wb`` to ``from pandas_datareader import data, wb``.
- FutureWarning)
- pandas.core.frame.DataFrame
- apple.head()
讓我們簡(jiǎn)單說一下數(shù)據(jù)內(nèi)容。Open是當(dāng)天的開始價(jià)格(不是前一天閉市的價(jià)格);high是股票當(dāng)天的最高價(jià);low是股票當(dāng)天的最低價(jià);close是閉市時(shí)間的股票價(jià)格。Volume指交易數(shù)量。Adjust close是根據(jù)法人行為調(diào)整之后的閉市價(jià)格。雖然股票價(jià)格基本上是由交易者決定的,stock splits (拆股。指上市公司將現(xiàn)有股票一拆為二,新股價(jià)格為原股的一半的行為)以及dividends(分紅。每一股的分紅)同樣也會(huì)影響股票價(jià)格,也應(yīng)該在模型中被考慮到。
可視化股市數(shù)據(jù)
獲得數(shù)據(jù)之后讓我們考慮將其可視化。下面我會(huì)演示如何使用matplotlib包。值得注意的是appleDataFrame對(duì)象有一個(gè)plot()方法讓畫圖變得更簡(jiǎn)單。
- import matplotlib.pyplot as plt # Import matplotlib
- # This line is necessary for the plot to appear in a Jupyter notebook
- %matplotlib inline
- # Control the default size of figures in this Jupyter notebook
- %pylab inline
- pylab.rcParams['figure.figsize'] = (15, 9) # Change the size of plots
- apple["Adj Close"].plot(grid = True) # Plot the adjusted closing price of AAPL
- Populating the interactive namespace from numpy and matplotlib
線段圖是可行的,但是每一天的數(shù)據(jù)至少有四個(gè)變量(開市,股票最高價(jià),股票最低價(jià)和閉市),我們希望找到一種不需要我們畫四條不同的線就能看到這四個(gè)變量走勢(shì)的可視化方法。一般來說我們使用燭柱圖(也稱為日本陰陽燭圖表)來可視化金融數(shù)據(jù),燭柱圖最早在18世紀(jì)被日本的稻米商人所使用。可以用matplotlib來作圖,但是需要費(fèi)些功夫。
你們可以使用我實(shí)現(xiàn)的一個(gè)函數(shù)更容易地畫燭柱圖,它接受pandas的data frame作為數(shù)據(jù)來源。(程序基于這個(gè)例子, 你可以從這里找到相關(guān)函數(shù)的文檔。)
- from matplotlib.dates import DateFormatter, WeekdayLocator,\
- DayLocator, MONDAY
- from matplotlib.finance import candlestick_ohlc
- def pandas_candlestick_ohlc(dat, stick = "day", otherseries = None):
- """
- :param dat: pandas DataFrame object with datetime64 index, and float columns "Open", "High", "Low", and "Close", likely created via DataReader from "yahoo"
- :param stick: A string or number indicating the period of time covered by a single candlestick. Valid string inputs include "day", "week", "month", and "year", ("day" default), and any numeric input indicates the number of trading days included in a period
- :param otherseries: An iterable that will be coerced into a list, containing the columns of dat that hold other series to be plotted as lines
- This will show a Japanese candlestick plot for stock data stored in dat, also plotting other series if passed.
- """
- mondays = WeekdayLocator(MONDAY) # major ticks on the mondays
- alldays = DayLocator() # minor ticks on the days
- dayFormatter = DateFormatter('%d') # e.g., 12
- # Create a new DataFrame which includes OHLC data for each period specified by stick input
- transdat = dat.loc[:,["Open", "High", "Low", "Close"]]
- if (type(stick) == str):
- if stick == "day":
- plotdat = transdat
- stick = 1 # Used for plotting
- elif stick in ["week", "month", "year"]:
- if stick == "week":
- transdat["week"] = pd.to_datetime(transdat.index).map(lambda x: x.isocalendar()[1]) # Identify weeks
- elif stick == "month":
- transdat["month"] = pd.to_datetime(transdat.index).map(lambda x: x.month) # Identify months
- transdat["year"] = pd.to_datetime(transdat.index).map(lambda x: x.isocalendar()[0]) # Identify years
- grouped = transdat.groupby(list(set(["year",stick]))) # Group by year and other appropriate variable
- plotdat = pd.DataFrame({"Open": [], "High": [], "Low": [], "Close": []}) # Create empty data frame containing what will be plotted
- for name, group in grouped:
- plotdat = plotdat.append(pd.DataFrame({"Open": group.iloc[0,0],
- "High": max(group.High),
- "Low": min(group.Low),
- "Close": group.iloc[-1,3]},
- index = [group.index[0]]))
- if stick == "week": stick = 5
- elif stick == "month": stick = 30
- elif stick == "year": stick = 365
- elif (type(stick) == int and stick >= 1):
- transdat["stick"] = [np.floor(i / stick) for i in range(len(transdat.index))]
- grouped = transdat.groupby("stick")
- plotdat = pd.DataFrame({"Open": [], "High": [], "Low": [], "Close": []}) # Create empty data frame containing what will be plotted
- for name, group in grouped:
- plotdat = plotdat.append(pd.DataFrame({"Open": group.iloc[0,0],
- "High": max(group.High),
- "Low": min(group.Low),
- "Close": group.iloc[-1,3]},
- index = [group.index[0]]))
- else:
- raise ValueError('Valid inputs to argument "stick" include the strings "day", "week", "month", "year", or a positive integer')
- # Set plot parameters, including the axis object ax used for plotting
- fig, ax = plt.subplots()
- fig.subplots_adjust(bottom=0.2)
- if plotdat.index[-1] - plotdat.index[0] < pd.Timedelta('730 days'):
- weekFormatter = DateFormatter('%b %d') # e.g., Jan 12
- 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)
- # Create the candelstick chart
- candlestick_ohlc(ax, list(zip(list(date2num(plotdat.index.tolist())), plotdat["Open"].tolist(), plotdat["High"].tolist(),
- plotdat["Low"].tolist(), plotdat["Close"].tolist())),
- colorup = "black", colordown = "red", width = stick * .4)
- # Plot other series (such as moving averages) as lines
- if otherseries != None:
- if type(otherseries) != list:
- otherseries = [otherseries]
- dat.loc[:,otherseries].plot(ax = ax, lw = 1.3, grid = True)
- ax.xaxis_date()
- ax.autoscale_view()
- plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
- plt.show()
- pandas_candlestick_ohlc(apple)
燭狀圖中黑色線條代表該交易日閉市價(jià)格高于開市價(jià)格(盈利),紅色線條代表該交易日開市價(jià)格高于閉市價(jià)格(虧損)??潭染€代表當(dāng)天交易的最高價(jià)和最低價(jià)(影線用來指明燭身的哪端是開市,哪端是閉市)。燭狀圖在金融和技術(shù)分析中被廣泛使用在交易決策上,利用燭身的形狀,顏色和位置。我今天不會(huì)涉及到策略。
我們也許想要把不同的金融商品呈現(xiàn)在一張圖上:這樣我們可以比較不同的股票,比較股票跟市場(chǎng)的關(guān)系,或者可以看其他證券,例如交易所交易基金(ETFs)。在后面的內(nèi)容中,我們將會(huì)學(xué)到如何畫金融證券跟一些指數(shù)(移動(dòng)平均)的關(guān)系。屆時(shí)你需要使用線段圖而不是燭狀圖。(試想你如何重疊不同的燭狀圖而讓圖表保持整潔?)
下面我展示了不同技術(shù)公司股票的數(shù)據(jù),以及如何調(diào)整數(shù)據(jù)讓數(shù)據(jù)線聚在一起。
- microsoft = web.DataReader("MSFT", "yahoo", start, end)
- google = web.DataReader("GOOG", "yahoo", start, end)
- # Below I create a DataFrame consisting of the adjusted closing price of these stocks, first by making a list of these objects and using the join method
- stocks = pd.DataFrame({"AAPL": apple["Adj Close"],
- "MSFT": microsoft["Adj Close"],
- "GOOG": google["Adj Close"]})
- stocks.head()
- stocks.plot(grid = True)
這張圖表的問題在哪里呢?雖然價(jià)格的絕對(duì)值很重要(昂貴的股票很難購得,這不僅會(huì)影響它們的波動(dòng)性,也會(huì)影響你交易它們的難易度),但是在交易中,我們更關(guān)注每支股票價(jià)格的變化而不是它的價(jià)格。Google的股票價(jià)格比蘋果微軟的都高,這個(gè)差別讓蘋果和微軟的股票顯得波動(dòng)性很低,而事實(shí)并不是那樣。
一個(gè)解決辦法就是用兩個(gè)不同的標(biāo)度來作圖。一個(gè)標(biāo)度用于蘋果和微軟的數(shù)據(jù);另一個(gè)標(biāo)度用來表示Google的數(shù)據(jù)。
- stocks.plot(secondary_y = ["AAPL", "MSFT"], grid = True)
一個(gè)“更好”的解決方法是可視化我們實(shí)際關(guān)心的信息:股票的收益。這需要我們進(jìn)行必要的數(shù)據(jù)轉(zhuǎn)化。數(shù)據(jù)轉(zhuǎn)化的方法很多。其中一個(gè)轉(zhuǎn)化方法是將每個(gè)交易日的股票交個(gè)跟比較我們所關(guān)心的時(shí)間段開始的股票價(jià)格相比較。也就是:
這需要轉(zhuǎn)化stock對(duì)象中的數(shù)據(jù),操作如下:
- # df.apply(arg) will apply the function arg to each column in df, and return a DataFrame with the result
- # Recall that lambda x is an anonymous function accepting parameter x; in this case, x will be a pandas Series object
- stock_return = stocks.apply(lambda x: x / x[0])
- stock_return.head()
- stock_return.plot(grid = True).axhline(y = 1, color = "black", lw = 2)
這個(gè)圖就有用多了?,F(xiàn)在我們可以看到從我們所關(guān)心的日期算起,每支股票的收益有多高。而且我們可以看到這些股票之間的相關(guān)性很高。它們基本上朝同一個(gè)方向移動(dòng),在其他類型的圖表中很難觀察到這一現(xiàn)象。
我們還可以用每天的股值變化作圖。一個(gè)可行的方法是我們使用后一天$t + 1$和當(dāng)天$t$的股值變化占當(dāng)天股價(jià)的比例:
我們也可以比較當(dāng)天跟前一天的價(jià)格:
以上的公式并不相同,可能會(huì)讓我們得到不同的結(jié)論,但是我們可以使用對(duì)數(shù)差異來表示股票價(jià)格變化:
(這里的
是自然對(duì)數(shù),我們的定義不完全取決于使用
還是
.) 使用對(duì)數(shù)差異的好處是該差異值可以被解釋為股票的百分比差異,但是不受分母的影響。
下面的代碼演示了如何計(jì)算和可視化股票的對(duì)數(shù)差異:
- # Let's use NumPy's log function, though math's log function would work just as well
- import numpy as np
- stock_change = stocks.apply(lambda x: np.log(x) - np.log(x.shift(1))) # shift moves dates back by 1.
- stock_change.head()
- stock_change.plot(grid = True).axhline(y = 0, color = "black", lw = 2)
你更傾向于哪種轉(zhuǎn)換方法呢?從相對(duì)時(shí)間段開始日的收益差距可以明顯看出不同證券的總體走勢(shì)。不同交易日之間的差距被用于更多預(yù)測(cè)股市行情的方法中,它們是不容被忽視的。
移動(dòng)平均值
圖表非常有用。在現(xiàn)實(shí)生活中,有些交易人在做決策的時(shí)候幾乎完全基于圖表(這些人是“技術(shù)人員”,從圖表中找到規(guī)律并制定交易策略被稱作技術(shù)分析,它是交易的基本教義之一。)下面讓我們來看看如何找到股票價(jià)格的變化趨勢(shì)。
一個(gè)q天的移動(dòng)平均值(用
來表示)定義為:對(duì)于某一個(gè)時(shí)間點(diǎn)t,它之前q天的平均值。
移動(dòng)平均值可以讓一個(gè)系列的數(shù)據(jù)變得更平滑,有助于我們找到趨勢(shì)。q值越大,移動(dòng)平均對(duì)短期的波動(dòng)越不敏感。移動(dòng)平均的基本目的就是從噪音中識(shí)別趨勢(shì)??焖俚囊苿?dòng)平均有偏小的q,它們更接近股票價(jià)格;而慢速的移動(dòng)平均有較大的q值,這使得它們對(duì)波動(dòng)不敏感從而更加穩(wěn)定。
pandas提供了計(jì)算移動(dòng)平均的函數(shù)。下面我將演示使用這個(gè)函數(shù)來計(jì)算蘋果公司股票價(jià)格的20天(一個(gè)月)移動(dòng)平均值,并將它跟股票價(jià)格畫在一起。
- apple["20d"] = np.round(apple["Close"].rolling(window = 20, center = False).mean(), 2)
- pandas_candlestick_ohlc(apple.loc['2016-01-04':'2016-08-07',:], otherseries = "20d")
注意到平均值的起始點(diǎn)時(shí)間是很遲的。我們必須等到20天之后才能開始計(jì)算該值。這個(gè)問題對(duì)于更長(zhǎng)時(shí)間段的移動(dòng)平均來說是個(gè)更加嚴(yán)重的問題。因?yàn)槲蚁M铱梢杂?jì)算200天的移動(dòng)平均,我將擴(kuò)展我們所得到的蘋果公司股票的數(shù)據(jù),但我們主要還是只關(guān)注2016。
- start = datetime.datetime(2010,1,1)
- apple = web.DataReader("AAPL", "yahoo", start, end)
- apple["20d"] = np.round(apple["Close"].rolling(window = 20, center = False).mean(), 2)
- pandas_candlestick_ohlc(apple.loc['2016-01-04':'2016-08-07',:], otherseries = "20d")
你會(huì)發(fā)現(xiàn)移動(dòng)平均比真實(shí)的股票價(jià)格數(shù)據(jù)平滑很多。而且這個(gè)指數(shù)是非常難改變的:一支股票的價(jià)格需要變到平局值之上或之下才能改變移動(dòng)平均線的方向。因此平均線的交叉點(diǎn)代表了潛在的趨勢(shì)變化,需要加以注意。
交易者往往對(duì)不同的移動(dòng)平均感興趣,例如20天,50天和200天。要同時(shí)生成多條移動(dòng)平均線也不難:
- apple["50d"] = np.round(apple["Close"].rolling(window = 50, center = False).mean(), 2)
- apple["200d"] = np.round(apple["Close"].rolling(window = 200, center = False).mean(), 2)
- pandas_candlestick_ohlc(apple.loc['2016-01-04':'2016-08-07',:], otherseries = ["20d", "50d", "200d"])
20天的移動(dòng)平均線對(duì)小的變化非常敏感,而200天的移動(dòng)平均線波動(dòng)最小。這里的200天平均線顯示出來總體的熊市趨勢(shì):股值總體來說一直在下降。20天移動(dòng)平均線所代表的信息是熊市牛市交替,接下來有可能是牛市。這些平均線的交叉點(diǎn)就是交易信息點(diǎn),它們代表股票價(jià)格的趨勢(shì)會(huì)有所改變因而你需要作出能盈利的相應(yīng)決策。
更新:該文章早期版本提到算法交易跟高頻交易是一個(gè)意思。但是網(wǎng)友評(píng)論指出這并不一定:算法可以用來進(jìn)行交易但不一定就是高頻。高頻交易是算法交易中間很大的一部分,但是兩者不等價(jià)。