matplotlib 美国国债收益率曲线

matplotlib US Treasury yield curve

我目前正在尝试构建一个包含每日美国国债利率的数据框。如您所见,pandas 自动设置列的格式以便它们按顺序排列,这显然是我不希望的。这是我的一些代码。我只需要做一个小例子来说明我遇到的问题。

import quandl
import matplotlib.pyplot as plt

One_Month = quandl.get('FRED/DGS1MO')

^^ 所有费率重复

Yield_Curve = pd.DataFrame({'1m': One_Month['Value'], '3m': Three_Month['Value'], '1yr': One_Year['Value']})
Yield_Curve.loc['2017-06-22'].plot()
plt.show()

Yield_Curve.tail()


             1m      1yr     3m
Date            
2017-06-16  0.85    1.21    1.03
2017-06-19  0.85    1.22    1.02
2017-06-20  0.88    1.22    1.01
2017-06-21  0.85    1.22    0.99
2017-06-22  0.80    1.22    0.96

正如我所说,我只向数据框添加了三个利率,但显然两年期、三年期和五年期利率也会导致问题。

我做了一些搜索并看到了这个 post:

虽然使用最后 post 中的代码显然有效,但我宁愿能够保留我当前的数据集(One_Month、Three_Month...)来做这是因为我也将它们用于其他分析。

问:有什么方法可以锁定列顺序吗?

感谢您的帮助!

如果你不想改变原来的列顺序,尽管你需要排序的列和财务符号,我想你应该像下面这样定制你自己的列顺序。

fi_col = df.columns.str.extract('(\d)(\D+)', expand=True).sort_values([1, 0]).reset_index(drop=True)
fi_col = fi_col[0] + fi_col[1]

print(df[fi_col])

              1m    3m   1yr
Date                        
2017-06-16  0.85  1.03  1.21
2017-06-19  0.85  1.02  1.22
2017-06-20  0.88  1.01  1.22
2017-06-21  0.85  0.99  1.22
2017-06-22  0.80  0.96  1.22

如果您要定义列顺序,可以使用 reindex_axis():

df = df.reindex_axis(labels=['1m', '3m', '1yr'], axis=1)

df
              1m    3m   1yr
Date                        
2017-06-16  0.85  1.03  1.21
2017-06-19  0.85  1.02  1.22
2017-06-20  0.88  1.01  1.22
2017-06-21  0.85  0.99  1.22
2017-06-22  0.80  0.96  1.22

使用 pandas-datareader 您可以将符号指定为一个列表。除了按照@Andrew L 的建议使用 reindex_axis 之外,您还可以只传递带有两个括号的有序列列表,请参见下面的最后一行,以指定列顺序。

from pandas_datareader.data import DataReader as dr
syms = ['DGS10', 'DGS5', 'DGS2', 'DGS1MO', 'DGS3MO']
yc = dr(syms, 'fred') # could specify start date with start param here
names = dict(zip(syms, ['10yr', '5yr', '2yr', '1m', '3m']))
yc = yc.rename(columns=names)
yc = yc[['1m', '3m', '2yr', '5yr', '10yr']]

print(yc)
              1m    3m   2yr   5yr  10yr
DATE                                    
2010-01-01   NaN   NaN   NaN   NaN   NaN
2010-01-04  0.05  0.08  1.09  2.65  3.85
2010-01-05  0.03  0.07  1.01  2.56  3.77
2010-01-06  0.03  0.06  1.01  2.60  3.85
2010-01-07  0.02  0.05  1.03  2.62  3.85
         ...   ...   ...   ...   ...
2017-06-16  0.85  1.03  1.32  1.75  2.16
2017-06-19  0.85  1.02  1.36  1.80  2.19
2017-06-20  0.88  1.01  1.36  1.77  2.16
2017-06-21  0.85  0.99  1.36  1.78  2.16
2017-06-22  0.80  0.96  1.34  1.76  2.15

yc.loc['2016-06-01'].plot(label='Jun 1')
yc.loc['2016-06-02'].plot(label='Jun 2')
plt.legend(loc=0)

您还可以直接从美国财政部的网站上提取所有历史汇率(每日更新):

from bs4 import BeautifulSoup
import requests
import pandas as pd

soup = BeautifulSoup(requests.get('https://data.treasury.gov/feed.svc/DailyTreasuryYieldCurveRateData').text,'lxml')
table = soup.find_all('m:properties')
tbondvalues = []
for i in table:
    tbondvalues.append([i.find('d:new_date').text[:10],i.find('d:bc_1month').text,i.find('d:bc_2month').text,i.find('d:bc_3month').text,i.find('d:bc_6month').text,i.find('d:bc_1year').text,i.find('d:bc_2year').text,i.find('d:bc_3year').text,i.find('d:bc_5year').text,i.find('d:bc_10year').text,i.find('d:bc_20year').text,i.find('d:bc_30year').text])
ustcurve = pd.DataFrame(tbondvalues,columns=['date','1m','2m','3m','6m','1y','2y','3y','5y','10y','20y','30y'])
ustcurve.iloc[:,1:] = ustcurve.iloc[:,1:].apply(pd.to_numeric)/100
ustcurve['date'] = pd.to_datetime(ustcurve['date'])