无论您是交易自己的小账户,还是管理数千亿美元的投资者资金,经济都很重要。经济可以帮助你知道应该采取哪种偏见——看涨还是看跌。
你如何形成一个观点?
- 购买分析师报告
- 阅读“专家”评论
- 做大多数人做的事,猜猜
这些选项听起来都不是很好。
不幸的是,小投资者没有经济学家团队来研究经济形势并提供指导。
今天,我将向您展示如何构建收益率曲线的动画图表以形成经济状况的视图。
收益率曲线是不同主要美国国债的收益率与其到期日的关系图。收益率曲线为投资者对经济的预测提供了重要的见解。“倒挂”收益率曲线已被证明可以可靠地预测经济衰退。
通常,长期国债的收益率高于短期国债。这是因为放贷时间越长风险越大。当收益率曲线倒挂时,长期国债的收益率低于短期国债的收益率。当市场预计美联储未来会因经济衰退而降低利率时,就会发生这种情况。
投资者使用倒挂的收益率曲线作为降低投资组合风险的标志。
您可以构建美国收益率曲线的动画图表来形成宏观经济状况的视图。
一切都无需支付任何费用。
导入和设置
首先导入 NumPy、Matplotlib和 OpenBB SDK。您可以使用OpenBB SDK获取圣路易斯联储数据门户 (FRED) 的收益率曲线数据。要使用数据,您需要免费的FRED API 密钥。
- importnumpyasnp
- import matplotlib.pyplot as plt
- import matplotlib.animation as animation
- from openbb_terminal.sdk import openbb
- font = {
- "family": "normal",
- "weight": "normal",
- "size": 12
- plt.rc('font', **font)
- openbb.keys.fred(
- key="inert_your_api_key_here",
- persist=True,
设置您想要用来构建收益率曲线的债券到期日。关于使用哪种期限有一些约定,但没有“绝对”的答案。关键是要在各个期限内获得良好的代表性。
- maturities = ['3m', '6m', '1y', '2y', '3y', '5y', '7y', '10y', '30y']
- data = openbb.economy.treasury(
- instruments=["nominal"],
- maturities=maturities,
- start_date="1985-01-01"
- data.columns = maturities
- data["inverted"] = data["30y"] < data["3m"]
使用OpenBB SDK一次性获取所有期限的利率数据。使用工具类型返回债券的票面利率(非通货膨胀调整)。如果 30 年期收益率低于 3 个月期收益率,则将收益率曲线标记为倒挂。有些人使用30年期和10年期,或者10年期和3个月期。根据您的分析,使用对您有意义的数据。
nominal
构建可视化图表
使用 Matplotlib,您可以为图表制作动画。动画图表提供了一种可视化数据随时间变化的好方法。首先,设置绘图。此样板代码设置图形,创建刻度范围和标签,并设置轴标签。
- # Initialize figure
- fig = plt.figure()
- ax = fig.add_subplot(1, 1, 1)
- line, = ax.plot([], [])
- # Set the range of ticks
- ax.set_xlim(0, 7)
- ax.set_ylim(0, 20)
- # Set the tick locations
- ax.set_xticks(range(8))
- ax.set_yticks([2, 4, 6, 8, 10, 12, 14, 16, 18])
- # Set the axis labels
- ax.set_xticklabels(["1m","3m","6m","1y","5y","10y","20y","30y"])
- ax.set_yticklabels([2, 4, 6, 8, 10, 12, 14, 16, 18])
- # Foce the y-axis labels to the left
- ax.yaxis.set_label_position("left")
- ax.yaxis.tick_left()
- # Add the axis lables
- plt.ylabel("Yield (%)")
- plt.xlabel("Time to maturty")
接下来,构建动画功能。
- def init_func():
- line.set_data([], [])
- plt.title("U.S. Treasury Bond Yield Curve")
- return line
- def animate(i):
- x = range(0, len(maturities))
- y = data[maturities].iloc[i]
- dt_ = data.index[i].strftime("%Y-%m-%d")
- if data.inverted.iloc[i]:
- line.set_color("r")
- else:
- line.set_color("y")
- line.set_data(x, y)
- plt.title(f"U.S. Treasury Bond Yield Curve ({dt_})")
- return line,
- ani = animation.FuncAnimation(
- fig,
- animate,
- init_func=init_func,
- frames=len(data.index),
- interval=5,
- blit=True
第一个函数设置图表的初始状态。该函数抓取数据进行绘图,当收益率曲线反转时将曲线颜色更改为红色,并设置数据。然后,该函数将循环遍历每行数据、创建绘图并将其显示给您。
特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.