def display_donchian( ohlc: pd.DataFrame, ticker: str = "", upper_length: int = 20, lower_length: int = 20, export: str = "", external_axes: Optional[List[plt.Axes]] = None, ): """Show donchian channels Parameters ---------- ohlc : pd.DataFrame Dataframe of stock prices ticker : str Ticker upper_length : int Length of window to calculate upper channel lower_length : int Length of window to calculate lower channel export : str Format of export file external_axes : Optional[List[plt.Axes]], optional External axes (1 axis is expected in the list), by default None """ df_ta = volatility_model.donchian(ohlc["High"], ohlc["Low"], upper_length, lower_length) 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"{ticker} donchian") ax.set_xlim(plot_data.index[0], plot_data.index[-1]) ax.set_ylabel("Price ($)") ax.legend([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"), "donchian", df_ta, )
async def donchian_command(ctx, ticker="", upper_length="25", lower_length="100", start="", end=""): """Displays chart with donchian channel [Yahoo Finance]""" try: # Debug if cfg.DEBUG: logger.debug( "!stocks.ta.donchian %s %s %s %s %s", ticker, upper_length, lower_length, start, end, ) # Check for argument 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 upper_length.lstrip("-").isnumeric(): raise Exception("Number has to be an integer") upper_length = float(upper_length) if not lower_length.lstrip("-").isnumeric(): raise Exception("Number has to be an integer") lower_length = float(lower_length) 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.donchian(df_stock["High"], df_stock["Low"], upper_length, lower_length) # Output Data fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) ax.plot(df_stock.index, df_stock["Adj Close"].values, color="k", lw=3) 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} donchian") 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_donchian.png") uploaded_image = gst_imgur.upload_image("ta_donchian.png", title="something") image_link = uploaded_image.link if cfg.DEBUG: logger.debug("Image URL: %s", image_link) title = "Stocks: Donchian-Channels " + 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_donchian.png") await ctx.send(embed=embed) except Exception as e: embed = discord.Embed( title="ERROR Stocks: Donchian-Channels", colour=cfg.COLOR, description=e, ) embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) await ctx.send(embed=embed)
def view_donchian( ticker: str, s_interval: str, df_stock: pd.DataFrame, upper_length: int, lower_length: int, export: str = "", ): """Show donchian channels Parameters ---------- ticker : str Ticker s_interval : str Interval of stock data df_stock : pd.DataFrame Dataframe of stock prices upper_length : int Length of window to calculate upper channel lower_length : int Length of window to calculate lower channel export : str Format of export file """ df_ta = volatility_model.donchian(df_stock, upper_length, lower_length) 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="k", lw=3) else: ax.plot(df_stock.index, df_stock["Close"].values, color="k", lw=3) 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} donchian") 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="-") 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"), "donchian", df_ta, )
def donchian_command(ticker="", upper_length="25", lower_length="100", start="", end=""): """Displays chart with donchian channel [Yahoo Finance]""" # Debug if cfg.DEBUG: logger.debug( "ta donchian %s %s %s %s %s", ticker, upper_length, lower_length, start, end, ) # Check for argument 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 upper_length.lstrip("-").isnumeric(): raise Exception("Number has to be an integer") upper_length = float(upper_length) if not lower_length.lstrip("-").isnumeric(): raise Exception("Number has to be an integer") lower_length = float(lower_length) ticker = ticker.upper() df_stock = 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.donchian(df_stock["High"], df_stock["Low"], upper_length, lower_length) df_ta = df_ta.fillna(0.0) # Output Data fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) ax.plot(df_stock.index, df_stock["Adj Close"].values, lw=3) ax.plot(df_ta.index, df_ta.iloc[:, 0].values, lw=1.5, label="upper") ax.plot(df_ta.index, df_ta.iloc[:, 1].values, lw=1.5, ls="--") ax.plot(df_ta.index, df_ta.iloc[:, 2].values, lw=1.5, label="lower") ax.set_title(f"{ticker} donchian") 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, ) ax.grid(b=True, which="major", color="#666666", linestyle="-") plt.gcf().autofmt_xdate() fig.tight_layout(pad=1) plt.legend() imagefile = "ta_donchian.png" dataBytesIO = io.BytesIO() plt.savefig(dataBytesIO) plt.close("all") dataBytesIO.seek(0) imagefile = image_border(imagefile, base64=dataBytesIO) return { "title": f"Stocks: Donchian-Channels {ticker}", "imagefile": imagefile, }