python 利率获取
20 October 2018
本文介绍如何使用 tushare 包来获取利率数据,并通过 matplotlib 绘制利率走势图。
%matplotlib notebook
import numpy as np
import pandas as pd
import tushare as ts
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as mtick
def filter_dr(dr, dtype):
"""
从利率的 dataframe 中获取指定类型的利率
@dr: 利率数据
@dtype: 利率类型,例如:'定期存款整存整取(一年)'
"""
# 过滤出指定类型的利率数据
result = dr.loc[ dr['deposit_type'] == dtype ]
# 过滤无效数据
result = result.loc[ result['rate'] != '--' ]
# 丢弃类型数据,只保留时间和利率值
result = result.drop(['deposit_type'], axis=1)
# 时间格式
result.date = pd.to_datetime(result.date)
result.rate = pd.to_numeric(result.rate, errors='coerce')
# result.sort_values('date', inplace=True)
# result.set_index(['date'], inplace = True)
return result
def plot_dr(dr, title):
"""
绘制利率图
@dr : 利率数据
@title : 图的标题
"""
# drtypes = pd.unique(dr['deposit_type'])
drtypes = ['定期存款整存整取(一年)', '定期存款整存整取(三年)', '定期存款整存整取(五年)']
fig = plt.figure(figsize=(10,6))
ax = fig.add_subplot(1,1,1)
for drtype in drtypes:
result = filter_dr(dr, drtype)
ax.plot(result['date'], result['rate'], label=drtype)
fmt='%.2f%%'
ax.yaxis.set_major_formatter(mtick.FormatStrFormatter(fmt))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
ymin, ymax = ax.get_ylim()
ax.set_yticks(np.round(np.linspace(ymin, ymax, 20), 2))
plt.xticks(rotation=60)
plt.xlabel('日期')
plt.ylabel('利率(%)')
plt.title(title)
plt.subplots_adjust(bottom=0.2, right=0.9, left=0.1)
plt.legend()
plt.show()
# 使用 tushare 获取利率数据
deposit_rate = ts.get_deposit_rate()
# 画利率走势图
plot_dr(deposit_rate, '利率走势图')
# 查看一年期利率数据
filter_dr(deposit_rate, '定期存款整存整取(一年)')
date | rate | |
---|---|---|
6 | 2015-10-24 | 1.50 |
20 | 2015-08-26 | 1.75 |
34 | 2015-06-28 | 2.00 |
48 | 2015-05-11 | 2.25 |
62 | 2015-03-01 | 2.50 |
76 | 2014-11-22 | 2.75 |
90 | 2012-07-06 | 3.00 |
104 | 2012-06-08 | 3.25 |
118 | 2011-07-07 | 3.50 |
132 | 2011-04-06 | 3.25 |
146 | 2011-02-09 | 3.00 |
160 | 2010-12-26 | 2.75 |
174 | 2010-10-20 | 2.50 |
188 | 2008-12-23 | 2.25 |
202 | 2008-11-27 | 2.52 |
216 | 2008-10-30 | 3.60 |
230 | 2008-10-09 | 3.87 |
244 | 2007-12-21 | 4.14 |
258 | 2007-09-15 | 3.87 |
272 | 2007-08-22 | 3.60 |
286 | 2007-07-21 | 3.33 |
300 | 2007-05-19 | 3.06 |
314 | 2007-03-18 | 2.79 |
328 | 2006-08-19 | 2.52 |
342 | 2004-10-29 | 2.25 |
356 | 2002-02-21 | 1.98 |
370 | 1999-06-10 | 2.25 |
384 | 1998-12-07 | 3.78 |
398 | 1998-07-01 | 4.77 |
412 | 1998-03-25 | 5.22 |
426 | 1997-10-23 | 5.67 |
440 | 1996-08-23 | 7.47 |
454 | 1996-05-01 | 9.18 |
468 | 1993-07-11 | 10.98 |
482 | 1993-05-15 | 9.18 |
496 | 1991-04-21 | 7.56 |
510 | 1990-08-21 | 8.64 |
524 | 1990-04-15 | 10.08 |
538 | 1989-02-01 | 11.34 |