Hi everyone,
This will be my first post on the forum. I hope it is understandable.
I am trying to combine a bar chart of annual returns (bars) with weekly cumulated returns (continuous line) with the code below.
Any idea what I am doing wrong here as I am only getting the bar charts? I would it is linked to the x axis and the frequency but I do not know where to start.
Many thanks in advance for your help
Libraries:
import pandas as pd
import numpy as np
import plotly.graph_objs as go
Data:
# Dataframe of weekly cumulative returns
np.random.seed(0)
dates = pd.date_range(start='2017-12-31', end='2023-07-31', freq='W')
cumulative_returns = np.random.uniform(-0.15, 0.15, len(dates)).cumsum()
cumulative_returns = np.clip(cumulative_returns, -0.15, 0.15)
df_cumulative = pd.DataFrame({'Date': dates, 'Cumulative Return': cumulative_returns})
df_cumulative.set_index('Date', inplace=True)
# DataFrame of annual returns
annual_returns = {2018: -0.05, 2019: 0.10, 2020: 0.05, 2021: 0.10, 2022: -0.10, 2023: 0.05}
df_annual = pd.DataFrame.from_dict(annual_returns, orient='index', columns=['Annual Return'])
df_annual.index.name = 'Year'
Combined bar and scatter plots:
# Plotting
fig = go.Figure()
# Bar chart
fig.add_trace(go.Bar(
x=df_annual.index,
y=df_annual['Annual Return'],
name='Annual Performance',
))
# Scatter plot
fig.add_trace(go.Scatter(
x=df_cumulative.index,
y=df_cumulative['Cumulative Return'],
name='Cumulative Performance'
))
fig.update_layout(width=1000, height=500)
fig.show()
Output:
Output when removing the bar chart section of the code:
What I would like to achieve, a combination of both (non related data, for illustration):