目录
导包
import numpy as np
import pandas as pd
Backend TkAgg is interactive backend. Turning interactive mode on.
import pandas_datareader.data as web
读取数据
从雅虎财经读取BABA股票信息
>>> baba = web.DataReader(name = 'BABA',data_source='yahoo',start='2014-09-19')
baba.info() #打印列信息
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 1126 entries, 2014-09-19 to 2019-03-12
Data columns (total 6 columns):
High 1126 non-null float64
Low 1126 non-null float64
Open 1126 non-null float64
Close 1126 non-null float64
Volume 1126 non-null int64
Adj Close 1126 non-null float64
dtypes: float64(5), int64(1)
memory usage: 61.6 KB
>>> baba.tail()
High Low ... Volume Adj Close
Date ...
2019-03-06 185.589996 183.020004 ... 10009100 184.169998
2019-03-07 181.800003 176.729996 ... 16488900 177.320007
2019-03-08 175.350006 171.565002 ... 14674200 175.029999
2019-03-11 181.720001 177.580002 ... 13764000 180.410004
2019-03-12 182.179993 179.509995 ... 8655500 180.630005
[5 rows x 6 columns]
收盘价曲线
baba['Close'].plot(figsize=(8,5)) #设置长宽比例
<matplotlib.axes._subplots.AxesSubplot object at 0x00000168B2F91908>
对数收益率的向量化计算
>>> baba['Return'] = np.log(baba['Close']/baba['Close'].shift(1)) #shift前移
>>> baba[['Close','Return']].plot(subplots=True,style='b',figsize=(8,5)) #分开显示,加粗
array([<matplotlib.axes._subplots.AxesSubplot object at 0x00000168B0DB4828>,
<matplotlib.axes._subplots.AxesSubplot object at 0x00000168B5018EF0>],
dtype=object)
移动平均值计算
月度
baba['30d']=baba['Close'].rolling(window=30).mean() #30日均值
季度
baba['90d']=baba['Close'].rolling(window=90).mean() #90日均值
baba[['Close','30d','90d']].tail()
Close 30d 90d
Date
2019-03-06 184.169998 171.160334 155.307334
2019-03-07 177.320007 172.003335 155.726334
2019-03-08 175.029999 172.642334 156.064445
2019-03-11 180.410004 173.349001 156.481556
2019-03-12 180.630005 174.072668 157.006556
移动历史标准差--移动历史波动率
import math
baba['Mov_Vol_30'] = baba['Return'].rolling(window=30).std()*math.sqrt(30)
baba['Mov_Vol'] = baba['Return'].rolling(window=365).std()*math.sqrt(365)
baba[['Close','Mov_Vol','Mov_Vol_30','Return']].plot(subplots=True,style='b',figsize=(8,7))
array([<matplotlib.axes._subplots.AxesSubplot object at 0x00000168B14E8860>,
<matplotlib.axes._subplots.AxesSubplot object at 0x00000168B524D1D0>,
<matplotlib.axes._subplots.AxesSubplot object at 0x00000168B5482898>],
dtype=object)