Analyzing Stocks vs. Bonds Performance with Python's .melt() and .query() Methods!

Analyzing Stocks vs. Bonds Performance with Python's .melt() and .query() Methods!

It is widespread knowledge that the price of bonds is inversely related to the price of stocks. Recently, I tackled an insightful exercise to confirm this relationship using Python. Here's a step-by-step breakdown of how I approached this analysis:

  1. Data Preparation: I started with a table of percent changes in the US 10-year treasury bond price in wide format, with separate columns for each year.
  2. Reshaping Data: I used the .melt() method to convert the wide format into a long format, making it easier to analyze.

bond_perc = ten_yr.melt(id_vars='metric', var_name='date', value_name='close')        

Filtering Data: I then filtered the melted data to select only the rows where metric equals close using the .query() method.

bond_perc_close = bond_perc.query('metric == "close"')        

Merging Data: Next, I merged this bond data with a table of the Dow Jones Industrial stock index price using an inner join.

dow_bond = pd.merge_ordered(dji, bond_perc_close, on='date', suffixes=('_dow', '_bond'), how='inner')        

Visualizing Data: Finally, I plotted the percent changes in stock and bond prices to visualize the inverse relationship.

dow_bond.plot(y=['close_dow', 'close_bond'], x='date', rot=90)
plt.show()        

要查看或添加评论,请登录

Naeem Shahzad的更多文章

社区洞察

其他会员也浏览了