<jupyter_start><jupyter_text>CPPI  The Limits of Diversification<jupyter_code>pwd
returns = load_industry_data('ind30_m_ew_rets.csv')/100
firms = load_industry_data('ind30_m_nfirms.csv')
sizes = load_industry_data('ind30_m_size.csv')
#Market Capitalization

market_cap = firms * sizes
market_cap.head()
total_market_cap= market_cap.sum(axis=1)
total_market_cap.plot()
#weight industries by Market cap every year
capitalization_weight = market_cap.divide(total_market_cap, axis='rows')
capitalization_weight.head()
## See how industry importance changes over time
capitalization_weight[['Fin','Steel']].plot()
# Plot the returns of the Cap-weighted Portfolio
total_market_return = (capitalization_weight*returns).sum(axis='columns')
total_market_return.plot()
# Compute the Drawdowns of the Cap-Weighted portfolio and show the variation in wealt
drawdowns = compute_drawdown(total_market_return, initial_wealth=1)
total_market_index = drawdowns.wealth
total_market_index.plot(figsize=(12, 6))
# Zoom into the 80s +
total_market_index["1980":].plot(figsize=(12, 6))
total_market_index["1980":].rolling(window=36).mean().plot()
tmi_tr36rets = total_market_return.rolling(window=36).aggregate(annualize_returns, 12)
tmi_tr36rets.plot(figsize=(12,6), label="Trailing 36 month return", legend=True)
total_market_return.plot(label="Returns", legend=True)<jupyter_output><empty_output><jupyter_text>Rolling Correlation<jupyter_code>import matplotlib.pyplot as plt

ts_corr = returns.rolling(window=36).corr()
ts_corr.index.names = ['date','industry']
ind_tr36corr = ts_corr.groupby(level='date').apply(lambda cormat: cormat.values.mean())
ind_tr36corr.plot(figsize=(12,6))
plt.title('Rolling Mean Correlation')
tmi_tr36rets.plot(label='Trailing 36-month Returns', figsize=(12,6), legend=True)
ind_tr36corr.plot(label='Trailing 36-month Correlations', figsize=(12,6), legend=True,
                 secondary_y=True)<jupyter_output><empty_output><jupyter_text>Moral of the Story: when market is down, correlations are increasing and vice versa<jupyter_code>#returns are negatively correlated to correlations
tmi_tr36rets.corr(ind_tr36corr)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1190365910143585, 'fraction_numerical': 0.03195924038906901, 'mean_word_length': 9.236966824644549, 'pattern_counts': {'":': 2, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '167667', 'license': 'MIT', 'n_tokens_mistral': 793, 'n_tokens_neox': 722, 'n_words': 133, 'path': 'notebooks/cppi.ipynb', 'repo_name': 'algorythmist/finance-toolbox', 'size': '2159'}