def _plot_txt_time(self, stats, ax=None, **kwargs): """ Outputs the statistics for various time frames. """ returns = stats['returns'] mly_ret = perf.aggregate_returns(returns, 'monthly') yly_ret = perf.aggregate_returns(returns, 'yearly') mly_pct = mly_ret[mly_ret >= 0].shape[0] / float(mly_ret.shape[0]) mly_avg_win_pct = np.mean(mly_ret[mly_ret >= 0]) mly_avg_loss_pct = np.mean(mly_ret[mly_ret < 0]) mly_max_win_pct = np.max(mly_ret) mly_max_loss_pct = np.min(mly_ret) yly_pct = yly_ret[yly_ret >= 0].shape[0] / float(yly_ret.shape[0]) yly_max_win_pct = np.max(yly_ret) yly_max_loss_pct = np.min(yly_ret) header = ["Performance", "Value"] rows = [["Winning Months %", "{:.0%}".format(mly_pct)], ["Average Winning Month %", "{:.2%}".format(mly_avg_win_pct)], ["Average Losing Month %", "{:.2%}".format(mly_avg_loss_pct)], ["Best Month %", "{:.2%}".format(mly_max_win_pct)], ["Worst Month %", "{:.2%}".format(mly_max_loss_pct)], ["Winning Years %", '{:.0%}'.format(yly_pct)], ["Best Year %", '{:.2%}'.format(yly_max_win_pct)], ["Worst Year %", '{:.2%}'.format(yly_max_loss_pct)]] table = (Table().add(header, rows).set_global_opts( title_opts=opts.ComponentTitleOpts(title="Time"))) return table
def _plot_yearly_returns(self, stats, ax=None, **kwargs): """ Plots a barplot of returns by year. """ def format_perc(x, pos): return '%.0f%%' % x returns = stats['returns'] if ax is None: ax = plt.gca() y_axis_formatter = FuncFormatter(format_perc) ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter)) ax.yaxis.grid(linestyle=':') yly_ret = perf.aggregate_returns(returns, 'yearly') * 100.0 yly_ret.plot(ax=ax, kind="bar") ax.set_title('Yearly Returns (%)', fontweight='bold') ax.set_ylabel('') ax.set_xlabel('') ax.set_xticklabels(ax.get_xticklabels(), rotation=45) ax.xaxis.grid(False) return ax
def _plot_monthly_returns(self, stats, ax=None, **kwargs): """ Plots a heatmap of the monthly returns. """ returns = stats['returns'] if ax is None: ax = plt.gca() monthly_ret = perf.aggregate_returns(returns, 'monthly') monthly_ret = monthly_ret.unstack() monthly_ret = np.round(monthly_ret, 3) monthly_ret.rename( columns={1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun', 7: 'Jul', 8: 'Aug', 9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dec'}, inplace=True ) sns.heatmap( monthly_ret.fillna(0) * 100.0, annot=True, fmt="0.1f", annot_kws={"size": 8}, alpha=1.0, center=0.0, cbar=False, cmap=cm.RdYlGn, ax=ax, **kwargs) ax.set_title('Monthly Returns (%)', fontweight='bold') ax.set_ylabel('') ax.set_yticklabels(ax.get_yticklabels(), rotation=0) ax.set_xlabel('') return ax
def _plot_yearly_returns(self, stats, ax=None, **kwargs): """ Plots a barplot of returns by year. """ def format_perc(x, pos): return '%.0f%%' % x returns = stats['returns'] if ax is None: ax = plt.gca() y_axis_formatter = FuncFormatter(format_perc) ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter)) ax.yaxis.grid(linestyle=':') yly_ret = perf.aggregate_returns(returns, 'yearly') * 100.0 yly_ret.plot(ax=ax, kind="bar") ax.set_title('Yearly Returns (%)', fontweight='bold') ax.set_ylabel('') ax.set_xlabel('') ax.set_xticklabels(ax.get_xticklabels(), rotation=45) ax.xaxis.grid(False) return ax
def _plot_monthly_returns(self, stats, ax=None, **kwargs): """ Plots a heatmap of the monthly returns. """ returns = stats['returns'] if ax is None: ax = plt.gca() monthly_ret = perf.aggregate_returns(returns, 'monthly') monthly_ret = monthly_ret.unstack() monthly_ret = np.round(monthly_ret, 3) monthly_ret.rename( columns={1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun', 7: 'Jul', 8: 'Aug', 9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dec'}, inplace=True ) sns.heatmap( monthly_ret.fillna(0) * 100.0, annot=True, fmt="0.1f", annot_kws={"size": 8}, alpha=1.0, center=0.0, cbar=False, cmap=cm.RdYlGn, ax=ax, **kwargs) ax.set_title('Monthly Returns (%)', fontweight='bold') ax.set_ylabel('') ax.set_yticklabels(ax.get_yticklabels(), rotation=0) ax.set_xlabel('') return ax
def _plot_monthly_returns(self, stats): """ Plots the monthly returns heatmap """ returns = stats['returns'] monthly_ret = perf.aggregate_returns(returns, 'monthly') monthly_ret = monthly_ret.unstack() monthly_ret = np.round(monthly_ret, 3) monthly_ret = monthly_ret.fillna(0) * 100 row_count = len(monthly_ret) month = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] values = [] for i in range(12): for j in range(row_count): v = monthly_ret.iloc[j, i] s = "%.3f" % v values.append([i, j, round(v, 3), s]) c = (HeatMap().add_xaxis(month).add_yaxis("", list( monthly_ret.index), values).set_global_opts( title_opts=opts.TitleOpts(title="Monthly Returns (%)"), visualmap_opts=opts.VisualMapOpts( min_=min(values, key=lambda x: x[2])[2], max_=max(values, key=lambda x: x[2])[2]), )) return c
def _calculate_monthly_aggregated_returns_hc(self, returns): """ Calculate the monthly aggregated returns in the format utilised by Highcharts. 0% -> 0.0, 100% -> 100.0 Parameters ---------- returns : `pd.Series` The Series of daily returns values. Returns ------- `list[list]` The list of list-based returns: [[month, year, return]] """ month_returns = perf.aggregate_returns(returns, 'monthly') data = [] years = month_returns.index.levels[0].tolist() years_range = range(0, len(years)) months_range = range(0, 12) for month in months_range: for year in years_range: try: data.append([ month, year, 100.0 * month_returns.loc[(years[year], month + 1)] ]) except KeyError: # Truncated year, so no data available pass return data
def _plot_monthly_returns(self, stats, ax=None, **kwargs): """ Plots a heatmap of the monthly returns. """ returns = stats['returns'] if ax is None: ax = plt.gca() # print(returns) # https://www.geeksforgeeks.org/pandas-groupby/ # https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html # http://www.datasciencemadesimple.com/reshape-using-stack-unstack-function-pandas-python/ # def cumulate_returns(x): # return np.exp(np.log(1 + x).cumsum())[-1] - 1 # rtn = returns.groupby([lambda x: x.year, lambda x: x.month]).apply(cumulate_returns) # print(rtn.unstack()) #print(rtn.groups) #print(rtn.first()) monthly_ret = perf.aggregate_returns(returns, 'monthly') monthly_ret = monthly_ret.unstack() monthly_ret = np.round(monthly_ret, 3) monthly_ret.rename(columns={ 1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun', 7: 'Jul', 8: 'Aug', 9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dec' }, inplace=True) #print(monthly_ret) sns.heatmap(monthly_ret.fillna(0) * 100.0, annot=True, fmt="0.1f", annot_kws={"size": 8}, alpha=1.0, center=0.0, cbar=False, cmap=cm.RdYlGn, ax=ax, **kwargs) ax.set_title('Monthly Returns (%)', fontweight='bold') ax.set_ylabel('') ax.set_yticklabels(ax.get_yticklabels(), rotation=0) ax.set_xlabel('') return ax
def _plot_yearly_returns(self, stats): """ Plot the barplot of returns by year """ returns = stats["returns"] yly_ret = perf.aggregate_returns(returns, 'yearly') * 100.0 yly_ret = yly_ret.map(lambda x: round(x, 3)) c = (Bar().add_xaxis(list(yly_ret.index)).add_yaxis( "", list(yly_ret)).set_global_opts(title_opts=opts.TitleOpts( title="Yearly Returns (%)"))) return c
def _calculate_yearly_aggregated_returns(self, returns): """ Calculate the yearly aggregated returns as a list of tuples, with the first entry being the year integer and the second entry the returns. 0% -> 0.0, 100% -> 1.0 Parameters ---------- returns : `pd.Series` The Series of daily returns values. Returns ------- `list[tuple]` The list of tuple-based returns: [(year, return)] """ year_returns = perf.aggregate_returns(returns, 'yearly') return list(zip(year_returns.index, year_returns))
def _calculate_monthly_aggregated_returns(self, returns): """ Calculate the monthly aggregated returns as a list of tuples, with the first entry a further tuple of (year, month) and the second entry the returns. 0% -> 0.0, 100% -> 1.0 Parameters ---------- returns : `pd.Series` The Series of daily returns values. Returns ------- `list[tuple]` The list of tuple-based returns: [((year, month), return)] """ month_returns = perf.aggregate_returns(returns, 'monthly') return list(zip(month_returns.index, month_returns))
def _plot_daily_returns(self, stats, ax=None, **kwargs): """ Plots a heatmap of the daily returns. """ returns = stats['returns'] if ax is None: ax = plt.gca() daily_ret = perf.aggregate_returns(returns, 'daily') daily_ret = daily_ret.unstack() daily_ret = np.round(daily_ret, 3) # daily_ret.rename( # columns={1: '1', 2: '2', 3: '3', 4: '4', # 5: '5', 6: '6', 7: '7', 8: '8', # 9: '9', 10: '10', 11: '11', 12: '12'}, # columns={1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', # 5: 'May', 6: 'Jun', 7: 'Jul', 8: 'Aug', # 9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dec'}, # inplace=True # ) sns.heatmap(daily_ret.fillna(0) * 100.0, annot=True, fmt="0.1f", annot_kws={"size": 8}, alpha=1.0, center=0.0, cbar=True, cmap=cm.RdYlGn_r, ax=ax, **kwargs) ax.set_title('Daily Returns (%)', fontweight='bold') ax.set_ylabel('') ax.set_yticklabels(ax.get_yticklabels(), rotation=0) ax.set_xlabel('') return ax
def _plot_txt_time(self, stats, ax=None, **kwargs): """ Outputs the statistics for various time frames. """ def format_perc(x, pos): return '%.0f%%' % x returns = stats['returns'] if ax is None: ax = plt.gca() y_axis_formatter = FuncFormatter(format_perc) ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter)) mly_ret = perf.aggregate_returns(returns, 'monthly') yly_ret = perf.aggregate_returns(returns, 'yearly') mly_pct = mly_ret[mly_ret >= 0].shape[0] / float(mly_ret.shape[0]) mly_avg_win_pct = np.mean(mly_ret[mly_ret >= 0]) mly_avg_loss_pct = np.mean(mly_ret[mly_ret < 0]) mly_max_win_pct = np.max(mly_ret) mly_max_loss_pct = np.min(mly_ret) yly_pct = yly_ret[yly_ret >= 0].shape[0] / float(yly_ret.shape[0]) yly_max_win_pct = np.max(yly_ret) yly_max_loss_pct = np.min(yly_ret) ax.text(0.5, 8.9, 'Winning Months %', fontsize=8) ax.text(9.5, 8.9, '{:.0%}'.format(mly_pct), fontsize=8, fontweight='bold', horizontalalignment='right') ax.text(0.5, 7.9, 'Average Winning Month %', fontsize=8) ax.text(9.5, 7.9, '{:.2%}'.format(mly_avg_win_pct), fontsize=8, fontweight='bold', color='red' if mly_avg_win_pct < 0 else 'green', horizontalalignment='right') ax.text(0.5, 6.9, 'Average Losing Month %', fontsize=8) ax.text(9.5, 6.9, '{:.2%}'.format(mly_avg_loss_pct), fontsize=8, fontweight='bold', color='red' if mly_avg_loss_pct < 0 else 'green', horizontalalignment='right') ax.text(0.5, 5.9, 'Best Month %', fontsize=8) ax.text(9.5, 5.9, '{:.2%}'.format(mly_max_win_pct), fontsize=8, fontweight='bold', color='red' if mly_max_win_pct < 0 else 'green', horizontalalignment='right') ax.text(0.5, 4.9, 'Worst Month %', fontsize=8) ax.text(9.5, 4.9, '{:.2%}'.format(mly_max_loss_pct), fontsize=8, fontweight='bold', color='red' if mly_max_loss_pct < 0 else 'green', horizontalalignment='right') ax.text(0.5, 3.9, 'Winning Years %', fontsize=8) ax.text(9.5, 3.9, '{:.0%}'.format(yly_pct), fontsize=8, fontweight='bold', horizontalalignment='right') ax.text(0.5, 2.9, 'Best Year %', fontsize=8) ax.text(9.5, 2.9, '{:.2%}'.format(yly_max_win_pct), fontsize=8, fontweight='bold', color='red' if yly_max_win_pct < 0 else 'green', horizontalalignment='right') ax.text(0.5, 1.9, 'Worst Year %', fontsize=8) ax.text(9.5, 1.9, '{:.2%}'.format(yly_max_loss_pct), fontsize=8, fontweight='bold', color='red' if yly_max_loss_pct < 0 else 'green', horizontalalignment='right') # ax.text(0.5, 0.9, 'Positive 12 Month Periods', fontsize=8) # ax.text(9.5, 0.9, num_trades, fontsize=8, fontweight='bold', horizontalalignment='right') ax.set_title('Time', fontweight='bold') ax.grid(False) ax.spines['top'].set_linewidth(2.0) ax.spines['bottom'].set_linewidth(2.0) ax.spines['right'].set_visible(False) ax.spines['left'].set_visible(False) ax.get_yaxis().set_visible(False) ax.get_xaxis().set_visible(False) ax.set_ylabel('') ax.set_xlabel('') ax.axis([0, 10, 0, 10]) return ax
def _plot_txt_time(self, stats, ax=None, **kwargs): """ Outputs the statistics for various time frames. """ def format_perc(x, pos): return '%.0f%%' % x returns = stats['returns'] if ax is None: ax = plt.gca() y_axis_formatter = FuncFormatter(format_perc) ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter)) mly_ret = perf.aggregate_returns(returns, 'monthly') yly_ret = perf.aggregate_returns(returns, 'yearly') mly_pct = mly_ret[mly_ret >= 0].shape[0] / float(mly_ret.shape[0]) mly_avg_win_pct = np.mean(mly_ret[mly_ret >= 0]) mly_avg_loss_pct = np.mean(mly_ret[mly_ret < 0]) mly_max_win_pct = np.max(mly_ret) mly_max_loss_pct = np.min(mly_ret) yly_pct = yly_ret[yly_ret >= 0].shape[0] / float(yly_ret.shape[0]) yly_max_win_pct = np.max(yly_ret) yly_max_loss_pct = np.min(yly_ret) ax.text(0.5, 8.9, 'Winning Months %', fontsize=8) ax.text(9.5, 8.9, '{:.0%}'.format(mly_pct), fontsize=8, fontweight='bold', horizontalalignment='right') ax.text(0.5, 7.9, 'Average Winning Month %', fontsize=8) ax.text(9.5, 7.9, '{:.2%}'.format(mly_avg_win_pct), fontsize=8, fontweight='bold', color='red' if mly_avg_win_pct < 0 else 'green', horizontalalignment='right') ax.text(0.5, 6.9, 'Average Losing Month %', fontsize=8) ax.text(9.5, 6.9, '{:.2%}'.format(mly_avg_loss_pct), fontsize=8, fontweight='bold', color='red' if mly_avg_loss_pct < 0 else 'green', horizontalalignment='right') ax.text(0.5, 5.9, 'Best Month %', fontsize=8) ax.text(9.5, 5.9, '{:.2%}'.format(mly_max_win_pct), fontsize=8, fontweight='bold', color='red' if mly_max_win_pct < 0 else 'green', horizontalalignment='right') ax.text(0.5, 4.9, 'Worst Month %', fontsize=8) ax.text(9.5, 4.9, '{:.2%}'.format(mly_max_loss_pct), fontsize=8, fontweight='bold', color='red' if mly_max_loss_pct < 0 else 'green', horizontalalignment='right') ax.text(0.5, 3.9, 'Winning Years %', fontsize=8) ax.text(9.5, 3.9, '{:.0%}'.format(yly_pct), fontsize=8, fontweight='bold', horizontalalignment='right') ax.text(0.5, 2.9, 'Best Year %', fontsize=8) ax.text(9.5, 2.9, '{:.2%}'.format(yly_max_win_pct), fontsize=8, fontweight='bold', color='red' if yly_max_win_pct < 0 else 'green', horizontalalignment='right') ax.text(0.5, 1.9, 'Worst Year %', fontsize=8) ax.text(9.5, 1.9, '{:.2%}'.format(yly_max_loss_pct), fontsize=8, fontweight='bold', color='red' if yly_max_loss_pct < 0 else 'green', horizontalalignment='right') # ax.text(0.5, 0.9, 'Positive 12 Month Periods', fontsize=8) # ax.text(9.5, 0.9, num_trades, fontsize=8, fontweight='bold', horizontalalignment='right') ax.set_title('Time', fontweight='bold') ax.grid(False) ax.spines['top'].set_linewidth(2.0) ax.spines['bottom'].set_linewidth(2.0) ax.spines['right'].set_visible(False) ax.spines['left'].set_visible(False) ax.get_yaxis().set_visible(False) ax.get_xaxis().set_visible(False) ax.set_ylabel('') ax.set_xlabel('') ax.axis([0, 10, 0, 10]) return ax