def view_kc( ohlc: pd.DataFrame, length: int = 20, scalar: float = 2, mamode: str = "ema", offset: int = 0, s_ticker: str = "", export: str = "", external_axes: Optional[List[plt.Axes]] = None, ): """View Keltner Channels Indicator Parameters ---------- ohlc : pd.DataFrame Dataframe of stock prices length : int Length of window mamode: str Type of filter offset : int Offset value s_ticker : str Ticker export : str Format to export data external_axes : Optional[List[plt.Axes]], optional External axes (2 axes are expected in the list), by default None """ df_ta = volatility_model.kc( ohlc["High"], ohlc["Low"], ohlc["Adj Close"], length, scalar, mamode, offset, ) plot_data = pd.merge(ohlc, df_ta, how="outer", left_index=True, right_index=True) plot_data = reindex_dates(plot_data) # This plot has 1 axis if external_axes is None: _, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) else: if len(external_axes) != 1: console.print("[red]Expected list of 1 axis item./n[/red]") return (ax, ) = external_axes ax.plot(plot_data.index, plot_data["Adj Close"].values) ax.plot( plot_data.index, plot_data[df_ta.columns[0]].values, linewidth=0.7, label="Upper", ) ax.plot(plot_data.index, plot_data[df_ta.columns[1]].values, linewidth=0.7, ls="--") ax.plot( plot_data.index, plot_data[df_ta.columns[2]].values, linewidth=0.7, label="Lower", ) ax.fill_between( plot_data.index, plot_data[df_ta.columns[0]].values, plot_data[df_ta.columns[2]].values, alpha=0.1, ) ax.set_title(f"{s_ticker} Keltner Channels") ax.set_xlim(plot_data.index[0], plot_data.index[-1]) ax.set_ylabel("Price") ax.legend([s_ticker, df_ta.columns[0], df_ta.columns[1], df_ta.columns[2]]) theme.style_primary_axis( ax, data_index=plot_data.index.to_list(), tick_labels=plot_data["date"].to_list(), ) if external_axes is None: theme.visualize_output() export_data( export, os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"), "kc", df_ta, )
def view_kc( s_ticker: str, s_interval: str, df_stock: pd.DataFrame, length: int, scalar: float, mamode: str, offset: int, export: str = "", ): """View Keltner Channels Indicator Parameters ---------- s_ticker : str Ticker s_interval : str Interval of data df_stock : pd.DataFrame Dataframe of stock prices length : int Length of window mamode: str Type of filter offset : int Offset value export : str Format to export data """ df_ta = volatility_model.kc(s_interval, df_stock, length, scalar, mamode, offset) fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) if s_interval == "1440min": ax.plot(df_stock.index, df_stock["Adj Close"].values, color="fuchsia") else: ax.plot(df_stock.index, df_stock["Close"].values, color="fuchsia") ax.plot(df_ta.index, df_ta.iloc[:, 0].values, "b", lw=1.5, label="upper") ax.plot(df_ta.index, df_ta.iloc[:, 1].values, "b", lw=1.5, ls="--") ax.plot(df_ta.index, df_ta.iloc[:, 2].values, "b", lw=1.5, label="lower") ax.set_title(f"{s_ticker} Keltner Channels") ax.set_xlim(df_stock.index[0], df_stock.index[-1]) ax.set_xlabel("Time") ax.set_ylabel("Price") ax.legend([s_ticker, df_ta.columns[0], df_ta.columns[1], df_ta.columns[2]]) ax.fill_between( df_ta.index, df_ta.iloc[:, 0].values, df_ta.iloc[:, 2].values, alpha=0.1, color="b", ) ax.grid(b=True, which="major", color="#666666", linestyle="-") if gtff.USE_ION: plt.ion() plt.gcf().autofmt_xdate() fig.tight_layout(pad=1) plt.legend() plt.show() print("") export_data( export, os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"), "kc", df_ta, )
async def kc_command(ctx, ticker="", length="20", scalar="2", mamode="sma", offset="0", start="", end=""): """Displays chart with keltner channel [Yahoo Finance]""" try: # Debug if cfg.DEBUG: # pylint: disable=logging-too-many-args logger.debug( "!stocks.ta.kc %s %s %s %s %s %s %s", ticker, length, scalar, mamode, offset, start, end, ) # Check for argument possible_ma = ["sma", "ema", "wma", "hma", "zlma"] if ticker == "": raise Exception("Stock ticker is required") if start == "": start = datetime.now() - timedelta(days=365) else: start = datetime.strptime(start, cfg.DATE_FORMAT) if end == "": end = datetime.now() else: end = datetime.strptime(end, cfg.DATE_FORMAT) if not length.lstrip("-").isnumeric(): raise Exception("Number has to be an integer") length = int(length) if not scalar.lstrip("-").isnumeric(): raise Exception("Number has to be an integer") scalar = float(scalar) if not offset.lstrip("-").isnumeric(): raise Exception("Number has to be an integer") offset = float(offset) if mamode not in possible_ma: raise Exception("Invalid ma entered") ticker = ticker.upper() df_stock = discordbot.helpers.load(ticker, start) if df_stock.empty: raise Exception("Stock ticker is invalid") # Retrieve Data df_stock = df_stock.loc[(df_stock.index >= start) & (df_stock.index < end)] df_ta = volatility_model.kc( df_stock["High"], df_stock["Low"], df_stock["Adj Close"], length, scalar, mamode, offset, ) # Output Data fig = go.Figure() fig.add_trace( go.Scatter( name="upper", x=df_ta.index, y=df_ta.iloc[:, 2].values, opacity=1, mode="lines", line_color="indigo", showlegend=False, ), ) fig.add_trace( go.Scatter( name="lower", x=df_ta.index, y=df_ta.iloc[:, 0].values, opacity=1, mode="lines", line_color="indigo", fill="tonexty", fillcolor="rgba(74, 0, 128, 0.2)", showlegend=False, ), ) fig.add_trace( go.Scatter( name="mid", x=df_ta.index, y=df_ta.iloc[:, 1].values, opacity=1, line=dict( width=1.5, dash="dash", ), ), ) fig.add_trace( go.Scatter( name=f"{ticker}", x=df_stock.index, y=df_stock["Adj Close"], line=dict(color="#fdc708", width=2), opacity=1, ), ) fig.update_layout( margin=dict(l=0, r=0, t=50, b=20), template=cfg.PLT_TA_STYLE_TEMPLATE, colorway=cfg.PLT_TA_COLORWAY, title=f"{ticker} Keltner Channels ({mamode.upper()})", title_x=0.5, yaxis_title="Stock Price ($)", xaxis_title="Time", yaxis=dict(fixedrange=False, ), xaxis=dict( rangeslider=dict(visible=False), type="date", ), dragmode="pan", legend=dict(yanchor="top", y=0.99, xanchor="left", x=0.01), ) config = dict({"scrollZoom": True}) imagefile = "ta_kc.png" # Check if interactive settings are enabled plt_link = "" if cfg.INTERACTIVE: html_ran = random.randint(69, 69420) fig.write_html(f"in/kc_{html_ran}.html", config=config) plt_link = f"[Interactive]({cfg.INTERACTIVE_URL}/kc_{html_ran}.html)" fig.update_layout( width=800, height=500, ) fig.write_image(imagefile) img = Image.open(imagefile) print(img.size) im_bg = Image.open(cfg.IMG_BG) h = img.height + 240 w = img.width + 520 # Paste fig onto background img and autocrop background img = img.resize((w, h), Image.ANTIALIAS) x1 = int(0.5 * im_bg.size[0]) - int(0.5 * img.size[0]) y1 = int(0.5 * im_bg.size[1]) - int(0.5 * img.size[1]) x2 = int(0.5 * im_bg.size[0]) + int(0.5 * img.size[0]) y2 = int(0.5 * im_bg.size[1]) + int(0.5 * img.size[1]) img = img.convert("RGB") im_bg.paste(img, box=(x1 - 5, y1, x2 - 5, y2)) im_bg.save(imagefile, "PNG", quality=100) image = Image.open(imagefile) image = autocrop_image(image, 0) image.save(imagefile, "PNG", quality=100) image = disnake.File(imagefile) print(f"Image {imagefile}") if cfg.DEBUG: logger.debug("Image: %s", imagefile) title = "Stocks: Keltner-Channel " + ticker embed = disnake.Embed(title=title, description=plt_link, colour=cfg.COLOR) embed.set_image(url=f"attachment://{imagefile}") embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) os.remove(imagefile) await ctx.send(embed=embed, file=image) except Exception as e: embed = disnake.Embed( title="ERROR Stocks: Keltner-Channel", colour=cfg.COLOR, description=e, ) embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) await ctx.send(embed=embed, delete_after=30.0)
def kc_command( ticker="", interval: int = 15, past_days: int = 0, length="20", scalar="2", ma_mode="sma", offset="0", start="", end="", extended_hours: bool = False, heikin_candles: bool = False, news: bool = False, ): """Displays chart with keltner channel [Yahoo Finance]""" # Debug if imps.DEBUG: # pylint: disable=logging-too-many-args logger.debug( "ta kc %s %s %s %s %s %s %s %s %s %s %s %s", ticker, interval, past_days, length, scalar, ma_mode, offset, start, end, extended_hours, heikin_candles, news, ) # Check for argument if not length.lstrip("-").isnumeric(): raise Exception("Number has to be an integer") length = int(length) if not scalar.lstrip("-").isnumeric(): raise Exception("Number has to be an integer") scalar = float(scalar) if not offset.lstrip("-").isnumeric(): raise Exception("Number has to be an integer") offset = float(offset) # Retrieve Data df_stock, start, end, bar_start = load_candle.stock_data( ticker=ticker, interval=interval, past_days=past_days, extended_hours=extended_hours, start=start, end=end, heikin_candles=heikin_candles, ) if df_stock.empty: raise Exception("No Data Found") df_ta = df_stock.loc[(df_stock.index >= start) & (df_stock.index < end)] if df_ta.empty: raise Exception("No Data Found") ta_data = volatility_model.kc( df_stock["High"], df_stock["Low"], df_stock["Adj Close"], length, scalar, ma_mode, offset, ) df_ta = df_ta.join(ta_data) # Output Data if interval != 1440: df_ta = df_ta.loc[(df_ta.index >= bar_start) & (df_ta.index < end)] df_ta = df_ta.fillna(0.0) plot = load_candle.candle_fig( df_ta, ticker, interval, extended_hours, news, bar=bar_start, int_bar=interval, shared_xaxes=True, vertical_spacing=0.07, ) title = f"<b>{plot['plt_title']} Keltner Channels ({ma_mode.upper()})</b>" fig = plot["fig"] idx = 6 if interval != 1440 else 11 fig.add_trace( go.Scatter( name="upper", x=df_ta.index, y=df_ta.iloc[:, (idx + 2)].values, opacity=1, mode="lines", line_color="indigo", showlegend=False, ), row=1, col=1, secondary_y=True, ) fig.add_trace( go.Scatter( name="lower", x=df_ta.index, y=df_ta.iloc[:, idx].values, opacity=1, mode="lines", line_color="indigo", fill="tonexty", fillcolor="rgba(74, 0, 128, 0.2)", showlegend=False, ), row=1, col=1, secondary_y=True, ) fig.add_trace( go.Scatter( name="mid", x=df_ta.index, y=df_ta.iloc[:, (idx + 1)].values, opacity=1, line=dict( width=1.5, dash="dash", ), showlegend=False, ), row=1, col=1, secondary_y=True, ) fig.update_layout( margin=dict(l=0, r=0, t=50, b=20), template=imps.PLT_TA_STYLE_TEMPLATE, colorway=imps.PLT_TA_COLORWAY, title=title, title_x=0.02, title_font_size=14, dragmode="pan", ) imagefile = "ta_kc.png" # Check if interactive settings are enabled plt_link = "" if imps.INTERACTIVE: plt_link = imps.inter_chart(fig, imagefile, callback=False) fig.update_layout( width=800, height=500, ) imagefile = imps.image_border(imagefile, fig=fig) return { "title": f"Stocks: Keltner-Channel {ticker.upper()}", "description": plt_link, "imagefile": imagefile, }
async def kc_command(ctx, ticker="", length="20", scalar="2", mamode="sma", offset="0", start="", end=""): """Displays chart with keltner channel [Yahoo Finance]""" try: # Debug if cfg.DEBUG: # pylint: disable=logging-too-many-args logger.debug( "!stocks.ta.kc %s %s %s %s %s %s %s", ticker, length, scalar, mamode, offset, start, end, ) # Check for argument possible_ma = ["sma", "ema", "wma", "hma", "zlma"] if ticker == "": raise Exception("Stock ticker is required") if start == "": start = datetime.now() - timedelta(days=365) else: start = datetime.strptime(start, cfg.DATE_FORMAT) if end == "": end = datetime.now() else: end = datetime.strptime(end, cfg.DATE_FORMAT) if not length.lstrip("-").isnumeric(): raise Exception("Number has to be an integer") length = int(length) if not scalar.lstrip("-").isnumeric(): raise Exception("Number has to be an integer") scalar = float(scalar) if not offset.lstrip("-").isnumeric(): raise Exception("Number has to be an integer") offset = float(offset) if mamode not in possible_ma: raise Exception("Invalid ma entered") ticker = ticker.upper() df_stock = discordbot.helpers.load(ticker, start) if df_stock.empty: raise Exception("Stock ticker is invalid") # Retrieve Data df_stock = df_stock.loc[(df_stock.index >= start) & (df_stock.index < end)] df_ta = volatility_model.kc( df_stock["High"], df_stock["Low"], df_stock["Adj Close"], length, scalar, mamode, offset, ) # Output Data fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) ax.plot(df_stock.index, df_stock["Adj Close"].values, color="fuchsia") ax.plot(df_ta.index, df_ta.iloc[:, 0].values, "b", lw=1.5, label="upper") ax.plot(df_ta.index, df_ta.iloc[:, 1].values, "b", lw=1.5, ls="--") ax.plot(df_ta.index, df_ta.iloc[:, 2].values, "b", lw=1.5, label="lower") ax.set_title(f"{ticker} Keltner Channels") ax.set_xlim(df_stock.index[0], df_stock.index[-1]) ax.set_xlabel("Time") ax.set_ylabel("Price") ax.legend( [ticker, df_ta.columns[0], df_ta.columns[1], df_ta.columns[2]]) ax.fill_between( df_ta.index, df_ta.iloc[:, 0].values, df_ta.iloc[:, 2].values, alpha=0.1, color="b", ) ax.grid(b=True, which="major", color="#666666", linestyle="-") plt.gcf().autofmt_xdate() fig.tight_layout(pad=1) plt.legend() plt.savefig("ta_kc.png") uploaded_image = gst_imgur.upload_image("ta_kc.png", title="something") image_link = uploaded_image.link if cfg.DEBUG: logger.debug("Image URL: %s", image_link) title = "Stocks: Keltner-Channel " + ticker embed = discord.Embed(title=title, colour=cfg.COLOR) embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) embed.set_image(url=image_link) os.remove("ta_kc.png") await ctx.send(embed=embed) except Exception as e: embed = discord.Embed( title="ERROR Stocks: Keltner-Channel", colour=cfg.COLOR, description=e, ) embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) await ctx.send(embed=embed)
def kc_command(ticker="", length="20", scalar="2", mamode="sma", offset="0", start="", end=""): """Displays chart with keltner channel [Yahoo Finance]""" # Debug if cfg.DEBUG: # pylint: disable=logging-too-many-args logger.debug( "ta-kc %s %s %s %s %s %s %s", ticker, length, scalar, mamode, offset, start, end, ) # Check for argument possible_ma = ["sma", "ema", "wma", "hma", "zlma"] if ticker == "": raise Exception("Stock ticker is required") if start == "": start = datetime.now() - timedelta(days=365) else: start = datetime.strptime(start, cfg.DATE_FORMAT) if end == "": end = datetime.now() else: end = datetime.strptime(end, cfg.DATE_FORMAT) if not length.lstrip("-").isnumeric(): raise Exception("Number has to be an integer") length = int(length) if not scalar.lstrip("-").isnumeric(): raise Exception("Number has to be an integer") scalar = float(scalar) if not offset.lstrip("-").isnumeric(): raise Exception("Number has to be an integer") offset = float(offset) if mamode not in possible_ma: raise Exception("Invalid ma entered") ticker = ticker.upper() df_stock = helpers.load(ticker, start) if df_stock.empty: raise Exception("Stock ticker is invalid") # Retrieve Data df_stock = df_stock.loc[(df_stock.index >= start) & (df_stock.index < end)] df_ta = volatility_model.kc( df_stock["High"], df_stock["Low"], df_stock["Adj Close"], length, scalar, mamode, offset, ) # Output Data fig = go.Figure() fig.add_trace( go.Scatter( name="upper", x=df_ta.index, y=df_ta.iloc[:, 2].values, opacity=1, mode="lines", line_color="indigo", showlegend=False, ), ) fig.add_trace( go.Scatter( name="lower", x=df_ta.index, y=df_ta.iloc[:, 0].values, opacity=1, mode="lines", line_color="indigo", fill="tonexty", fillcolor="rgba(74, 0, 128, 0.2)", showlegend=False, ), ) fig.add_trace( go.Scatter( name="mid", x=df_ta.index, y=df_ta.iloc[:, 1].values, opacity=1, line=dict( width=1.5, dash="dash", ), ), ) fig.add_trace( go.Scatter( name=f"{ticker}", x=df_stock.index, y=df_stock["Adj Close"], line=dict(color="#fdc708", width=2), opacity=1, ), ) fig.update_layout( margin=dict(l=0, r=0, t=50, b=20), template=cfg.PLT_TA_STYLE_TEMPLATE, colorway=cfg.PLT_TA_COLORWAY, title=f"{ticker} Keltner Channels ({mamode.upper()})", title_x=0.5, yaxis_title="Stock Price ($)", xaxis_title="Time", yaxis=dict(fixedrange=False, ), xaxis=dict( rangeslider=dict(visible=False), type="date", ), dragmode="pan", legend=dict(yanchor="top", y=0.99, xanchor="left", x=0.01), ) config = dict({"scrollZoom": True}) imagefile = "ta_kc.png" # Check if interactive settings are enabled plt_link = "" if cfg.INTERACTIVE: html_ran = helpers.uuid_get() fig.write_html(f"in/kc_{html_ran}.html", config=config) plt_link = f"[Interactive]({cfg.INTERACTIVE_URL}/kc_{html_ran}.html)" fig.update_layout( width=800, height=500, ) imagefile = helpers.image_border(imagefile, fig=fig) return { "title": f"Stocks: Keltner-Channel {ticker}", "description": plt_link, "imagefile": imagefile, }