def pt_command(ticker: str = "", raw: bool = False, start=""): """Displays price targets [Business Insider]""" # Debug if imps.DEBUG: logger.debug("dd pt %s", ticker) # Check for argument if ticker == "": raise Exception("Stock ticker is required") if start == "": start = datetime.now() - timedelta(days=365) else: start = datetime.strptime(start, imps.DATE_FORMAT) if raw not in [True, False]: raise Exception("raw argument has to be true or false") df_analyst_data = business_insider_model.get_price_target_from_analysts(ticker) stock = imps.load(ticker, start) title = f"Stocks: [Business Insider] Price Targets {ticker}" if df_analyst_data.empty or stock.empty: raise Exception("Enter valid ticker") # Output Data if raw: df_analyst_data.sort_index(ascending=False) report = "```" + df_analyst_data.to_string() + "```" output = { "title": title, "description": report, } else: plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) if start: df_analyst_data = df_analyst_data[start:] plt.plot(stock.index, stock["Adj Close"].values, lw=3) plt.plot(df_analyst_data.groupby(by=["Date"]).mean()) plt.scatter(df_analyst_data.index, df_analyst_data["Price Target"], c="r", s=40) plt.legend(["Closing Price", "Average Price Target", "Price Target"]) plt.title(f"{ticker.upper()} (Time Series) and Price Target") plt.xlim(stock.index[0], stock.index[-1]) plt.xlabel("Time") plt.ylabel("Share Price") plt.grid(b=True, which="major", color="#666666", linestyle="-") imagefile = "ta_pt.png" dataBytesIO = io.BytesIO() plt.savefig(dataBytesIO) plt.close("all") dataBytesIO.seek(0) imagefile = imps.image_border(imagefile, base64=dataBytesIO) output = { "title": title, "imagefile": imagefile, } return output
def price_target_from_analysts( ticker: str, start: str, interval: str, stock: DataFrame, num: int, raw: bool, export: str = "", ): """Display analysts' price targets for a given stock. [Source: Business Insider] Parameters ---------- ticker : str Due diligence ticker symbol start : str Start date of the stock data interval : str Stock data interval stock : DataFrame Due diligence stock dataframe num : int Number of latest price targets from analysts to print raw : bool Display raw data only export : str Export dataframe data to csv,json,xlsx file """ df_analyst_data = business_insider_model.get_price_target_from_analysts( ticker) if raw: df_analyst_data.index = df_analyst_data.index.strftime("%d/%m/%Y") if gtff.USE_TABULATE_DF: print( tabulate( df_analyst_data.sort_index(ascending=False).head(num), headers=df_analyst_data.columns, floatfmt=".2f", showindex=True, tablefmt="fancy_grid", )) else: print(df_analyst_data.head(num).to_string()) else: plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) # Slice start of ratings if start: df_analyst_data = df_analyst_data[start:] # type: ignore if interval == "1440min": plt.plot(stock.index, stock["Adj Close"].values, lw=3) # Intraday else: plt.plot(stock.index, stock["Close"].values, lw=3) if start: plt.plot(df_analyst_data.groupby( by=["Date"]).mean()[start:]) # type: ignore else: plt.plot(df_analyst_data.groupby(by=["Date"]).mean()) plt.scatter(df_analyst_data.index, df_analyst_data["Price Target"], c="r", s=40) plt.legend(["Closing Price", "Average Price Target", "Price Target"]) plt.title(f"{ticker} (Time Series) and Price Target") plt.xlim(stock.index[0], stock.index[-1]) plt.xlabel("Time") plt.ylabel("Share Price") plt.grid(b=True, which="major", color="#666666", linestyle="-") if gtff.USE_ION: plt.ion() plt.gcf().autofmt_xdate() plt.show() print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "pt", df_analyst_data, )
def price_target_from_analysts( ticker: str, start: str, interval: str, stock: DataFrame, num: int, raw: bool, export: str = "", external_axes: Optional[List[plt.Axes]] = None, ): """Display analysts' price targets for a given stock. [Source: Business Insider] Parameters ---------- ticker : str Due diligence ticker symbol start : str Start date of the stock data interval : str Stock data interval stock : DataFrame Due diligence stock dataframe num : int Number of latest price targets from analysts to print raw : bool Display raw data only export : str Export dataframe data to csv,json,xlsx file external_axes : Optional[List[plt.Axes]], optional External axes (1 axis is expected in the list), by default None """ df_analyst_data = business_insider_model.get_price_target_from_analysts( ticker) if raw: df_analyst_data.index = df_analyst_data.index.strftime("%Y-%m-%d") print_rich_table( df_analyst_data.sort_index(ascending=False).head(num), headers=list(df_analyst_data.columns), show_index=True, title="Analyst Price Targets", ) else: # This plot has 1 axis if not external_axes: _, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) else: if len(external_axes) != 1: console.print("[red]Expected list of one axis item./n[/red]") return (ax, ) = external_axes # Slice start of ratings if start: df_analyst_data = df_analyst_data[start:] # type: ignore if interval == "1440min": ax.plot(stock.index, stock["Adj Close"].values) legend_price_label = "Adjusted closing price" # Intraday else: ax.plot(stock.index, stock["Close"].values) legend_price_label = "Closing price" if start: ax.plot(df_analyst_data.groupby( by=["Date"]).mean()[start:]) # type: ignore else: ax.plot(df_analyst_data.groupby(by=["Date"]).mean()) ax.scatter( df_analyst_data.index, df_analyst_data["Price Target"], color=theme.down_color, edgecolors=theme.up_color, zorder=2, ) ax.legend([legend_price_label, "Average Price Target", "Price Target"]) ax.set_title(f"{ticker} (Time Series) and Price Target") ax.set_xlim(stock.index[0], stock.index[-1]) ax.set_ylabel("Share Price") theme.style_primary_axis(ax) if not external_axes: theme.visualize_output() console.print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), "pt", df_analyst_data, )
async def pt_command(ctx, ticker="", raw="", start=""): """Displays price targets [Business Insider]""" try: # Debug if cfg.DEBUG: logger.debug("!stocks.dd.pt %s", ticker) # 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 raw in ["false", "False", "FALSE", ""]: raw = False if raw in ["true", "True", "TRUE"]: raw = True if raw not in [True, False]: raise Exception("raw argument has to be true or false") df_analyst_data = business_insider_model.get_price_target_from_analysts( ticker) stock = discordbot.helpers.load(ticker, start) if df_analyst_data.empty or stock.empty: raise Exception("Enter valid ticker") # Output Data if raw: df_analyst_data.sort_index(ascending=False) report = "´´´" + df_analyst_data.to_string() + "´´´" embed = discord.Embed( title="Stocks: [Business Insider] Price Targets", description=report, colour=cfg.COLOR, ).set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) ctx.send(embed=embed) else: plt.figure(dpi=PLOT_DPI) if start: df_analyst_data = df_analyst_data[start:] plt.plot(stock.index, stock["Adj Close"].values, lw=3) plt.plot(df_analyst_data.groupby(by=["Date"]).mean()) plt.scatter(df_analyst_data.index, df_analyst_data["Price Target"], c="r", s=40) plt.legend( ["Closing Price", "Average Price Target", "Price Target"]) plt.title(f"{ticker} (Time Series) and Price Target") plt.xlim(stock.index[0], stock.index[-1]) plt.xlabel("Time") plt.ylabel("Share Price") plt.grid(b=True, which="major", color="#666666", linestyle="-") plt.gcf().autofmt_xdate() plt.savefig("ta_pt.png") uploaded_image = gst_imgur.upload_image("ta_pt.png", title="something") image_link = uploaded_image.link if cfg.DEBUG: logger.debug("Image URL: %s", image_link) title = "Stocks: [Business Insider] Price Targets " + 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_pt.png") await ctx.send(embed=embed) except Exception as e: embed = discord.Embed( title="ERROR Stocks: [Business Insider] Price Targets", colour=cfg.COLOR, description=e, ) embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) await ctx.send(embed=embed)
def test_get_price_target_from_analysts(recorder): result_df = business_insider_model.get_price_target_from_analysts( ticker="TSLA") recorder.capture(result_df)
async def pt_command(ctx, ticker: str = "", raw: bool = False, start=""): """Displays price targets [Business Insider]""" # Debug if cfg.DEBUG: logger.debug("!stocks.dd.pt %s", ticker) # 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 raw not in [True, False]: raise Exception("raw argument has to be true or false") df_analyst_data = business_insider_model.get_price_target_from_analysts( ticker) stock = discordbot.helpers.load(ticker, start) print(df_analyst_data) if df_analyst_data.empty or stock.empty: raise Exception("Enter valid ticker") # Output Data if raw: df_analyst_data.sort_index(ascending=False) report = "```" + df_analyst_data.to_string() + "```" embed = disnake.Embed( title="Stocks: [Business Insider] Price Targets", description=report, colour=cfg.COLOR, ).set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) ctx.send(embed=embed) else: plt.style.use("seaborn") plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) if start: df_analyst_data = df_analyst_data[start:] plt.plot(stock.index, stock["Adj Close"].values, lw=3) plt.plot(df_analyst_data.groupby(by=["Date"]).mean()) plt.scatter(df_analyst_data.index, df_analyst_data["Price Target"], c="r", s=40) plt.legend(["Closing Price", "Average Price Target", "Price Target"]) plt.title(f"{ticker} (Time Series) and Price Target") plt.xlim(stock.index[0], stock.index[-1]) plt.xlabel("Time") plt.ylabel("Share Price") plt.grid(b=True, which="major", color="#666666", linestyle="-") plt.savefig("ta_pt.png") imagefile = "ta_pt.png" img = Image.open(imagefile) print(img.size) im_bg = Image.open(cfg.IMG_BG) h = img.height + 240 w = img.width + 520 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 = discordbot.helpers.autocrop_image(image, 0) image.save(imagefile, "PNG", quality=100) uploaded_image = gst_imgur.upload_image("ta_pt.png", title="something") image_link = uploaded_image.link if cfg.DEBUG: logger.debug("Image URL: %s", image_link) title = "Stocks: [Business Insider] Price Targets " + ticker embed = disnake.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_pt.png") await ctx.send(embed=embed)