%22%22%22Marimo%20notebook%20demonstrating%20the%20hierarchical%201%2FN%20portfolio%20allocation%20strategy.%0A%0AThis%20notebook%20implements%20a%20hierarchical%20version%20of%20the%201%2FN%20portfolio%20allocation%20strategy%2C%0Ainspired%20by%20Thomas%20Raffinot.%20It%20builds%20a%20dendrogram%20using%20the%20'ward'%20distance%20method%0Aand%20applies%20the%201%2FN%20strategy%20level%20by%20level%2C%20from%20the%20root%20to%20the%20leaves.%0A%22%22%22%0A%0A%23%20%2F%2F%2F%20script%0A%23%20requires-python%20%3D%20%22%3E%3D3.11%22%0A%23%20dependencies%20%3D%20%5B%0A%23%20%20%20%20%20%22marimo%3D%3D0.18.4%22%2C%0A%23%20%20%20%20%20%22plotly%22%2C%0A%23%20%20%20%20%20%22polars%22%2C%0A%23%20%20%20%20%20%22pyhrp%22%2C%0A%23%20%5D%0A%23%0A%23%20%5Btool.uv.sources%5D%0A%23%20pyhrp%20%3D%20%7B%20path%20%3D%20%22..%2F..%22%2C%20editable%3Dtrue%20%7D%0A%23%0A%23%20%2F%2F%2F%0A%0Aimport%20marimo%0A%0A__generated_with%20%3D%20%220.25.2%22%0Aapp%20%3D%20marimo.App()%0A%0Awith%20app.setup%3A%0A%20%20%20%20import%20marimo%20as%20mo%0A%20%20%20%20import%20polars%20as%20pl%0A%0A%20%20%20%20from%20pyhrp.hrp%20import%20build_tree%0A%0A%0A%40app.cell%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%201%20over%20N%20(the%20hierarchical%20version)%0A%0A%20%20%20%20Inspired%20by%20Thomas%20Raffinot%0A%0A%20%20%20%20-%20Compute%20a%20dendrogram%20using%20the%20'ward'%20distance%20method.%0A%20%20%20%20%20%20Do%20not%20compute%20a%202nd%20Dendrogram.%0A%20%20%20%20-%20Apply%20the%20methods%20level%20by%20level.%20Go%20from%20level%200%20(only%20the%20root)%2C%0A%20%20%20%20%20%20to%20level%201%20(left%20and%20right%20of%20the%20root)%2C%20to%20level%202%20(...)%0A%20%20%20%20-%20On%20level%20n%20evaluate%20the%20function%20f%20for%20all%20leaves%20for%20each%20node.%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_()%3A%0A%20%20%20%20from%20pyhrp.hrp%20import%20compute_corr%2C%20compute_cov%0A%0A%20%20%20%20_prices%20%3D%20pl.read_csv(str(mo.notebook_location()%20%2F%20%22public%22%20%2F%20%22stock_prices.csv%22))%0A%20%20%20%20returns%20%3D%20_prices.drop(_prices.columns%5B0%5D).select(pl.all().pct_change()).drop_nulls().fill_null(0.0)%0A%20%20%20%20cor%20%3D%20compute_corr(returns)%0A%20%20%20%20compute_cov(returns)%0A%20%20%20%20return%20(cor%2C)%0A%0A%0A%40app.cell%0Adef%20_(cor)%3A%0A%20%20%20%20dendrogram%20%3D%20build_tree(cor%2C%20method%3D%22ward%22)%0A%20%20%20%20dendrogram.plot().show()%0A%20%20%20%20return%20(dendrogram%2C)%0A%0A%0A%40app.cell%0Adef%20_(dendrogram)%3A%0A%20%20%20%20for%20level%2C%20portfolio%20in%20dendrogram.one_over_n()%3A%0A%20%20%20%20%20%20%20%20print(f%22Level%3A%20%7Blevel%7D%22)%0A%20%20%20%20%20%20%20%20portfolio.plot(names%3Ddendrogram.names).show()%0A%20%20%20%20return%0A%0A%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20app.run()%0A
f33ef36ad9dac2ea13cec2ec74f1d36b