tushare库
- 1. tushare 介绍
 - 2. mplfinance 介绍
 - 3. 获取K线数据
 - 4. 处理数据
 - 5. 数据的可视化
 
1. tushare 介绍
 
点击这里查看 tushare 文档
点击这里注册 tushare 账号
2. mplfinance 介绍
对大多数金融数据使用者来说,最简单也最常见的金融图表非K线图莫数,后面可以看到,使用mplfinance模块,只需要一行代码就可以生成需要的K线图了。不过,为了生成K线数据,我们需要一支股票的open,high,low,close,以及volume历史价格/成交量数据,并且把这些数据存储到一个包含时间序列标签的DataFrame对象中。
3. 获取K线数据
 tushare提供了一系列的股票数据接口,在tushare的文档网站上有相当完备的解释,因此这里就不赘述了,只简单介绍tushare的最基本用法。
 
import tushare as ts
在 
In [1]: daily = ts.pro_bar('000001.SZ', start_date='2019-01-01', end_date='20191231')   
In [2]: daily
       ts_code trade_date   open  ...  pct_chg         vol       amount
0    000001.SZ   20191231  16.57  ...  -0.7242   704442.25  1154704.348
1    000001.SZ   20191230  16.46  ...  -0.3608   976970.31  1603152.786
2    000001.SZ   20191227  16.53  ...   0.9715  1042574.72  1741473.179
3    000001.SZ   20191226  16.34  ...   1.0429   372033.86   610381.757
4    000001.SZ   20191225  16.45  ...  -0.6098   414917.98   679664.596
..         ...        ...    ...  ...      ...         ...          ...
239  000001.SZ   20190108   9.73  ...  -0.8214   402388.11   389247.795
240  000001.SZ   20190107   9.84  ...  -0.1026   865687.66   841166.430
241  000001.SZ   20190104   9.24  ...   5.0647  1481159.06  1422149.888
242  000001.SZ   20190103   9.18  ...   0.9793   415537.95   384457.707
243  000001.SZ   20190102   9.39  ...  -2.0256   539386.32   498695.109
[244 rows x 11 columns]
4. 处理数据
分析获取的数据的结构,可以发现 
In [3]: daily.info() <class 'pandas.core.frame.DataFrame'> RangeIndex: 244 entries, 0 to 243 Data columns (total 11 columns): ts_code 244 non-null object trade_date 244 non-null object open 244 non-null float64 high 244 non-null float64 low 244 non-null float64 close 244 non-null float64 pre_close 244 non-null float64 change 244 non-null float64 pct_chg 244 non-null float64 vol 244 non-null float64 amount 244 non-null float64 dtypes: float64(9), object(2) memory usage: 21.1+ KB
其中的open、high、low、close、和vol几列信息是需要的,其余的数据列都可以删除掉,另外,这些数据的 
In [4]: daily.index=daily.trade_date In [5]: daily = daily.rename(index=pd.Timestamp)
转化后,删除不需要的列,调整 
In [6]: daily.drop(columns=['ts_code', 'trade_date', 'pre_close', 'change', 'pct_chg', 'amount'], inplace=True) In [7]: daily.columns=['open', 'high', 'low', 'close', 'volume'] In [8]: daily.sort_index(inplace=True) In [9]: daily.info() <class 'pandas.core.frame.DataFrame'> DatetimeIndex: 244 entries, 2019-01-02 to 2019-12-31 Data columns (total 5 columns): open 244 non-null float64 high 244 non-null float64 low 244 non-null float64 close 244 non-null float64 volume 244 non-null float64 dtypes: float64(5) memory usage: 21.4+ KB
这样,K线数据就已经准备好了。
5. 数据的可视化
通过mplfinance可以非常容易地生成K线图,只要将这个DataFrame对象直接传递到plot()函数中即可。
点击这里查看完整的实现代码