Skip to content

Instantly share code, notes, and snippets.

@fnneves
Created May 11, 2021 16:36
Show Gist options
  • Save fnneves/6349448c823d8618c8dc98906fa1b2d6 to your computer and use it in GitHub Desktop.
Save fnneves/6349448c823d8618c8dc98906fa1b2d6 to your computer and use it in GitHub Desktop.
df = plotlydf_portfval[['date', 'ptf_growth', 'sp500_growth']].copy().round(3)
df['month'] = df.date.dt.month_name() # date column should be formatted as datetime
df['weekday'] = df.date.dt.day_name() # could be interesting to analyze weekday returns later
df['year'] = df.date.dt.year
df['weeknumber'] = df.date.dt.week # could be interesting to try instead of timeperiod
df['timeperiod'] = df.year.astype(str) + ' - ' + df.date.dt.month.astype(str).str.zfill(2)
# getting the percentage change for each period. the first period will be NaN
sp = df.reset_index().groupby('timeperiod').last()['sp500_growth'].pct_change()*100
ptf = df.reset_index().groupby('timeperiod').last()['ptf_growth'].pct_change()*100
plotlydf_growth_compare = pd.merge(ptf, sp, on='timeperiod').reset_index().round(3)
plotlydf_growth_compare.head()
# Plotly part
fig_growth2 = go.Figure()
fig_growth2.layout.template = CHART_THEME
fig_growth2.add_trace(go.Bar(
x=plotlydf_growth_compare.timeperiod,
y=plotlydf_growth_compare.ptf_growth.round(2),
name='Portfolio'
))
fig_growth2.add_trace(go.Bar(
x=plotlydf_growth_compare.timeperiod,
y=plotlydf_growth_compare.sp500_growth.round(2),
name='S&P 500',
))
fig_growth2.update_layout(barmode='group')
fig_growth2.layout.height=300
fig_growth2.update_layout(margin = dict(t=50, b=50, l=25, r=25))
fig_growth2.update_layout(
xaxis_tickfont_size=12,
yaxis=dict(
title='% change',
titlefont_size=13,
tickfont_size=12,
))
fig_growth2.update_layout(legend=dict(
yanchor="top",
y=0.99,
xanchor="right",
x=0.99))
fig_growth2.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment