def comp_plot(df): ''' merged is a merged file containing Index(['Bill Date', # 'Qty', 'Sale Count', 'state', 'positive', 'Daily Cases'], dtype ='object') ''' # Create figure with secondary y-axis df2 = df.groupby('Bill Date').agg({'Qty': 'sum', 'Pred': 'sum'}).reset_index() fig = _make_subplots(specs=[[{"secondary_y": False }]]) fig.add_trace( _go.Line(x=df2['Bill Date'], y=df2['Qty'], name="Actual Sales"), secondary_y=False, ) # Add traces fig.add_trace( _go.Line(x=df2['Bill Date'], y=df2['Pred'], name="Predictions"), secondary_y=False, ) # Add figure title fig.update_layout( title_text="Sales vs Prediction", plot_bgcolor='rgba(0,0,0,0)' ) # Set x-axis title fig.update_xaxes(title_text="Dates") # Set y-axes titles fig.update_yaxes(title_text="Sales Qty", secondary_y=False) fig.show()
def sales_plot(merged, over='Qty'): ''' merged is a merged file containing Index(['Bill Date', # 'Qty', 'Sale Count', 'state', 'positive', 'Daily Cases'], dtype ='object') ''' # Create figure with secondary y-axis fig = _make_subplots(specs=[[{"secondary_y": True}]]) fig.add_trace( _go.Bar(x=merged['Bill Date'], y=merged['Daily Cases'], name="COVID Evolution", opacity=0.50), secondary_y=True, ) # Add traces fig.add_trace( _go.Line(x=merged['Bill Date'], y=merged[over], name="Sales Qty"), secondary_y=False, ) # Add figure title fig.update_layout( title_text="COVID vs Sales", plot_bgcolor='rgba(0,0,0,0)' ) # Set x-axis title fig.update_xaxes(title_text="Dates") # Set y-axes titles fig.update_yaxes(title_text="Sales Qty", secondary_y=False) fig.update_yaxes(title_text="COVID Evolution", secondary_y=True) fig.show()
def make_subplots(*args, **kwargs) -> tp.BaseFigure: """Makes subplots and passes them to `FigureWidget`.""" return make_figure(_make_subplots(*args, **kwargs))
def make_subplots(*args, **kwargs): """Makes subplots and passes them to `FigureWidget`.""" return FigureWidget(_make_subplots(*args, **kwargs))
def chart_perf_summary(df, geometric=True, title=None): """ Function to plot the cumulative performance and drawdowns of multiple assets Parameters ---------- df : DataFrame | Series wide dataframe with a datetime index and assets as columns or a series with a datetime index for a univariate chart geometric : bool True to plot geometric returns, False to plot absolute title : str Title for plot >>> import risktools as rt >>> df = rt.data.open_data('dfwide') >>> df = df[['CL01', 'CL12', 'CL36']] >>> df = rt.returns(df, period_return=1) >>> rt.chart_perf_summary(df, title="Cummulative Returns and Drawdowns") """ df = df.copy() if geometric == True: ret = df.add(1).cumprod() else: ret = df.cumsum() dd = drawdowns(df, geometric=geometric) cols = DEFAULT_PLOTLY_COLORS fig = _make_subplots(rows=2, cols=1, subplot_titles=("Cummulative Returns", "Drawdowns")) for i, c in enumerate(ret.columns): fig.add_trace( go.Scatter( x=ret.index, y=ret[c], name=c, line=dict(width=2, color=cols[i]), legendgroup="a", ), row=1, col=1, ) for i, c in enumerate(dd.columns): fig.add_trace( go.Scatter( x=dd.index, y=dd[c], name=c, line=dict(width=2, color=cols[i]), legendgroup="b", showlegend=False, ), row=2, col=1, ) fig.update_layout(title_text=title) return fig
def chart_eia_sd(market, key, start_dt="2010-01-01", output="chart", **kwargs): """ Function for plotting and returning data from the EIA Supply & Demand Balances for refined oil products such as mogas, diesel, jet and resid. Parameters ---------- market : ['mogas', 'diesel', 'jet', 'resid'] Refined product type to build the S&D balance for key : str EIA API key start_dt : str | datetime Starting date for S&D balance data output : ['chart','data'] Output as a chart or return data as a dataframe, by default 'chart' Returns ------- pandas dataframe or a plotly figure object Examples -------- >>> import risktools as rt >>> fig = rt.chart_eia_sd('mogas', up['eia']) >>> fig.show() """ eia = data.open_data("tickers_eia") eia = eia[eia.sd_category == market] df = get_eia_df(eia.tick_eia.to_list(), key=key) df = df.merge(eia[["tick_eia", "category"]], left_on=["series_id"], right_on=["tick_eia"]).drop("tick_eia", axis=1) df.date = pd.to_datetime(df.date) df = df.set_index("date").sort_index() # create list of plotly figure objects using repeating calls to the # five_year_plot function to loop through later to create subplot figs = [] for c in df.category.unique(): tf = df.loc[df.category == c, "value"] figs.append(chart_five_year_plot(tf, title=c)) # calc shape of final subplot n = len(df.category.unique()) m = 2 n = _ceil(n / m) fig = _make_subplots( n, m, subplot_titles=(" ", " ", " ", " ", " ", " "), ) # Copy returns figures from five_year_plot to a single subplot figure a = 1 b = 1 for i, _ in enumerate(figs): for j, _ in enumerate(figs[i]["data"]): fig.add_trace(figs[i]["data"][j], row=a, col=b) fig["layout"]["annotations"][ (a - 1) * 2 + b - 1]["text"] = figs[i]["layout"]["title"]["text"] # copy xaxis nticks and tickformat to subplots so that it keeps that formatting. # if they don't exist, pass try: fig["layout"][f"xaxis{i+1}"]["nticks"] = figs[i]["layout"][ "xaxis"]["nticks"] fig["layout"][f"xaxis{i+1}"]["tickformat"] = figs[i]["layout"][ "xaxis"]["tickformat"] except: pass if b == m: b = 1 a += 1 else: b += 1 fig.update_layout(showlegend=False) # return figs if output == "chart": return fig else: return df