|
| 1 | +import pandas as pd |
| 2 | +import plotly.graph_objects as go |
| 3 | +from plotly.subplots import make_subplots |
| 4 | + |
| 5 | + |
| 6 | +def plot_portfolio(portfolio, title, tac): |
| 7 | + """Main function to plot the portfolio performance and metrics.""" |
| 8 | + portfolio_return = _calculate_portfolio_return(portfolio["assets"]) |
| 9 | + annualized_return = _calculate_annualized_return(portfolio["assets"]) |
| 10 | + buy_and_hold_return = _calculate_annualized_return(portfolio["Close"]) |
| 11 | + trades = _calculate_trades(portfolio["shares"]) |
| 12 | + |
| 13 | + fig = make_subplots( |
| 14 | + rows=2, |
| 15 | + cols=1, |
| 16 | + shared_xaxes=True, |
| 17 | + row_heights=[0.70, 0.30], |
| 18 | + vertical_spacing=0.2, |
| 19 | + specs=[[{"type": "xy"}], [{"type": "domain"}]], |
| 20 | + ) |
| 21 | + |
| 22 | + for trace in _create_portfolio_traces(portfolio): |
| 23 | + fig.add_trace(trace, row=1, col=1) |
| 24 | + |
| 25 | + metrics_table = _create_metrics_table( |
| 26 | + portfolio_return, annualized_return, trades, buy_and_hold_return, tac |
| 27 | + ) |
| 28 | + fig.add_trace(metrics_table, row=2, col=1) |
| 29 | + |
| 30 | + fig.update_layout(_create_plot_layout(title)) |
| 31 | + |
| 32 | + return fig |
| 33 | + |
| 34 | + |
| 35 | +def _calculate_portfolio_return(stock): |
| 36 | + """Calculate the total return of the stock.""" |
| 37 | + initial_value = stock.iloc[0] |
| 38 | + final_value = stock.iloc[-1] |
| 39 | + total_return = (final_value / initial_value) - 1 |
| 40 | + portfolio_return = total_return * 100 |
| 41 | + return portfolio_return |
| 42 | + |
| 43 | + |
| 44 | +def _calculate_annualized_return(stock): |
| 45 | + """Calculate the annualized return for a stock.""" |
| 46 | + initial_value = stock.iloc[0] |
| 47 | + final_value = stock.iloc[-1] |
| 48 | + total_return = (final_value / initial_value) - 1 |
| 49 | + |
| 50 | + years = _calculate_years(stock) |
| 51 | + annualized_return = ((1 + total_return) ** (1 / years) - 1) * 100 |
| 52 | + |
| 53 | + return annualized_return |
| 54 | + |
| 55 | + |
| 56 | +def _calculate_years(stock): |
| 57 | + """Calculate the number of years between the first and last date of a stock.""" |
| 58 | + total_seconds = (stock.index[-1] - stock.index[0]).total_seconds() |
| 59 | + years = total_seconds / pd.Timedelta(days=365).total_seconds() |
| 60 | + return years |
| 61 | + |
| 62 | + |
| 63 | +def _calculate_trades(stock): |
| 64 | + """Calculate the number of trades by counting changes in the shares held.""" |
| 65 | + trades = stock.diff().ne(0).sum() |
| 66 | + return trades |
| 67 | + |
| 68 | + |
| 69 | +def _create_portfolio_traces(portfolio): |
| 70 | + """Create Plotly traces for cash and assets over time.""" |
| 71 | + traces = [ |
| 72 | + go.Scatter(x=portfolio.index, y=portfolio["cash"], mode="lines", name="Cash"), |
| 73 | + go.Scatter( |
| 74 | + x=portfolio.index, |
| 75 | + y=portfolio["assets"], |
| 76 | + mode="lines", |
| 77 | + name="Assets (Cash + Holdings)", |
| 78 | + ), |
| 79 | + ] |
| 80 | + return traces |
| 81 | + |
| 82 | + |
| 83 | +def _create_metrics_table( |
| 84 | + portfolio_return, annualized_return, trades, buy_and_hold_return, tac |
| 85 | +): |
| 86 | + """Create a Plotly table for the portfolio metrics.""" |
| 87 | + table = go.Table( |
| 88 | + header={ |
| 89 | + "values": ["Metric", "Value"], |
| 90 | + "fill_color": "lightgrey", |
| 91 | + "align": "center", |
| 92 | + }, |
| 93 | + cells={ |
| 94 | + "values": [ |
| 95 | + [ |
| 96 | + "Total Return", |
| 97 | + "Annualized Return", |
| 98 | + "Trades", |
| 99 | + "Assumed TAC", |
| 100 | + "Benchmark: Annualized Buy and Hold Return", |
| 101 | + ], |
| 102 | + [ |
| 103 | + f"{portfolio_return:.2f}%", |
| 104 | + f"{annualized_return:.2f}%", |
| 105 | + trades, |
| 106 | + f"{tac * 100:.2f}%", |
| 107 | + f"{buy_and_hold_return:.2f}%", |
| 108 | + ], |
| 109 | + ], |
| 110 | + "align": "left", |
| 111 | + }, |
| 112 | + ) |
| 113 | + return table |
| 114 | + |
| 115 | + |
| 116 | +def _create_plot_layout(title): |
| 117 | + """Create the layout configuration for the Plotly figure.""" |
| 118 | + layout = { |
| 119 | + "title": title, |
| 120 | + "xaxis_title": "Date", |
| 121 | + "yaxis_title": "Value", |
| 122 | + "legend_title": "Portfolio Components", |
| 123 | + "template": "plotly", |
| 124 | + } |
| 125 | + return layout |
0 commit comments