Thx @backtrader for the guidance.
I have adapted the package monthly_returns to backtrader using backtraders TimeReturn
to create a heatmap of monthly returns. Maybe this will help somebody.
Do you know if pyfolio is going to be re-integrated in backtrader anytime soon? Thx for all your work!
I have only included the relevant parts (imports, adding analyzer, and then the code i adapted).
import matplotlib.pyplot as plt
import seaborn as sns
import collections
import pandas as pd
......
#add analyzer
cerebro.addanalyzer(bt.analyzers.TimeReturn, _name='myreturntme',timeframe=bt.TimeFrame.Months)
.....
#Get analyzer analysis
tmereturn = strat.analyzers.myreturntme.get_analysis()
....
# empty list for datetime index
lst_indx = []
# empty list for monthly retuns
lst_mnth_ret = []
#iterate through returns
for key, value in tmereturn.items():
lst_indx.append(key)
lst_mnth_ret.append(value)
#Create dataframe for returns
df_ret_mnth = pd.DataFrame(lst_mnth_ret, index=lst_indx)
#Change label of column
df_ret_mnth.columns = ['Returns']
#multiply returns by 100
df_ret_mnth['Returns'] = df_ret_mnth['Returns'] *100
#Add year month info
df_ret_mnth['Year'] = df_ret_mnth.index.strftime('%Y')
df_ret_mnth['Month'] = df_ret_mnth.index.strftime('%b')
# make pivot table
df_ret_mnth = df_ret_mnth.pivot('Year', 'Month', 'Returns').fillna(0)
df_ret_mnth = df_ret_mnth[['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']]
#Get Plot size
size = list(plt.gcf().get_size_inches())
figsize = (size[0], size[0] // 2)
plt.close()
#Create subplot
fig, ax = plt.subplots(figsize=figsize)
#create heatmap
ax = sns.heatmap(df_ret_mnth, ax=ax, annot=True,
annot_kws={"size": 10}, fmt="0.2f", linewidths=0.5,
square=False, cbar=True, cmap='RdYlGn')
ax.set_title('Monthly Returns (%)', fontsize=12, color='black', fontweight="bold")
fig.subplots_adjust(hspace=0)
plt.yticks(rotation=0)
plt.show()
plt.close()
Here is the result