在本篇学习日志中,我们将深入了解如何使用Tushare库获取美国历年国债利率数据,并进行详细的数据分析。
第一部分:初始化与数据获取
首先,我们需要初始化Tushare API,并使用us_tycr
接口获取美国历年国债利率数据。
import tushare as ts
import pandas as pd
import matplotlib.pyplot as plt
# 初始化Tushare API
pro = ts.pro_api()
# 获取美国历年国债收益率曲线数据(日频)从2012年3月30日到2020年3月27日
df = pro.us_tycr(start_date='20120330', end_date='20200327')
第二部分:数据概览
让我们先来看一下获取到的美国历年国债利率数据的一些基本信息。
# 打印数据前几行
print(df.head())
数据样例:
date m1 m2 m3 m6 y1 y2 y3 y5 y7 y10 y20 y30
0 20200327 0.01 0.03 0.03 0.02 0.11 0.25 0.30 0.41 0.60 0.72 1.09 1.29
1 20200326 0.01 0.01 0.00 0.04 0.13 0.30 0.36 0.51 0.72 0.83 1.20 1.42
2 20200325 0.00 0.00 0.00 0.07 0.19 0.34 0.41 0.56 0.77 0.88 1.23 1.45
3 20200324 0.01 0.01 0.01 0.09 0.25 0.38 0.44 0.52 0.75 0.84 1.19 1.39
4 20200323 0.01 0.04 0.02 0.08 0.17 0.28 0.31 0.38 0.63 0.76 1.12 1.33
第三部分:数据分析
3.1 收益率曲线趋势分析
让我们通过折线图来深入分析美国历年国债收益率曲线的趋势。
# 将日期转换为日期格式
df['date'] = pd.to_datetime(df['date'], format='%Y%m%d')
# 绘制收益率曲线趋势图
plt.figure(figsize=(12, 6))
for column in df.columns[1:]:
plt.plot(df['date'], df[column], label=column)
plt.title('美国历年国债收益率曲线趋势分析')
plt.xlabel('日期') plt.ylabel('利率')
plt.legend()
plt.grid(True)
plt.show()
3.2 选择性分析
我们也可以选择性地分析感兴趣的期限,比如1月期和1年期。
# 绘制1月期和1年期利率趋势图
plt.figure(figsize=(12, 6))
plt.plot(df['date'], df['m1'], label='1月期') plt.plot(df['date'], df['y1'], label='1年期')
plt.title('美国历年国债1月期和1年期收益率趋势分析')
plt.xlabel('日期')
plt.ylabel('利率')
plt.legend()
plt.grid(True)
plt.show()
第四部分:总结
通过以上分析,我们可以清晰地看到美国历年国债收益率曲线在不同期限下的趋势。这有助于我们了解美国长短期债券市场的变化。