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:
- 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.
- 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()