diff --git a/discordbot/config_discordbot.py b/discordbot/config_discordbot.py index 2677e07757e..0762645d415 100644 --- a/discordbot/config_discordbot.py +++ b/discordbot/config_discordbot.py @@ -23,6 +23,7 @@ COMMAND_PREFIX = "!" DATE_FORMAT = "%Y-%m-%d" COLOR = discord.Color.from_rgb(0, 206, 154) MENU_TIMEOUT = 30 +DEBUG = True AUTHOR_NAME = "Gamestonk Terminal" AUTHOR_ICON_URL = ( diff --git a/discordbot/economy/currencies.py b/discordbot/economy/currencies.py index 97e835471a9..48d8b8047eb 100644 --- a/discordbot/economy/currencies.py +++ b/discordbot/economy/currencies.py @@ -4,35 +4,57 @@ import config_discordbot as cfg from gamestonk_terminal.economy import wsj_model -async def currencies_command(ctx, arg): - # Help - if arg == "-h" or arg == "help": - help_txt = "Currencies [Source: Wall St. Journal]\n" - embed = discord.Embed( - title="Economy: [WSJ] Currencies HELP", - description=help_txt, - colour=cfg.COLOR, - ) - embed.set_author( - name=cfg.AUTHOR_NAME, - icon_url=cfg.AUTHOR_ICON_URL, - ) +async def currencies_command(ctx, arg=""): + try: + # Debug + if cfg.DEBUG: + print(f"!stocks.economy.currencies {arg}") - await ctx.send(embed=embed) + # Help + if arg == "-h" or arg == "help": + help_txt = "Currencies [Source: Wall St. Journal]\n" + embed = discord.Embed( + title="Economy: [WSJ] Currencies HELP", + description=help_txt, + colour=cfg.COLOR, + ) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) - else: - df_data = wsj_model.global_currencies() - if df_data.empty: - df_data_str = "No currencies data available" else: - df_data_str = "```" + df_data.to_string(index=False) + "```" + df_data = wsj_model.global_currencies() + if df_data.empty: + df_data_str = "No currencies data available" + else: + df_data_str = "```" + df_data.to_string(index=False) + "```" - embed = discord.Embed( - title="Economy: [WSJ] Currencies", description=df_data_str, colour=cfg.COLOR - ) + embed = discord.Embed( + title="Economy: [WSJ] Currencies", + description=df_data_str, + colour=cfg.COLOR, + ) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + + await ctx.send(embed=embed) + + except Exception as e: + title = "INTERNAL ERROR" + embed = discord.Embed(title=title, colour=cfg.COLOR) embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) - + embed.set_description( + "Try updating the bot, make sure DEBUG is True in the config " + "and restart it.\nIf the error still occurs open a issue at: " + "https://github.com/GamestonkTerminal/GamestonkTerminal/issues" + f"\n{e}" + ) await ctx.send(embed=embed) + if cfg.DEBUG: + print(e) diff --git a/discordbot/economy/economy_menu.py b/discordbot/economy/economy_menu.py index fc69f9f36ea..f215d9a56da 100644 --- a/discordbot/economy/economy_menu.py +++ b/discordbot/economy/economy_menu.py @@ -58,6 +58,9 @@ class EconomyCommands(discord.ext.commands.Cog): @discord.ext.commands.command(name="economy") async def economy(self, ctx: discord.ext.commands.Context): + if cfg.DEBUG: + print("!economy") + text = ( "0️⃣ !economy.overview\n" "1️⃣ !economy.futures\n" @@ -91,23 +94,41 @@ class EconomyCommands(discord.ext.commands.Cog): "reaction_add", timeout=cfg.MENU_TIMEOUT, check=check ) if reaction.emoji == "0️⃣": + if cfg.DEBUG: + print("Reaction selected: 0") await overview_command(ctx) elif reaction.emoji == "1️⃣": + if cfg.DEBUG: + print("Reaction selected: 1") await futures_command(ctx) elif reaction.emoji == "2️⃣": + if cfg.DEBUG: + print("Reaction selected: 2") await usbonds_command(ctx) elif reaction.emoji == "3️⃣": + if cfg.DEBUG: + print("Reaction selected: 3") await glbonds_command(ctx) elif reaction.emoji == "4️⃣": + if cfg.DEBUG: + print("Reaction selected: 4") await indices_command(ctx) elif reaction.emoji == "5️⃣": + if cfg.DEBUG: + print("Reaction selected: 5") await currencies_command(ctx) elif reaction.emoji == "6️⃣": + if cfg.DEBUG: + print("Reaction selected: 6") await feargreed_command(ctx) elif reaction.emoji == "7️⃣": - await valuation_command(ctx, "") + if cfg.DEBUG: + print("Reaction selected: 7") + await valuation_command(ctx) elif reaction.emoji == "8️⃣": - await performance_command(ctx, "") + if cfg.DEBUG: + print("Reaction selected: 8") + await performance_command(ctx) # TODO: Make this work - may need to set different discord server configurations # await msg.remove_reaction(reaction.emoji, user) diff --git a/discordbot/economy/feargreed.py b/discordbot/economy/feargreed.py index fbab7545520..5c034d13082 100644 --- a/discordbot/economy/feargreed.py +++ b/discordbot/economy/feargreed.py @@ -8,71 +8,93 @@ from discordbot import gst_imgur from gamestonk_terminal.economy import cnn_view, cnn_model -async def feargreed_command(ctx, arg): - # Help - if arg == "-h" or arg == "help": - help_txt = """CNN Fear And Greed indicator or index. From Junk Bond Demand, Market Volatility, - Put and Call Options, Market Momentum Stock Price Strength, Stock Price Breadth, - Safe Heaven Demand, and Index. [Source: CNN Business]\n""" +async def feargreed_command(ctx, arg=""): + try: + # Debug + if cfg.DEBUG: + print(f"!stocks.economy.feargreed {arg}") - embed = discord.Embed( - title="Economy: [CNN] Fear Geed Index HELP", - description=help_txt, - colour=cfg.COLOR, - ) - embed.set_author( - name=cfg.AUTHOR_NAME, - icon_url=cfg.AUTHOR_ICON_URL, - ) + # Help + if arg == "-h" or arg == "help": + help_txt = """CNN Fear And Greed indicator or index. From Junk Bond Demand, Market Volatility, + Put and Call Options, Market Momentum Stock Price Strength, Stock Price Breadth, + Safe Heaven Demand, and Index. [Source: CNN Business]\n""" - await ctx.send(embed=embed) + embed = discord.Embed( + title="Economy: [CNN] Fear Geed Index HELP", + description=help_txt, + colour=cfg.COLOR, + ) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) - else: - plt.ion() - fig = plt.figure(figsize=[1, 1], dpi=10) + else: + plt.ion() + fig = plt.figure(figsize=[1, 1], dpi=10) - report, _ = cnn_model.get_feargreed_report("", fig) - cnn_view.fear_and_greed_index(indicator="", export="png") + report, _ = cnn_model.get_feargreed_report("", fig) + cnn_view.fear_and_greed_index(indicator="", export="png") - plt.close("all") + plt.close("all") - now = datetime.datetime.now() - image_path = os.path.join( - cfg.GST_PATH, - "exports", - "economy", - f"feargreed_{now.strftime('%Y%m%d_%H%M%S')}.png", - ) - - i = 0 - while not os.path.exists(image_path) and i < 10: - now -= datetime.timedelta(seconds=1) + now = datetime.datetime.now() image_path = os.path.join( cfg.GST_PATH, "exports", "economy", f"feargreed_{now.strftime('%Y%m%d_%H%M%S')}.png", ) - i += 1 - embed = discord.Embed( - title="Economy: [CNN] Fear Geed Index", description=report, colour=cfg.COLOR - ) + i = 0 + while not os.path.exists(image_path) and i < 10: + now -= datetime.timedelta(seconds=1) + image_path = os.path.join( + cfg.GST_PATH, + "exports", + "economy", + f"feargreed_{now.strftime('%Y%m%d_%H%M%S')}.png", + ) + i += 1 + + embed = discord.Embed( + title="Economy: [CNN] Fear Geed Index", + description=report, + colour=cfg.COLOR, + ) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + + if os.path.exists(image_path): + uploaded_image = gst_imgur.upload_image( + image_path, title="FearGreed Charts" + ) + embed.set_image(url=uploaded_image.link) + + else: + # report = "Error: The image could not be found" + print("Error with uploading the the image to Imgur.") + + plt.close("all") + + await ctx.send(embed=embed) + + except Exception as e: + title = "INTERNAL ERROR" + embed = discord.Embed(title=title, colour=cfg.COLOR) embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) - - if os.path.exists(image_path): - uploaded_image = gst_imgur.upload_image( - image_path, title="FearGreed Charts" - ) - embed.set_image(url=uploaded_image.link) - - else: - # report = "Error: The image could not be found" - print("Error with uploading the the image to Imgur.") - - plt.close("all") - + embed.set_description( + "Try updating the bot, make sure DEBUG is True in the config " + "and restart it.\nIf the error still occurs open a issue at: " + "https://github.com/GamestonkTerminal/GamestonkTerminal/issues" + f"\n{e}" + ) await ctx.send(embed=embed) + if cfg.DEBUG: + print(e) diff --git a/discordbot/economy/futures.py b/discordbot/economy/futures.py index d4cde1f2238..3f429e633cb 100644 --- a/discordbot/economy/futures.py +++ b/discordbot/economy/futures.py @@ -4,37 +4,57 @@ import config_discordbot as cfg from gamestonk_terminal.economy import wsj_model -async def futures_command(ctx, arg): - # Help - if arg == "-h" or arg == "help": - help_txt = "Futures/Commodities [Source: Wall St. Journal]\n" - embed = discord.Embed( - title="Economy: [WSJ] Futures/Commodities HELP", - description=help_txt, - colour=cfg.COLOR, - ) - embed.set_author( - name=cfg.AUTHOR_NAME, - icon_url=cfg.AUTHOR_ICON_URL, - ) +async def futures_command(ctx, arg=""): + try: + # Debug + if cfg.DEBUG: + print(f"!stocks.economy.feargreed {arg}") - await ctx.send(embed=embed) + # Help + if arg == "-h" or arg == "help": + help_txt = "Futures/Commodities [Source: Wall St. Journal]\n" + embed = discord.Embed( + title="Economy: [WSJ] Futures/Commodities HELP", + description=help_txt, + colour=cfg.COLOR, + ) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) - else: - df_data = wsj_model.top_commodities() - if df_data.empty: - df_data_str = "No futures/commodities data available" else: - df_data_str = "```" + df_data.to_string(index=False) + "```" + df_data = wsj_model.top_commodities() + if df_data.empty: + df_data_str = "No futures/commodities data available" + else: + df_data_str = "```" + df_data.to_string(index=False) + "```" - embed = discord.Embed( - title="Economy: [WSJ] Futures/Commodities", - description=df_data_str, - colour=cfg.COLOR, - ) + embed = discord.Embed( + title="Economy: [WSJ] Futures/Commodities", + description=df_data_str, + colour=cfg.COLOR, + ) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + + await ctx.send(embed=embed) + + except Exception as e: + title = "INTERNAL ERROR" + embed = discord.Embed(title=title, colour=cfg.COLOR) embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) - + embed.set_description( + "Try updating the bot, make sure DEBUG is True in the config " + "and restart it.\nIf the error still occurs open a issue at: " + "https://github.com/GamestonkTerminal/GamestonkTerminal/issues" + f"\n{e}" + ) await ctx.send(embed=embed) + if cfg.DEBUG: + print(e) diff --git a/discordbot/economy/glbonds.py b/discordbot/economy/glbonds.py index f2cace3b8dd..4d530526a3c 100644 --- a/discordbot/economy/glbonds.py +++ b/discordbot/economy/glbonds.py @@ -4,37 +4,56 @@ import config_discordbot as cfg from gamestonk_terminal.economy import wsj_model -async def glbonds_command(ctx, arg): - # Help - if arg == "-h" or arg == "help": - help_txt = "Global Bonds [Source: Wall St. Journal]\n" - embed = discord.Embed( - title="Economy: [WSJ] Global Bonds HELP", - description=help_txt, - colour=cfg.COLOR, - ) - embed.set_author( - name=cfg.AUTHOR_NAME, - icon_url=cfg.AUTHOR_ICON_URL, - ) +async def glbonds_command(ctx, arg=""): + try: + # Debug + if cfg.DEBUG: + print(f"!stocks.economy.glbonds {arg}") - await ctx.send(embed=embed) + # Help + if arg == "-h" or arg == "help": + help_txt = "Global Bonds [Source: Wall St. Journal]\n" + embed = discord.Embed( + title="Economy: [WSJ] Global Bonds HELP", + description=help_txt, + colour=cfg.COLOR, + ) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) - else: - df_data = wsj_model.global_bonds() - if df_data.empty: - df_data_str = "No global bonds data available" else: - df_data_str = "```" + df_data.to_string(index=False) + "```" + df_data = wsj_model.global_bonds() + if df_data.empty: + df_data_str = "No global bonds data available" + else: + df_data_str = "```" + df_data.to_string(index=False) + "```" - embed = discord.Embed( - title="Economy: [WSJ] Global Bonds", - description=df_data_str, - colour=cfg.COLOR, - ) + embed = discord.Embed( + title="Economy: [WSJ] Global Bonds", + description=df_data_str, + colour=cfg.COLOR, + ) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + + await ctx.send(embed=embed) + + except Exception as e: + title = "INTERNAL ERROR" + embed = discord.Embed(title=title, colour=cfg.COLOR) embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) - - await ctx.send(embed=embed) + embed.set_description( + "Try updating the bot, make sure DEBUG is True in the config " + "and restart it.\nIf the error still occurs open a issue at: " + "https://github.com/GamestonkTerminal/GamestonkTerminal/issues" + f"\n{e}" + ) + if cfg.DEBUG: + print(e) diff --git a/discordbot/economy/indices.py b/discordbot/economy/indices.py index 0018882065e..d2615a8f4a3 100644 --- a/discordbot/economy/indices.py +++ b/discordbot/economy/indices.py @@ -4,35 +4,57 @@ import config_discordbot as cfg from gamestonk_terminal.economy import wsj_model -async def indices_command(ctx, arg): - # Help - if arg == "-h" or arg == "help": - help_txt = "US Indices [Source: Wall St. Journal]\n" - embed = discord.Embed( - title="Economy: [WSJ] US Indices HELP", - description=help_txt, - colour=cfg.COLOR, - ) - embed.set_author( - name=cfg.AUTHOR_NAME, - icon_url=cfg.AUTHOR_ICON_URL, - ) +async def indices_command(ctx, arg=""): + try: + # Debug + if cfg.DEBUG: + print("!stocks.economy.indices {arg}") - await ctx.send(embed=embed) + # Help + if arg == "-h" or arg == "help": + help_txt = "US Indices [Source: Wall St. Journal]\n" + embed = discord.Embed( + title="Economy: [WSJ] US Indices HELP", + description=help_txt, + colour=cfg.COLOR, + ) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) - else: - df_data = wsj_model.us_indices() - if df_data.empty: - df_data_str = "No indices data available" else: - df_data_str = "```" + df_data.to_string(index=False) + "```" + df_data = wsj_model.us_indices() + if df_data.empty: + df_data_str = "No indices data available" + else: + df_data_str = "```" + df_data.to_string(index=False) + "```" - embed = discord.Embed( - title="Economy: [WSJ] US Indices", description=df_data_str, colour=cfg.COLOR - ) + embed = discord.Embed( + title="Economy: [WSJ] US Indices", + description=df_data_str, + colour=cfg.COLOR, + ) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + + await ctx.send(embed=embed) + + except Exception as e: + title = "INTERNAL ERROR" + embed = discord.Embed(title=title, colour=cfg.COLOR) embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) - + embed.set_description( + "Try updating the bot, make sure DEBUG is True in the config " + "and restart it.\nIf the error still occurs open a issue at: " + "https://github.com/GamestonkTerminal/GamestonkTerminal/issues" + f"\n{e}" + ) await ctx.send(embed=embed) + if cfg.DEBUG: + print(e) diff --git a/discordbot/economy/overview.py b/discordbot/economy/overview.py index 632bf21cf2d..a08ed3880b9 100644 --- a/discordbot/economy/overview.py +++ b/discordbot/economy/overview.py @@ -4,37 +4,57 @@ import config_discordbot as cfg from gamestonk_terminal.economy import wsj_model -async def overview_command(ctx, arg): - # Help - if arg == "-h" or arg == "help": - help_txt = "Market Overview [Source: Wall St. Journal]\n" - embed = discord.Embed( - title="Economy: [WSJ] Market Overview HELP", - description=help_txt, - colour=cfg.COLOR, - ) - embed.set_author( - name=cfg.AUTHOR_NAME, - icon_url=cfg.AUTHOR_ICON_URL, - ) +async def overview_command(ctx, arg=""): + try: + # Debug + if cfg.DEBUG: + print(f"!stocks.economy.overview {arg}") - await ctx.send(embed=embed) + # Help + if arg == "-h" or arg == "help": + help_txt = "Market Overview [Source: Wall St. Journal]\n" + embed = discord.Embed( + title="Economy: [WSJ] Market Overview HELP", + description=help_txt, + colour=cfg.COLOR, + ) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) - else: - df_data = wsj_model.market_overview() - if df_data.empty: - df_data_str = "No overview data available" else: - df_data_str = "```" + df_data.to_string(index=False) + "```" + df_data = wsj_model.market_overview() + if df_data.empty: + df_data_str = "No overview data available" + else: + df_data_str = "```" + df_data.to_string(index=False) + "```" - embed = discord.Embed( - title="Economy: [WSJ] Market Overview", - description=df_data_str, - colour=cfg.COLOR, - ) + embed = discord.Embed( + title="Economy: [WSJ] Market Overview", + description=df_data_str, + colour=cfg.COLOR, + ) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + + await ctx.send(embed=embed) + + except Exception as e: + title = "INTERNAL ERROR" + embed = discord.Embed(title=title, colour=cfg.COLOR) embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) - + embed.set_description( + "Try updating the bot, make sure DEBUG is True in the config " + "and restart it.\nIf the error still occurs open a issue at: " + "https://github.com/GamestonkTerminal/GamestonkTerminal/issues" + f"\n{e}" + ) await ctx.send(embed=embed) + if cfg.DEBUG: + print(e) diff --git a/discordbot/economy/performance.py b/discordbot/economy/performance.py index 4866b290520..06fcd92096e 100644 --- a/discordbot/economy/performance.py +++ b/discordbot/economy/performance.py @@ -5,7 +5,7 @@ from helpers import pagination from gamestonk_terminal.economy import finviz_model -async def performance_command(ctx, arg): +async def performance_command(ctx, arg="sector"): economy_group = { "sector": "Sector", "industry": "Industry", @@ -24,70 +24,106 @@ async def performance_command(ctx, arg): "capitalization": "Capitalization", } - # Help - if arg == "-h" or arg == "help": - help_txt = "Group performance [Source: Finviz]\n" + try: + # Debug + if cfg.DEBUG: + print(f"!stocks.economy.performance {arg}") - possible_args = "" - for k, v in economy_group.items(): - possible_args += f"\n{k}: {v}" + # Help + if arg == "-h" or arg == "help": + help_txt = "Group performance [Source: Finviz]\n" - help_txt += "\nPossible arguments:\n" - help_txt += " Groups to get data from. Default: sector\n" - help_txt += f"The choices are:{possible_args}" - embed = discord.Embed( - title="Economy: [Finviz] Performance HELP", - description=help_txt, - colour=cfg.COLOR, - ) - embed.set_author( - name=cfg.AUTHOR_NAME, - icon_url=cfg.AUTHOR_ICON_URL, - ) + possible_args = "" + for k, v in economy_group.items(): + possible_args += f"\n{k}: {v}" - await ctx.send(embed=embed) - - else: - # Select default - if not arg: - arg = "sector" - - # Parse argument - group = economy_group[arg] - - df_group = finviz_model.get_valuation_performance_data(group, "performance") - - future_column_name = df_group["Name"] - df_group = df_group.transpose() - df_group.columns = future_column_name - df_group.drop("Name") - columns = [] - - initial_str = "Page 0: Overview" - i = 1 - for col_name in df_group.columns.values: - initial_str += f"\nPage {i}: {col_name}" - i += 1 - - columns.append( - discord.Embed( - title=f"Economy: [Finviz] Performance {group}", - description=initial_str, + help_txt += "\nPossible arguments:\n" + help_txt += " Groups to get data from. Default: sector\n" + help_txt += f"The choices are:{possible_args}" + embed = discord.Embed( + title="Economy: [Finviz] Performance HELP", + description=help_txt, colour=cfg.COLOR, - ).set_author( + ) + embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) - ) - for column in df_group.columns.values: + + await ctx.send(embed=embed) + + else: + # Parse argument + try: + group = economy_group[arg] + except KeyError: + title = "ERROR Economy: [Finviz] Performance" + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + embed.set_description( + f"Entered group argument: {arg}" + "\nEnter a valid group argument, example: sector" + ) + await ctx.send(embed=embed) + if cfg.DEBUG: + print("ERROR: Bad group argument entered") + return + + df_group = finviz_model.get_valuation_performance_data(group, "performance") + + future_column_name = df_group["Name"] + df_group = df_group.transpose() + df_group.columns = future_column_name + df_group.drop("Name") + columns = [] + + initial_str = "Page 0: Overview" + i = 1 + for col_name in df_group.columns.values: + initial_str += f"\nPage {i}: {col_name}" + i += 1 + columns.append( discord.Embed( - description="```" + df_group[column].fillna("").to_string() + "```", + title=f"Economy: [Finviz] Performance {group}", + description=initial_str, colour=cfg.COLOR, ).set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) ) + for column in df_group.columns.values: + columns.append( + discord.Embed( + description="```" + + df_group[column].fillna("").to_string() + + "```", + colour=cfg.COLOR, + ).set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + ) - await pagination(columns, ctx) + await pagination(columns, ctx) + + except Exception as e: + title = "INTERNAL ERROR" + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + embed.set_description( + "Try updating the bot, make sure DEBUG is True in the config " + "and restart it.\nIf the error still occurs open a issue at: " + "https://github.com/GamestonkTerminal/GamestonkTerminal/issues" + f"\n{e}" + ) + await ctx.send(embed=embed) + if cfg.DEBUG: + print(e) diff --git a/discordbot/economy/usbonds.py b/discordbot/economy/usbonds.py index 731550b1de5..ddd4b68a29e 100644 --- a/discordbot/economy/usbonds.py +++ b/discordbot/economy/usbonds.py @@ -4,33 +4,59 @@ import config_discordbot as cfg from gamestonk_terminal.economy import wsj_model -async def usbonds_command(ctx, arg): - # Help - if arg == "-h" or arg == "help": - help_txt = "US Bonds [Source: Wall St. Journal]\n" - embed = discord.Embed( - title="Economy: [WSJ] US Bonds HELP", description=help_txt, colour=cfg.COLOR - ) - embed.set_author( - name=cfg.AUTHOR_NAME, - icon_url=cfg.AUTHOR_ICON_URL, - ) +async def usbonds_command(ctx, arg=""): + try: + # Debug + if cfg.DEBUG: + print(f"!stocks.economy.usbonds {arg}") - await ctx.send(embed=embed) + # Help + if arg == "-h" or arg == "help": + help_txt = "US Bonds [Source: Wall St. Journal]\n" + embed = discord.Embed( + title="Economy: [WSJ] US Bonds HELP", + description=help_txt, + colour=cfg.COLOR, + ) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + + await ctx.send(embed=embed) - else: - df_data = wsj_model.us_bonds() - if df_data.empty: - df_data_str = "No US bonds data available" else: - df_data_str = "```" + df_data.to_string(index=False) + "```" + df_data = wsj_model.us_bonds() + if df_data.empty: + df_data_str = "No US bonds data available" + else: + df_data_str = "```" + df_data.to_string(index=False) + "```" - embed = discord.Embed( - title="Economy: [WSJ] US Bonds", description=df_data_str, colour=cfg.COLOR - ) + embed = discord.Embed( + title="Economy: [WSJ] US Bonds", + description=df_data_str, + colour=cfg.COLOR, + ) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + + await ctx.send(embed=embed) + + except Exception as e: + title = "INTERNAL ERROR" + embed = discord.Embed(title=title, colour=cfg.COLOR) embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) - + embed.set_description( + "Try updating the bot, make sure DEBUG is True in the config " + "and restart it.\nIf the error still occurs open a issue at: " + "https://github.com/GamestonkTerminal/GamestonkTerminal/issues" + f"\n{e}" + ) await ctx.send(embed=embed) + if cfg.DEBUG: + print(e) diff --git a/discordbot/economy/valuation.py b/discordbot/economy/valuation.py index 8f374f2353e..32bb69b5e09 100644 --- a/discordbot/economy/valuation.py +++ b/discordbot/economy/valuation.py @@ -5,7 +5,7 @@ from helpers import pagination from gamestonk_terminal.economy import finviz_model -async def valuation_command(ctx, arg): +async def valuation_command(ctx, arg="sector"): economy_group = { "sector": "Sector", "industry": "Industry", @@ -24,70 +24,106 @@ async def valuation_command(ctx, arg): "capitalization": "Capitalization", } - # Help - if arg == "-h" or arg == "help": - help_txt = "Group valuation [Source: Finviz]\n" + try: + # Debug + if cfg.DEBUG: + print(f"!stocks.economy.performance {arg}") - possible_args = "" - for k, v in economy_group.items(): - possible_args += f"\n{k}: {v}" + # Help + if arg == "-h" or arg == "help": + help_txt = "Group valuation [Source: Finviz]\n" - help_txt += "\nPossible arguments:\n" - help_txt += " Groups to get data from. Default: sector\n" - help_txt += f"The choices are:{possible_args}" - embed = discord.Embed( - title="Economy: [Finviz] Valuation HELP", - description=help_txt, - colour=cfg.COLOR, - ) - embed.set_author( - name=cfg.AUTHOR_NAME, - icon_url=cfg.AUTHOR_ICON_URL, - ) + possible_args = "" + for k, v in economy_group.items(): + possible_args += f"\n{k}: {v}" - await ctx.send(embed=embed) - - else: - # Select default - if not arg: - arg = "sector" - - # Parse argument - group = economy_group[arg] - - df_group = finviz_model.get_valuation_performance_data(group, "valuation") - - future_column_name = df_group["Name"] - df_group = df_group.transpose() - df_group.columns = future_column_name - df_group.drop("Name") - columns = [] - - initial_str = "Page 0: Overview" - i = 1 - for col_name in df_group.columns.values: - initial_str += f"\nPage {i}: {col_name}" - i += 1 - - columns.append( - discord.Embed( - title=f"Economy: [Finviz] Valuation {group}", - description=initial_str, + help_txt += "\nPossible arguments:\n" + help_txt += " Groups to get data from. Default: sector\n" + help_txt += f"The choices are:{possible_args}" + embed = discord.Embed( + title="Economy: [Finviz] Valuation HELP", + description=help_txt, colour=cfg.COLOR, - ).set_author( + ) + embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) - ) - for column in df_group.columns.values: + + await ctx.send(embed=embed) + + else: + try: + # Parse argument + group = economy_group[arg] + except KeyError: + title = "ERROR Economy: [Finviz] Performance" + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + embed.set_description( + f"Entered group argument: {arg}" + "\nEnter a valid group argument, example: sector" + ) + await ctx.send(embed=embed) + if cfg.DEBUG: + print("ERROR: Bad group argument entered") + return + + df_group = finviz_model.get_valuation_performance_data(group, "valuation") + + future_column_name = df_group["Name"] + df_group = df_group.transpose() + df_group.columns = future_column_name + df_group.drop("Name") + columns = [] + + initial_str = "Page 0: Overview" + i = 1 + for col_name in df_group.columns.values: + initial_str += f"\nPage {i}: {col_name}" + i += 1 + columns.append( discord.Embed( - description="```" + df_group[column].fillna("").to_string() + "```", + title=f"Economy: [Finviz] Valuation {group}", + description=initial_str, colour=cfg.COLOR, ).set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) ) + for column in df_group.columns.values: + columns.append( + discord.Embed( + description="```" + + df_group[column].fillna("").to_string() + + "```", + colour=cfg.COLOR, + ).set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + ) - await pagination(columns, ctx) + await pagination(columns, ctx) + + except Exception as e: + title = "INTERNAL ERROR" + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + embed.set_description( + "Try updating the bot, make sure DEBUG is True in the config " + "and restart it.\nIf the error still occurs open a issue at: " + "https://github.com/GamestonkTerminal/GamestonkTerminal/issues" + f"\n{e}" + ) + await ctx.send(embed=embed) + if cfg.DEBUG: + print(e) diff --git a/discordbot/stocks/dark_pool_shorts/dpotc.py b/discordbot/stocks/dark_pool_shorts/dpotc.py index e0f62f5e69b..5c5b88a9143 100644 --- a/discordbot/stocks/dark_pool_shorts/dpotc.py +++ b/discordbot/stocks/dark_pool_shorts/dpotc.py @@ -9,110 +9,167 @@ from gamestonk_terminal.config_plot import PLOT_DPI from gamestonk_terminal.stocks.dark_pool_shorts import finra_model -async def dpotc_command(ctx, arg): - # Help - if arg == "-h" or arg == "help": - help_txt = "Display barchart of dark pool (ATS) and OTC (Non ATS) data. [Source: FINRA]\n" - help_txt += "\nPossible arguments:\n" - help_txt += " Stock ticker. REQUIRED!\n" - embed = discord.Embed( - title="Stocks: [FINRA] Dark Pools (ATS) vs OTC HELP", - description=help_txt, - colour=cfg.COLOR, - ) - embed.set_author( - name=cfg.AUTHOR_NAME, - icon_url=cfg.AUTHOR_ICON_URL, - ) +async def dpotc_command(ctx, arg=""): + try: + # Debug + if cfg.DEBUG: + print(f"!stocks.dps.dpotc {arg}") - await ctx.send(embed=embed) - - else: - # Parse argument - ticker = arg.upper() - - plt.ion() - - title = "Stocks: [FINRA] Dark Pools (ATS) vs OTC " + ticker - embed = discord.Embed(title=title, colour=cfg.COLOR) - embed.set_author( - name=cfg.AUTHOR_NAME, - icon_url=cfg.AUTHOR_ICON_URL, - ) - ats, otc = finra_model.getTickerFINRAdata(ticker) - - if ats.empty and otc.empty: - return embed.set_description("No data found.") - _, _ = plt.subplots(dpi=PLOT_DPI) - - plt.subplot(3, 1, (1, 2)) - if not ats.empty and not otc.empty: - plt.bar( - ats.index, - (ats["totalWeeklyShareQuantity"] + otc["totalWeeklyShareQuantity"]) - / 1_000_000, - color="tab:orange", + # Help + if arg == "-h" or arg == "help": + help_txt = "Display barchart of dark pool (ATS) and OTC (Non ATS) data. [Source: FINRA]\n" + help_txt += "\nPossible arguments:\n" + help_txt += " Stock ticker. REQUIRED!\n" + embed = discord.Embed( + title="Stocks: [FINRA] Dark Pools (ATS) vs OTC HELP", + description=help_txt, + colour=cfg.COLOR, ) - plt.bar( - otc.index, otc["totalWeeklyShareQuantity"] / 1_000_000, color="tab:blue" + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, ) - plt.legend(["ATS", "OTC"]) - elif not ats.empty: - plt.bar( - ats.index, - ats["totalWeeklyShareQuantity"] / 1_000_000, - color="tab:orange", + await ctx.send(embed=embed) + + else: + if arg == "": + title = "ERROR Stocks: [FINRA] Dark Pools (ATS) vs OTC" + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + embed.set_description( + "No ticker entered.\nEnter a valid ticker, example: GME" + ) + await ctx.send(embed=embed) + if cfg.DEBUG: + print("ERROR: No ticker entered") + return + + # Parse argument + ticker = arg.upper() + + plt.ion() + + title = "Stocks: [FINRA] Dark Pools (ATS) vs OTC " + ticker + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, ) - plt.legend(["ATS"]) - elif not otc.empty: - plt.bar( - otc.index, otc["totalWeeklyShareQuantity"] / 1_000_000, color="tab:blue" - ) - plt.legend(["OTC"]) + try: + ats, otc = finra_model.getTickerFINRAdata(ticker) + except Exception as e: + title = "ERROR Stocks: [FINRA] Dark Pools (ATS) vs OTC " + ticker + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + embed.set_description( + f"Ticker given: {arg}\nEnter a valid ticker, example: GME" + ) + await ctx.send(embed=embed) + if cfg.DEBUG: + print(f"POSSIBLE ERROR: Wrong ticker parameter entered\n{e}") + return - plt.ylabel("Total Weekly Shares [Million]") - plt.grid(b=True, which="major", color="#666666", linestyle="-", alpha=0.2) - plt.title(f"Dark Pools (ATS) vs OTC (Non-ATS) Data for {ticker}") + if ats.empty and otc.empty: + return embed.set_description("No data found.") + _, _ = plt.subplots(dpi=PLOT_DPI) - plt.subplot(313) - if not ats.empty: - plt.plot( - ats.index, - ats["totalWeeklyShareQuantity"] / ats["totalWeeklyTradeCount"], - color="tab:orange", - ) - plt.legend(["ATS"]) + plt.subplot(3, 1, (1, 2)) + if not ats.empty and not otc.empty: + plt.bar( + ats.index, + (ats["totalWeeklyShareQuantity"] + otc["totalWeeklyShareQuantity"]) + / 1_000_000, + color="tab:orange", + ) + plt.bar( + otc.index, + otc["totalWeeklyShareQuantity"] / 1_000_000, + color="tab:blue", + ) + plt.legend(["ATS", "OTC"]) - if not otc.empty: + elif not ats.empty: + plt.bar( + ats.index, + ats["totalWeeklyShareQuantity"] / 1_000_000, + color="tab:orange", + ) + plt.legend(["ATS"]) + + elif not otc.empty: + plt.bar( + otc.index, + otc["totalWeeklyShareQuantity"] / 1_000_000, + color="tab:blue", + ) + plt.legend(["OTC"]) + + plt.ylabel("Total Weekly Shares [Million]") + plt.grid(b=True, which="major", color="#666666", linestyle="-", alpha=0.2) + plt.title(f"Dark Pools (ATS) vs OTC (Non-ATS) Data for {ticker}") + + plt.subplot(313) + if not ats.empty: + plt.plot( + ats.index, + ats["totalWeeklyShareQuantity"] / ats["totalWeeklyTradeCount"], + color="tab:orange", + ) + plt.legend(["ATS"]) + + if not otc.empty: + plt.plot( + otc.index, + otc["totalWeeklyShareQuantity"] / otc["totalWeeklyTradeCount"], + color="tab:blue", + ) + plt.legend(["ATS", "OTC"]) + + else: plt.plot( otc.index, otc["totalWeeklyShareQuantity"] / otc["totalWeeklyTradeCount"], color="tab:blue", ) - plt.legend(["ATS", "OTC"]) + plt.legend(["OTC"]) - else: - plt.plot( - otc.index, - otc["totalWeeklyShareQuantity"] / otc["totalWeeklyTradeCount"], - color="tab:blue", - ) - plt.legend(["OTC"]) + plt.ylabel("Shares per Trade") + plt.grid(b=True, which="major", color="#666666", linestyle="-", alpha=0.2) + plt.gcf().autofmt_xdate() + plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%m/%d")) + plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=4)) + plt.xlabel("Weeks") + file_name = ticker + "_dpotc.png" + plt.savefig(file_name) + plt.close("all") + uploaded_image = gst_imgur.upload_image(file_name, title="something") + image_link = uploaded_image.link + embed.set_image(url=image_link) + os.remove(file_name) - plt.ylabel("Shares per Trade") - plt.grid(b=True, which="major", color="#666666", linestyle="-", alpha=0.2) - plt.gcf().autofmt_xdate() - plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%m/%d")) - plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=4)) - plt.xlabel("Weeks") - file_name = ticker + "_dpotc.png" - plt.savefig(file_name) - plt.close("all") - uploaded_image = gst_imgur.upload_image(file_name, title="something") - image_link = uploaded_image.link - embed.set_image(url=image_link) - os.remove(file_name) + await ctx.send(embed=embed) + except Exception as e: + title = "INTERNAL ERROR" + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + embed.set_description( + "Try updating the bot, make sure DEBUG is True in the config " + "and restart it.\nIf the error still occurs open a issue at: " + "https://github.com/GamestonkTerminal/GamestonkTerminal/issues" + f"\n{e}" + ) await ctx.send(embed=embed) + if cfg.DEBUG: + print(e) diff --git a/discordbot/stocks/dark_pool_shorts/dps_menu.py b/discordbot/stocks/dark_pool_shorts/dps_menu.py index ebbcf3ff598..9292e9c7cc1 100644 --- a/discordbot/stocks/dark_pool_shorts/dps_menu.py +++ b/discordbot/stocks/dark_pool_shorts/dps_menu.py @@ -53,6 +53,9 @@ class DarkPoolShortsCommands(discord.ext.commands.Cog): @discord.ext.commands.command(name="stocks.dps") async def dark_pool_shorts_menu(self, ctx: discord.ext.commands.Context, arg=""): + if cfg.DEBUG: + print("!stocks.dps") + text = ( "0️⃣ !stocks.dps.shorted \n" "1️⃣ !stocks.dps.hsi \n" @@ -96,20 +99,36 @@ class DarkPoolShortsCommands(discord.ext.commands.Cog): "reaction_add", timeout=cfg.MENU_TIMEOUT, check=check ) if reaction.emoji == "0️⃣": - await shorted_command(ctx, "") + if cfg.DEBUG: + print("Reaction selected: 0") + await shorted_command(ctx) elif reaction.emoji == "1️⃣": - await hsi_command(ctx, "") + if cfg.DEBUG: + print("Reaction selected: 1") + await hsi_command(ctx) elif reaction.emoji == "2️⃣": - await pos_command(ctx, "", "") + if cfg.DEBUG: + print("Reaction selected: 2") + await pos_command(ctx) elif reaction.emoji == "3️⃣": - await sidtc_command(ctx, "", "") + if cfg.DEBUG: + print("Reaction selected: 3") + await sidtc_command(ctx) elif reaction.emoji == "4️⃣": - await ftd_command(ctx, arg, "", "") + if cfg.DEBUG: + print("Reaction selected: 4") + await ftd_command(ctx, arg) elif reaction.emoji == "5️⃣": + if cfg.DEBUG: + print("Reaction selected: 5") await dpotc_command(ctx, arg) elif reaction.emoji == "6️⃣": + if cfg.DEBUG: + print("Reaction selected: 6") await spos_command(ctx, arg) elif reaction.emoji == "7️⃣": + if cfg.DEBUG: + print("Reaction selected: 7") await psi_command(ctx, arg) except asyncio.TimeoutError: diff --git a/discordbot/stocks/dark_pool_shorts/ftd.py b/discordbot/stocks/dark_pool_shorts/ftd.py index 069f49efe1f..28ef401dfe5 100644 --- a/discordbot/stocks/dark_pool_shorts/ftd.py +++ b/discordbot/stocks/dark_pool_shorts/ftd.py @@ -10,68 +10,152 @@ import helpers from gamestonk_terminal.stocks.dark_pool_shorts import sec_model -async def ftd_command(ctx, arg, arg2, arg3): - # Help - if arg == "-h" or arg == "help": - help_txt = "Display fails-to-deliver data for a given ticker. [Source: SEC]\n" - help_txt += "\nPossible arguments:\n" - help_txt += " Stock ticker. REQUIRED!\n" - help_txt += " Start of data. Default: 1 year ago\n" - help_txt += " End of data. Default: today\n" - embed = discord.Embed( - title="Stocks: [SEC] Failure-to-deliver HELP", - description=help_txt, - colour=cfg.COLOR, - ) - embed.set_author( - name=cfg.AUTHOR_NAME, - icon_url=cfg.AUTHOR_ICON_URL, - ) +async def ftd_command(ctx, arg="", arg2="", arg3=""): + try: + # Debug + if cfg.DEBUG: + print(f"!stocks.dps.ftd {arg} {arg2} {arg3}") + + # Help + if arg == "-h" or arg == "help": + help_txt = ( + "Display fails-to-deliver data for a given ticker. [Source: SEC]\n" + ) + help_txt += "\nPossible arguments:\n" + help_txt += " Stock ticker. REQUIRED!\n" + help_txt += " Start of data. Default: 1 year ago\n" + help_txt += " End of data. Default: today\n" + embed = discord.Embed( + title="Stocks: [SEC] Failure-to-deliver HELP", + description=help_txt, + colour=cfg.COLOR, + ) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + + else: + if arg == "": + title = "ERROR Stocks: [SEC] Failure-to-deliver" + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + embed.set_description( + "No ticker entered.\nEnter a valid ticker, example: GME" + ) + await ctx.send(embed=embed) + if cfg.DEBUG: + print("ERROR: No ticker entered") + return + + # Parse argument + ticker = arg.upper() + if arg2 == "": + start = datetime.now() - timedelta(days=365) + else: + try: + start = datetime.strptime(arg2, cfg.DATE_FORMAT) + except Exception as e: + title = "ERROR Stocks: [SEC] Failure-to-deliver" + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + embed.set_description( + f"Start Date given: {arg2}" + f"\nEnter a valid start date using the format: {cfg.DATE_FORMAT}" + ) + await ctx.send(embed=embed) + if cfg.DEBUG: + print(f"ERROR: Wrong start date parameter entered\n{e}") + return + if arg3 == "": + end = datetime.now() + else: + try: + end = datetime.strptime(arg3, cfg.DATE_FORMAT) + except Exception as e: + title = "ERROR Stocks: [SEC] Failure-to-deliver" + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + embed.set_description( + f"End Date given: {arg3}" + f"\nEnter a valid end date using the format: {cfg.DATE_FORMAT}" + ) + await ctx.send(embed=embed) + if cfg.DEBUG: + print(f"ERROR: Wrong end date parameter entered\n{e}") + return + + plt.ion() + try: + ftds_data = sec_model.get_fails_to_deliver(ticker, start, end, 0) + except Exception as e: + title = f"ERROR Stocks: [SEC] Failure-to-deliver {ticker}" + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + embed.set_description( + f"Ticker given: {arg}" "\nEnter a valid ticker, example: GME" + ) + await ctx.send(embed=embed) + if cfg.DEBUG: + print(f"POSSIBLE ERROR: Wrong ticker parameter entered\n{e}") + return + plt.bar( + ftds_data["SETTLEMENT DATE"], + ftds_data["QUANTITY (FAILS)"] / 1000, + ) + plt.ylabel("Shares [K]") + plt.title(f"Fails-to-deliver Data for {ticker}") + plt.grid(b=True, which="major", color="#666666", linestyle="-", alpha=0.2) + plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%Y/%m/%d")) + plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=7)) + plt.gcf().autofmt_xdate() + plt.xlabel("Days") + _ = plt.gca().twinx() + stock = helpers.load(ticker, start) + stock_ftd = stock[stock.index > start] + stock_ftd = stock_ftd[stock_ftd.index < end] + plt.plot(stock_ftd.index, stock_ftd["Adj Close"], color="tab:orange") + plt.ylabel("Share Price [$]") + plt.savefig("dps_ftd.png") + plt.close("all") + uploaded_image = gst_imgur.upload_image("dps_ftd.png", title="something") + image_link = uploaded_image.link + title = "Stocks: [SEC] Failure-to-deliver " + 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("dps_ftd.png") await ctx.send(embed=embed) - else: - # Parse argument - ticker = arg.upper() - if arg2 == "": - start = datetime.now() - timedelta(days=365) - else: - start = datetime.strptime(arg2, cfg.DATE_FORMAT) - if arg3 == "": - end = datetime.now() - else: - end = datetime.strptime(arg3, cfg.DATE_FORMAT) - - plt.ion() - ftds_data = sec_model.get_fails_to_deliver(ticker, start, end, 0) - plt.bar( - ftds_data["SETTLEMENT DATE"], - ftds_data["QUANTITY (FAILS)"] / 1000, - ) - plt.ylabel("Shares [K]") - plt.title(f"Fails-to-deliver Data for {ticker}") - plt.grid(b=True, which="major", color="#666666", linestyle="-", alpha=0.2) - plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%Y/%m/%d")) - plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=7)) - plt.gcf().autofmt_xdate() - plt.xlabel("Days") - _ = plt.gca().twinx() - stock = helpers.load(ticker, start) - stock_ftd = stock[stock.index > start] - stock_ftd = stock_ftd[stock_ftd.index < end] - plt.plot(stock_ftd.index, stock_ftd["Adj Close"], color="tab:orange") - plt.ylabel("Share Price [$]") - plt.savefig("dps_ftd.png") - plt.close("all") - uploaded_image = gst_imgur.upload_image("dps_ftd.png", title="something") - image_link = uploaded_image.link - title = "Stocks: [SEC] Failure-to-deliver " + ticker + except Exception as e: + title = "INTERNAL ERROR" 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("dps_ftd.png") - + embed.set_description( + "Try updating the bot, make sure DEBUG is True in the config " + "and restart it.\nIf the error still occurs open a issue at: " + "https://github.com/GamestonkTerminal/GamestonkTerminal/issues" + f"\n{e}" + ) await ctx.send(embed=embed) + if cfg.DEBUG: + print(e) diff --git a/discordbot/stocks/dark_pool_shorts/hsi.py b/discordbot/stocks/dark_pool_shorts/hsi.py index 7005d242dd2..395630d9d3f 100644 --- a/discordbot/stocks/dark_pool_shorts/hsi.py +++ b/discordbot/stocks/dark_pool_shorts/hsi.py @@ -5,68 +5,101 @@ from helpers import pagination from gamestonk_terminal.stocks.dark_pool_shorts import shortinterest_model -async def hsi_command(ctx, arg): +async def hsi_command(ctx, arg="10"): + try: + # Debug + if cfg.DEBUG: + print(f"!stocks.dps.hsi {arg}") - # Help - if arg == "-h" or arg == "help": - help_txt = ( - "Display top high shorted interest stocks [Source: highshortinterest.com]\n" - ) - help_txt += "\nPossible arguments:\n" - help_txt += " Number of stocks to display. Default: 10" - embed = discord.Embed( - title="Stocks: [highshortinterest.com] Top High Short Interest HELP", - description=help_txt, - colour=cfg.COLOR, - ) - embed.set_author( - name=cfg.AUTHOR_NAME, - icon_url=cfg.AUTHOR_ICON_URL, - ) - - await ctx.send(embed=embed) - - else: - # Select default - if not arg: - arg = "10" - - # Parse argument - num = int(arg) - - df = shortinterest_model.get_high_short_interest() - df = df.iloc[1:].head(n=num) - - future_column_name = df["Ticker"] - df = df.transpose() - df.columns = future_column_name - df.drop("Ticker") - columns = [] - initial_str = "Page 0: Overview" - i = 1 - for column in df.columns.values: - initial_str = initial_str + "\nPage " + str(i) + ": " + column - i += 1 - columns.append( - discord.Embed( - title="Stocks: [highshortinterest.com] Top High Short Interest", - description=initial_str, + # Help + if arg == "-h" or arg == "help": + help_txt = "Display top high shorted interest stocks [Source: highshortinterest.com]\n" + help_txt += "\nPossible arguments:\n" + help_txt += " Number of stocks to display. Default: 10" + embed = discord.Embed( + title="Stocks: [highshortinterest.com] Top High Short Interest HELP", + description=help_txt, colour=cfg.COLOR, - ).set_author( + ) + embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) - ) - for column in df.columns.values: + + await ctx.send(embed=embed) + + else: + try: + # Parse argument + num = int(arg) + if num < 0: + raise ValueError("Number has to be above 0") + except ValueError: + title = "ERROR Stocks: [SEC] Failure-to-deliver" + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + embed.set_description( + "No number (int) entered." + "\nEnter a valid (positive) number, example: 10" + ) + await ctx.send(embed=embed) + if cfg.DEBUG: + print("ERROR: No (positive) int entered") + return + + df = shortinterest_model.get_high_short_interest() + df = df.iloc[1:].head(n=num) + + future_column_name = df["Ticker"] + df = df.transpose() + df.columns = future_column_name + df.drop("Ticker") + columns = [] + initial_str = "Page 0: Overview" + i = 1 + for column in df.columns.values: + initial_str = initial_str + "\nPage " + str(i) + ": " + column + i += 1 columns.append( discord.Embed( title="Stocks: [highshortinterest.com] Top High Short Interest", - description="```" + df[column].fillna("").to_string() + "```", + description=initial_str, colour=cfg.COLOR, ).set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) ) + for column in df.columns.values: + columns.append( + discord.Embed( + title="Stocks: [highshortinterest.com] Top High Short Interest", + description="```" + df[column].fillna("").to_string() + "```", + colour=cfg.COLOR, + ).set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + ) - await pagination(columns, ctx) + await pagination(columns, ctx) + + except Exception as e: + title = "INTERNAL ERROR" + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + embed.set_description( + "Try updating the bot, make sure DEBUG is True in the config " + "and restart it.\nIf the error still occurs open a issue at: " + "https://github.com/GamestonkTerminal/GamestonkTerminal/issues" + f"\n{e}" + ) + await ctx.send(embed=embed) + if cfg.DEBUG: + print(e) diff --git a/discordbot/stocks/dark_pool_shorts/pos.py b/discordbot/stocks/dark_pool_shorts/pos.py index 68db965bf58..497dac7306d 100644 --- a/discordbot/stocks/dark_pool_shorts/pos.py +++ b/discordbot/stocks/dark_pool_shorts/pos.py @@ -5,106 +5,157 @@ from helpers import pagination from gamestonk_terminal.stocks.dark_pool_shorts import stockgrid_model -async def pos_command(ctx, arg, arg2): +async def pos_command(ctx, arg="dpp_dollar", arg2="10"): + try: + # Debug + if cfg.DEBUG: + print(f"!stocks.dps.pos {arg} {arg2}") - # Help - if arg == "-h" or arg == "help": - dark_pool_sort = { - "sv": "Short Vol. (1M)", - "sv_pct": "Short Vol. %", - "nsv": "Net Short Vol. (1M)", - "nsv_dollar": "Net Short Vol. ($100M)", - "dpp": "DP Position (1M)", - "dpp_dollar": "DP Position ($1B)", - } + # Help + if arg == "-h" or arg == "help": + dark_pool_sort = { + "sv": "Short Vol. (1M)", + "sv_pct": "Short Vol. %", + "nsv": "Net Short Vol. (1M)", + "nsv_dollar": "Net Short Vol. ($100M)", + "dpp": "DP Position (1M)", + "dpp_dollar": "DP Position ($1B)", + } - help_txt = "Get dark pool short positions. [Source: Stockgrid]\n" + help_txt = "Get dark pool short positions. [Source: Stockgrid]\n" - possible_args = "" - for k, v in dark_pool_sort.items(): - possible_args += f"\n{k}: {v}" + possible_args = "" + for k, v in dark_pool_sort.items(): + possible_args += f"\n{k}: {v}" - help_txt += "\nPossible arguments:\n" - help_txt += " Field for which to sort by. Default: dpp_dollar\n" - help_txt += f"The choices are:{possible_args}\n" - help_txt += " Number of top tickers to show. Default: 10" + help_txt += "\nPossible arguments:\n" + help_txt += " Field for which to sort by. Default: dpp_dollar\n" + help_txt += f"The choices are:{possible_args}\n" + help_txt += " Number of top tickers to show. Default: 10" - embed = discord.Embed( - title="Stocks: [Stockgrid] Dark Pool Short Position HELP", - description=help_txt, - colour=cfg.COLOR, - ) - embed.set_author( - name=cfg.AUTHOR_NAME, - icon_url=cfg.AUTHOR_ICON_URL, - ) - - await ctx.send(embed=embed) - - else: - # Select default - if not arg: - arg = "dpp_dollar" - if not arg2: - arg2 = "10" - - # Parse argument - sort = arg - num = int(arg2) - - df = stockgrid_model.get_dark_pool_short_positions(sort, False) - df = df.iloc[:num] - dp_date = df["Date"].values[0] - df = df.drop(columns=["Date"]) - df["Net Short Volume $"] = df["Net Short Volume $"] / 100_000_000 - df["Short Volume"] = df["Short Volume"] / 1_000_000 - df["Net Short Volume"] = df["Net Short Volume"] / 1_000_000 - df["Short Volume %"] = df["Short Volume %"] * 100 - df["Dark Pools Position $"] = df["Dark Pools Position $"] / (1_000_000_000) - df["Dark Pools Position"] = df["Dark Pools Position"] / 1_000_000 - df.columns = [ - "Ticker", - "Short Vol. (1M)", - "Short Vol. %", - "Net Short Vol. (1M)", - "Net Short Vol. ($100M)", - "DP Position (1M)", - "DP Position ($1B)", - ] - future_column_name = df["Ticker"] - df = df.transpose() - df.columns = future_column_name - df.drop("Ticker") - columns = [] - initial_str = "Page 0: Overview" - i = 1 - for column in df.columns.values: - initial_str = initial_str + "\nPage " + str(i) + ": " + column - i += 1 - columns.append( - discord.Embed( - title="Stocks: [Stockgrid] Dark Pool Short Position", - description=initial_str, + embed = discord.Embed( + title="Stocks: [Stockgrid] Dark Pool Short Position HELP", + description=help_txt, colour=cfg.COLOR, - ).set_author( + ) + embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) - ) - for column in df.columns.values: + + await ctx.send(embed=embed) + + else: + # Parse argument + sort = arg + + try: + num = int(arg2) + if num < 0: + raise ValueError("Number has to be above 0") + except ValueError: + title = "ERROR Stocks: [Stockgrid] Dark Pool Short Position" + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + embed.set_description( + "No number (int) entered in the second argument." + "\nEnter a valid (positive) number, example: 10" + ) + await ctx.send(embed=embed) + if cfg.DEBUG: + print("ERROR: No (positive) int for second argument entered") + return + + try: + df = stockgrid_model.get_dark_pool_short_positions(sort, False) + except Exception as e: + title = "ERROR Stocks: [Stockgrid] Dark Pool Short Position" + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + embed.set_description( + f"Sorting parameter given: {arg}" + "\nEnter a valid ticker, example: dpp_value" + ) + await ctx.send(embed=embed) + if cfg.DEBUG: + print(f"POSSIBLE ERROR: Wrong sort parameter entered\n{e}") + return + + df = df.iloc[:num] + dp_date = df["Date"].values[0] + df = df.drop(columns=["Date"]) + df["Net Short Volume $"] = df["Net Short Volume $"] / 100_000_000 + df["Short Volume"] = df["Short Volume"] / 1_000_000 + df["Net Short Volume"] = df["Net Short Volume"] / 1_000_000 + df["Short Volume %"] = df["Short Volume %"] * 100 + df["Dark Pools Position $"] = df["Dark Pools Position $"] / (1_000_000_000) + df["Dark Pools Position"] = df["Dark Pools Position"] / 1_000_000 + df.columns = [ + "Ticker", + "Short Vol. (1M)", + "Short Vol. %", + "Net Short Vol. (1M)", + "Net Short Vol. ($100M)", + "DP Position (1M)", + "DP Position ($1B)", + ] + future_column_name = df["Ticker"] + df = df.transpose() + df.columns = future_column_name + df.drop("Ticker") + columns = [] + initial_str = "Page 0: Overview" + i = 1 + for column in df.columns.values: + initial_str = initial_str + "\nPage " + str(i) + ": " + column + i += 1 columns.append( discord.Embed( - title="High Short Interest", - description="```The following data corresponds to the date: " - + dp_date - + "\n\n" - + df[column].fillna("").to_string() - + "```", + title="Stocks: [Stockgrid] Dark Pool Short Position", + description=initial_str, colour=cfg.COLOR, ).set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) ) + for column in df.columns.values: + columns.append( + discord.Embed( + title="High Short Interest", + description="```The following data corresponds to the date: " + + dp_date + + "\n\n" + + df[column].fillna("").to_string() + + "```", + colour=cfg.COLOR, + ).set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + ) - await pagination(columns, ctx) + await pagination(columns, ctx) + + except Exception as e: + title = "INTERNAL ERROR" + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + embed.set_description( + "Try updating the bot, make sure DEBUG is True in the config " + "and restart it.\nIf the error still occurs open a issue at: " + "https://github.com/GamestonkTerminal/GamestonkTerminal/issues" + f"\n{e}" + ) + await ctx.send(embed=embed) + if cfg.DEBUG: + print(e) diff --git a/discordbot/stocks/dark_pool_shorts/psi.py b/discordbot/stocks/dark_pool_shorts/psi.py index 78ae54480bd..e59c779e8da 100644 --- a/discordbot/stocks/dark_pool_shorts/psi.py +++ b/discordbot/stocks/dark_pool_shorts/psi.py @@ -9,97 +9,149 @@ from gamestonk_terminal.config_plot import PLOT_DPI from gamestonk_terminal.stocks.dark_pool_shorts import stockgrid_model -async def psi_command(ctx, arg): - # Help - if arg == "-h" or arg == "help": - help_txt = "Plot price vs short interest volume. [Source: Stockgrid]\n" - help_txt += "\nPossible arguments:\n" - help_txt += " Stock ticker. REQUIRED!\n" - embed = discord.Embed( - title="Stocks: [Stockgrid] Price vs Short Interest Volume HELP", - description=help_txt, - colour=cfg.COLOR, - ) - embed.set_author( - name=cfg.AUTHOR_NAME, - icon_url=cfg.AUTHOR_ICON_URL, - ) +async def psi_command(ctx, arg=""): + try: + # Debug + if cfg.DEBUG: + print(f"!stocks.dps.psi {arg}") + + # Help + if arg == "-h" or arg == "help": + help_txt = "Plot price vs short interest volume. [Source: Stockgrid]\n" + help_txt += "\nPossible arguments:\n" + help_txt += " Stock ticker. REQUIRED!\n" + embed = discord.Embed( + title="Stocks: [Stockgrid] Price vs Short Interest Volume HELP", + description=help_txt, + colour=cfg.COLOR, + ) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + + else: + if arg == "": + title = "ERROR Stocks: [SEC] Failure-to-deliver" + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + embed.set_description( + "No ticker entered." "\nEnter a valid ticker, example: GME" + ) + await ctx.send(embed=embed) + if cfg.DEBUG: + print("ERROR: No ticker entered") + return + + # Parse argument + ticker = arg.upper() + + plt.ion() + title = "Stocks: [Stockgrid] Price vs Short Interest Volume " + ticker + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + + try: + df, prices = stockgrid_model.get_short_interest_volume(ticker) + except Exception as e: + title = ( + f"ERROR Stocks: [Stockgrid] Price vs Short Interest Volume {arg}" + ) + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + embed.set_description( + f"Ticker given: {arg}" "\nEnter a valid ticker, example: GME" + ) + await ctx.send(embed=embed) + if cfg.DEBUG: + print(f"POSSIBLE ERROR: Wrong ticker parameter entered\n{e}") + return + + _, axes = plt.subplots( + 2, + 1, + dpi=PLOT_DPI, + gridspec_kw={"height_ratios": [2, 1]}, + ) + + axes[0].bar( + df["date"], + df["total_volume"] / 1_000_000, + width=timedelta(days=1), + color="b", + alpha=0.4, + label="Total Volume", + ) + axes[0].bar( + df["date"], + df["short_volume"] / 1_000_000, + width=timedelta(days=1), + color="r", + alpha=0.4, + label="Short Volume", + ) + + axes[0].set_ylabel("Volume (1M)") + ax2 = axes[0].twinx() + ax2.plot( + df["date"].values, prices[len(prices) - len(df) :], c="k", label="Price" + ) + ax2.set_ylabel("Price ($)") + + lines, labels = axes[0].get_legend_handles_labels() + lines2, labels2 = ax2.get_legend_handles_labels() + ax2.legend(lines + lines2, labels + labels2, loc="upper left") + + axes[0].grid() + axes[0].ticklabel_format(style="plain", axis="y") + plt.title(f"Price vs Short Volume Interest for {ticker}") + plt.gcf().autofmt_xdate() + + axes[1].plot( + df["date"].values, + 100 * df["short_volume%"], + c="green", + label="Short Vol. %", + ) + + axes[1].set_ylabel("Short Vol. %") + + axes[1].grid(axis="y") + lines, labels = axes[1].get_legend_handles_labels() + axes[1].legend(lines, labels, loc="upper left") + axes[1].set_ylim([0, 100]) + file_name = ticker + "_psi.png" + plt.savefig(file_name) + plt.close("all") + uploaded_image = gst_imgur.upload_image(file_name, title="something") + image_link = uploaded_image.link + embed.set_image(url=image_link) + os.remove(file_name) await ctx.send(embed=embed) - else: - # Parse argument - ticker = arg.upper() - - plt.ion() - title = "Stocks: [Stockgrid] Price vs Short Interest Volume " + ticker + except Exception as e: + title = "INTERNAL ERROR" embed = discord.Embed(title=title, colour=cfg.COLOR) embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) - - df, prices = stockgrid_model.get_short_interest_volume(ticker) - - _, axes = plt.subplots( - 2, - 1, - dpi=PLOT_DPI, - gridspec_kw={"height_ratios": [2, 1]}, + embed.set_description( + "Try updating the bot, make sure DEBUG is True in the config " + "and restart it.\nIf the error still occurs open a issue at: " + "https://github.com/GamestonkTerminal/GamestonkTerminal/issues" + f"\n{e}" ) - - axes[0].bar( - df["date"], - df["total_volume"] / 1_000_000, - width=timedelta(days=1), - color="b", - alpha=0.4, - label="Total Volume", - ) - axes[0].bar( - df["date"], - df["short_volume"] / 1_000_000, - width=timedelta(days=1), - color="r", - alpha=0.4, - label="Short Volume", - ) - - axes[0].set_ylabel("Volume (1M)") - ax2 = axes[0].twinx() - ax2.plot( - df["date"].values, prices[len(prices) - len(df) :], c="k", label="Price" - ) - ax2.set_ylabel("Price ($)") - - lines, labels = axes[0].get_legend_handles_labels() - lines2, labels2 = ax2.get_legend_handles_labels() - ax2.legend(lines + lines2, labels + labels2, loc="upper left") - - axes[0].grid() - axes[0].ticklabel_format(style="plain", axis="y") - plt.title(f"Price vs Short Volume Interest for {ticker}") - plt.gcf().autofmt_xdate() - - axes[1].plot( - df["date"].values, - 100 * df["short_volume%"], - c="green", - label="Short Vol. %", - ) - - axes[1].set_ylabel("Short Vol. %") - - axes[1].grid(axis="y") - lines, labels = axes[1].get_legend_handles_labels() - axes[1].legend(lines, labels, loc="upper left") - axes[1].set_ylim([0, 100]) - file_name = ticker + "_psi.png" - plt.savefig(file_name) - plt.close("all") - uploaded_image = gst_imgur.upload_image(file_name, title="something") - image_link = uploaded_image.link - embed.set_image(url=image_link) - os.remove(file_name) - await ctx.send(embed=embed) + if cfg.DEBUG: + print(e) diff --git a/discordbot/stocks/dark_pool_shorts/shorted.py b/discordbot/stocks/dark_pool_shorts/shorted.py index 976f3adb0c0..510ff772057 100644 --- a/discordbot/stocks/dark_pool_shorts/shorted.py +++ b/discordbot/stocks/dark_pool_shorts/shorted.py @@ -5,68 +5,104 @@ from helpers import pagination from gamestonk_terminal.stocks.dark_pool_shorts import yahoofinance_model -async def shorted_command(ctx, arg): - # Help - if arg == "-h" or arg == "help": - help_txt = "Display most shorted stocks screener. [Source: Yahoo Finance]\n" - help_txt += "\nPossible arguments:\n" - help_txt += " Number of stocks to display. Default: 5" - embed = discord.Embed( - title="Stocks: [Yahoo Finance] Most Shorted HELP", - description=help_txt, - colour=cfg.COLOR, - ) - embed.set_author( - name=cfg.AUTHOR_NAME, - icon_url=cfg.AUTHOR_ICON_URL, - ) +async def shorted_command(ctx, arg="5"): + try: + # Debug + if cfg.DEBUG: + print(f"!stocks.dps.shorted {arg}") - await ctx.send(embed=embed) - - else: - # Select default - if not arg: - arg = "5" - - # Parse argument - num = int(arg) - - df = yahoofinance_model.get_most_shorted().head(num) - - df.dropna(how="all", axis=1, inplace=True) - df = df.replace(float("NaN"), "") - future_column_name = df["Symbol"] - df = df.transpose() - df.columns = future_column_name - df.drop("Symbol") - columns = [] - - initial_str = "Page 0: Overview" - i = 1 - - for col_name in df.columns.values: - initial_str += f"\nPage {i}: {col_name}" - i += 1 - - columns.append( - discord.Embed( - title="Stocks: [Yahoo Finance] Most Shorted", - description=initial_str, + # Help + if arg == "-h" or arg == "help": + help_txt = "Display most shorted stocks screener. [Source: Yahoo Finance]\n" + help_txt += "\nPossible arguments:\n" + help_txt += " Number of stocks to display. Default: 5" + embed = discord.Embed( + title="Stocks: [Yahoo Finance] Most Shorted HELP", + description=help_txt, colour=cfg.COLOR, - ).set_author( + ) + embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) - ) - for column in df.columns.values: + + await ctx.send(embed=embed) + + else: + try: + # Parse argument + num = int(arg) + if num < 0: + raise ValueError("Number has to be above 0") + except ValueError: + title = "ERROR Stocks: [Yahoo Finance] Most Shorted" + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + embed.set_description( + "No number (int) entered." + "\nEnter a valid (positive) number, example: 10" + ) + await ctx.send(embed=embed) + if cfg.DEBUG: + print("ERROR: No (positive) int entered") + return + + df = yahoofinance_model.get_most_shorted().head(num) + + df.dropna(how="all", axis=1, inplace=True) + df = df.replace(float("NaN"), "") + future_column_name = df["Symbol"] + df = df.transpose() + df.columns = future_column_name + df.drop("Symbol") + columns = [] + + initial_str = "Page 0: Overview" + i = 1 + + for col_name in df.columns.values: + initial_str += f"\nPage {i}: {col_name}" + i += 1 + columns.append( discord.Embed( - description="```" + df[column].fillna("").to_string() + "```", + title="Stocks: [Yahoo Finance] Most Shorted", + description=initial_str, colour=cfg.COLOR, ).set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) ) + for column in df.columns.values: + columns.append( + discord.Embed( + description="```" + df[column].fillna("").to_string() + "```", + colour=cfg.COLOR, + ).set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + ) - await pagination(columns, ctx) + await pagination(columns, ctx) + + except Exception as e: + title = "INTERNAL ERROR" + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + embed.set_description( + "Try updating the bot, make sure DEBUG is True in the config " + "and restart it.\nIf the error still occurs open a issue at: " + "https://github.com/GamestonkTerminal/GamestonkTerminal/issues" + f"\n{e}" + ) + await ctx.send(embed=embed) + if cfg.DEBUG: + print(e) diff --git a/discordbot/stocks/dark_pool_shorts/sidtc.py b/discordbot/stocks/dark_pool_shorts/sidtc.py index c34b823b26d..b33fce03105 100644 --- a/discordbot/stocks/dark_pool_shorts/sidtc.py +++ b/discordbot/stocks/dark_pool_shorts/sidtc.py @@ -5,93 +5,144 @@ from helpers import pagination from gamestonk_terminal.stocks.dark_pool_shorts import stockgrid_model -async def sidtc_command(ctx, arg, arg2): - # Help - if arg == "-h" or arg == "help": - dark_pool_sort = { - "float": "Float Short %", - "dtc": "Days to Cover", - "si": "Short Interest", - } +async def sidtc_command(ctx, arg="float", arg2="10"): + try: + # Debug + if cfg.DEBUG: + print(f"!stocks.dps.sidtc {arg} {arg2}") - help_txt = "Get short interest and days to cover. [Source: Stockgrid]\n" + # Help + if arg == "-h" or arg == "help": + dark_pool_sort = { + "float": "Float Short %", + "dtc": "Days to Cover", + "si": "Short Interest", + } - possible_args = "" - for k, v in dark_pool_sort.items(): - possible_args += f"\n{k}: {v}" + help_txt = "Get short interest and days to cover. [Source: Stockgrid]\n" - help_txt += "\nPossible arguments:\n" - help_txt += " Field for which to sort by. Default: float\n" - help_txt += f"The choices are:{possible_args}\n" - help_txt += " Number of top tickers to show. Default: 10" + possible_args = "" + for k, v in dark_pool_sort.items(): + possible_args += f"\n{k}: {v}" - embed = discord.Embed( - title="Stocks: [Stockgrid] Short Interest and Days to Cover HELP", - description=help_txt, - colour=cfg.COLOR, - ) - embed.set_author( - name=cfg.AUTHOR_NAME, - icon_url=cfg.AUTHOR_ICON_URL, - ) + help_txt += "\nPossible arguments:\n" + help_txt += " Field for which to sort by. Default: float\n" + help_txt += f"The choices are:{possible_args}\n" + help_txt += " Number of top tickers to show. Default: 10" - await ctx.send(embed=embed) - - else: - # Select default - if not arg: - arg = "float" - if not arg2: - arg2 = "10" - - # Parse argument - sort = arg - num = int(arg2) - - df = stockgrid_model.get_short_interest_days_to_cover(sort) - df = df.iloc[:num] - dp_date = df["Date"].values[0] - df = df.drop(columns=["Date"]) - df["Short Interest"] = df["Short Interest"] / 1_000_000 - df.head() - df.columns = [ - "Ticker", - "Float Short %", - "Days to Cover", - "Short Interest (1M)", - ] - future_column_name = df["Ticker"] - df = df.transpose() - df.columns = future_column_name - df.drop("Ticker") - columns = [] - initial_str = "Page 0: Overview" - i = 1 - for column in df.columns.values: - initial_str = initial_str + "\nPage " + str(i) + ": " + column - i += 1 - columns.append( - discord.Embed( - title="Dark Pool Shorts", description=initial_str, colour=cfg.COLOR - ).set_author( + embed = discord.Embed( + title="Stocks: [Stockgrid] Short Interest and Days to Cover HELP", + description=help_txt, + colour=cfg.COLOR, + ) + embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) - ) - for column in df.columns.values: + + await ctx.send(embed=embed) + + else: + # Parse argument + if arg == "float" or arg == "dtc" or arg == "si": + sort = arg + else: + title = "ERROR Stocks: [Stockgrid] Short Interest and Days to Cover" + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + embed.set_description( + f"Entered sort argument: {arg}" + "\nEnter a valid sort argument, example: float" + ) + await ctx.send(embed=embed) + if cfg.DEBUG: + print("ERROR: Bad sort argument entered") + return + + try: + num = int(arg2) + if num < 0: + raise ValueError("Number has to be above 0") + except ValueError: + title = "ERROR Stocks: [Stockgrid] Short Interest and Days to Cover" + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + embed.set_description( + "No number (int) entered in the second argument." + "\nEnter a valid (positive) number, example: 10" + ) + await ctx.send(embed=embed) + if cfg.DEBUG: + print("ERROR: No (positive) int for second argument entered") + return + + df = stockgrid_model.get_short_interest_days_to_cover(sort) + df = df.iloc[:num] + dp_date = df["Date"].values[0] + df = df.drop(columns=["Date"]) + df["Short Interest"] = df["Short Interest"] / 1_000_000 + df.head() + df.columns = [ + "Ticker", + "Float Short %", + "Days to Cover", + "Short Interest (1M)", + ] + future_column_name = df["Ticker"] + df = df.transpose() + df.columns = future_column_name + df.drop("Ticker") + columns = [] + initial_str = "Page 0: Overview" + i = 1 + for column in df.columns.values: + initial_str = initial_str + "\nPage " + str(i) + ": " + column + i += 1 columns.append( discord.Embed( - title="Stocks: [Stockgrid] Short Interest and Days to Cover", - description="```The following data corresponds to the date: " - + dp_date - + "\n\n" - + df[column].fillna("").to_string() - + "```", - colour=cfg.COLOR, + title="Dark Pool Shorts", description=initial_str, colour=cfg.COLOR ).set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) ) + for column in df.columns.values: + columns.append( + discord.Embed( + title="Stocks: [Stockgrid] Short Interest and Days to Cover", + description="```The following data corresponds to the date: " + + dp_date + + "\n\n" + + df[column].fillna("").to_string() + + "```", + colour=cfg.COLOR, + ).set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + ) - await pagination(columns, ctx) + await pagination(columns, ctx) + + except Exception as e: + title = "INTERNAL ERROR" + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + embed.set_description( + "Try updating the bot, make sure DEBUG is True in the config " + "and restart it.\nIf the error still occurs open a issue at: " + "https://github.com/GamestonkTerminal/GamestonkTerminal/issues" + f"\n{e}" + ) + await ctx.send(embed=embed) + if cfg.DEBUG: + print(e) diff --git a/discordbot/stocks/dark_pool_shorts/spos.py b/discordbot/stocks/dark_pool_shorts/spos.py index 8388eb3b2a3..7f70fbac62a 100644 --- a/discordbot/stocks/dark_pool_shorts/spos.py +++ b/discordbot/stocks/dark_pool_shorts/spos.py @@ -8,71 +8,122 @@ from gamestonk_terminal.config_plot import PLOT_DPI from gamestonk_terminal.stocks.dark_pool_shorts import stockgrid_model -async def spos_command(ctx, arg): - # Help - if arg == "-h" or arg == "help": - help_txt = "Plot net short position. [Source: Stockgrid]\n" - help_txt += "\nPossible arguments:\n" - help_txt += " Stock ticker. REQUIRED!\n" - embed = discord.Embed( - title="Stocks: [Stockgrid] Net Short vs Position HELP", - description=help_txt, - colour=cfg.COLOR, - ) - embed.set_author( - name=cfg.AUTHOR_NAME, - icon_url=cfg.AUTHOR_ICON_URL, - ) +async def spos_command(ctx, arg=""): + try: + # Debug + if cfg.DEBUG: + print(f"!stocks.dps.spos {arg}") + + # Help + if arg == "-h" or arg == "help": + help_txt = "Plot net short position. [Source: Stockgrid]\n" + help_txt += "\nPossible arguments:\n" + help_txt += " Stock ticker. REQUIRED!\n" + embed = discord.Embed( + title="Stocks: [Stockgrid] Net Short vs Position HELP", + description=help_txt, + colour=cfg.COLOR, + ) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + + else: + if arg == "": + title = "ERROR Stocks: [Stockgrid] Net Short vs Position" + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + embed.set_description( + "No ticker entered." "\nEnter a valid ticker, example: GME" + ) + await ctx.send(embed=embed) + if cfg.DEBUG: + print("ERROR: No ticker entered") + return + + # Parse argument + ticker = arg.upper() + + plt.ion() + title = f"Stocks: [Stockgrid] Net Short vs Position {arg}" + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + + try: + df = stockgrid_model.get_net_short_position(ticker) + except Exception as e: + title = "ERROR Stocks: [Stockgrid] Price vs Short Interest Volume" + embed = discord.Embed(title=title, colour=cfg.COLOR) + embed.set_author( + name=cfg.AUTHOR_NAME, + icon_url=cfg.AUTHOR_ICON_URL, + ) + embed.set_description( + f"Ticker given: {arg}" "\nEnter a valid ticker, example: GME" + ) + await ctx.send(embed=embed) + if cfg.DEBUG: + print(f"POSSIBLE ERROR: Wrong ticker parameter entered\n{e}") + return + + fig = plt.figure(dpi=PLOT_DPI) + + ax = fig.add_subplot(111) + ax.bar( + df["dates"], + df["dollar_net_volume"] / 1_000, + color="r", + alpha=0.4, + label="Net Short Vol. (1k $)", + ) + ax.set_ylabel("Net Short Vol. (1k $)") + + ax2 = ax.twinx() + ax2.plot( + df["dates"].values, + df["dollar_dp_position"], + c="tab:blue", + label="Position (1M $)", + ) + ax2.set_ylabel("Position (1M $)") + + lines, labels = ax.get_legend_handles_labels() + lines2, labels2 = ax2.get_legend_handles_labels() + ax2.legend(lines + lines2, labels + labels2, loc="upper left") + + ax.grid() + plt.title(f"Net Short Vol. vs Position for {ticker}") + plt.gcf().autofmt_xdate() + file_name = ticker + "_spos.png" + plt.savefig(file_name) + plt.close("all") + uploaded_image = gst_imgur.upload_image(file_name, title="something") + image_link = uploaded_image.link + embed.set_image(url=image_link) + os.remove(file_name) await ctx.send(embed=embed) - else: - # Parse argument - ticker = arg.upper() - - plt.ion() - title = "Stocks: [Stockgrid] Net Short vs Position " + ticker + except Exception as e: + title = "INTERNAL ERROR" embed = discord.Embed(title=title, colour=cfg.COLOR) embed.set_author( name=cfg.AUTHOR_NAME, icon_url=cfg.AUTHOR_ICON_URL, ) - - df = stockgrid_model.get_net_short_position(ticker) - fig = plt.figure(dpi=PLOT_DPI) - - ax = fig.add_subplot(111) - ax.bar( - df["dates"], - df["dollar_net_volume"] / 1_000, - color="r", - alpha=0.4, - label="Net Short Vol. (1k $)", + embed.set_description( + "Try updating the bot, make sure DEBUG is True in the config " + "and restart it.\nIf the error still occurs open a issue at: " + "https://github.com/GamestonkTerminal/GamestonkTerminal/issues" + f"\n{e}" ) - ax.set_ylabel("Net Short Vol. (1k $)") - - ax2 = ax.twinx() - ax2.plot( - df["dates"].values, - df["dollar_dp_position"], - c="tab:blue", - label="Position (1M $)", - ) - ax2.set_ylabel("Position (1M $)") - - lines, labels = ax.get_legend_handles_labels() - lines2, labels2 = ax2.get_legend_handles_labels() - ax2.legend(lines + lines2, labels + labels2, loc="upper left") - - ax.grid() - plt.title(f"Net Short Vol. vs Position for {ticker}") - plt.gcf().autofmt_xdate() - file_name = ticker + "_spos.png" - plt.savefig(file_name) - plt.close("all") - uploaded_image = gst_imgur.upload_image(file_name, title="something") - image_link = uploaded_image.link - embed.set_image(url=image_link) - os.remove(file_name) - await ctx.send(embed=embed) + if cfg.DEBUG: + print(e)