def call_feargreed(self, other_args: List[str]):
        """Process feargreed command"""
        parser = argparse.ArgumentParser(
            add_help=False,
            prog="feargreed",
            description="""
                Display CNN Fear And Greed Index from https://money.cnn.com/data/fear-and-greed/.
            """,
        )
        parser.add_argument(
            "-i",
            "--indicator",
            dest="indicator",
            required=False,
            type=str,
            choices=["jbd", "mv", "pco", "mm", "sps", "spb", "shd", "index"],
            help="""
                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.
            """,
        )
        try:
            if other_args:
                if "-" not in other_args[0]:
                    other_args.insert(0, "-i")

            ns_parser = parse_known_args_and_warn(parser, other_args)
            if not ns_parser:
                return

            cnn_view.fear_and_greed_index(indicator=ns_parser.indicator)

        except Exception as e:
            print(e, "\n")
    def call_feargreed(self, other_args: List[str]):
        """Process feargreed command"""
        parser = argparse.ArgumentParser(
            add_help=False,
            prog="feargreed",
            description="""
                Display CNN Fear And Greed Index from https://money.cnn.com/data/fear-and-greed/.
            """,
        )
        parser.add_argument(
            "-i",
            "--indicator",
            dest="indicator",
            required=False,
            type=str,
            choices=self.fear_greed_indicators,
            help="""
                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.
            """,
        )
        if other_args and "-" not in other_args[0][0]:
            other_args.insert(0, "-i")

        ns_parser = parse_known_args_and_warn(
            parser, other_args, export_allowed=EXPORT_ONLY_FIGURES_ALLOWED)
        if ns_parser:
            cnn_view.fear_and_greed_index(
                indicator=ns_parser.indicator,
                export=ns_parser.export,
            )
Exemple #3
0
def feargreed_command(indicator=""):
    """CNN Fear and Greed Index [CNN]"""

    # Debug user input
    if cfg.DEBUG:
        logger.debug("econ-futures")

    # Check for argument
    possible_indicators = ("", "jbd", "mv", "pco", "mm", "sps", "spb", "shd")

    if indicator not in possible_indicators:
        raise Exception(
            f"Select a valid indicator from {', '.join(possible_indicators)}"  # nosec
        )

    # Retrieve data
    fig = plt.figure(figsize=[1, 1], dpi=10)

    report, _ = cnn_model.get_feargreed_report(indicator, fig)
    cnn_view.fear_and_greed_index(indicator=indicator, export="png")
    plt.close("all")

    # Output data
    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)
        image_path = os.path.join(
            cfg.GST_PATH,
            "exports",
            "economy",
            f"feargreed_{now.strftime('%Y%m%d_%H%M%S')}.png",
        )
        i += 1

    return {
        "title": "Economy: [CNN] Fear Geed Index",
        "imagefile": image_path,
        "description": report,
    }
def test_get_feargreed_report(mocker):
    # MOCK VISUALIZE_OUTPUT
    mocker.patch(
        target="gamestonk_terminal.helper_classes.TerminalStyle.visualize_output"
    )

    # MOCK PLOT_AUTOSCALE
    mocker.patch(
        target="gamestonk_terminal.economy.cnn_view.plot_autoscale",
        return_value=(8.0, 5.0),
    )

    # MOCK PLOT_DPI
    mocker.patch(
        target="gamestonk_terminal.economy.cnn_view.PLOT_DPI",
        new=100,
    )

    # MOCK EXPORT_DATA
    mocker.patch(target="gamestonk_terminal.economy.cnn_view.export_data")

    cnn_view.fear_and_greed_index(indicator="sps", export="")
def test_get_feargreed_report(mocker):
    # MOCK GTFF
    mocker.patch.object(target=cnn_view.gtff, attribute="USE_ION", new=True)

    # MOCK IMSHOW
    mocker.patch(target="matplotlib.pyplot.imshow")

    # MOCK PLOT_AUTOSCALE
    mocker.patch(
        target="gamestonk_terminal.economy.cnn_view.plot_autoscale",
        return_value=(8.0, 5.0),
    )

    # MOCK PLOT_DPI
    mocker.patch(
        target="gamestonk_terminal.economy.cnn_view.PLOT_DPI",
        new=100,
    )

    # MOCK EXPORT_DATA
    mocker.patch(target="gamestonk_terminal.economy.cnn_view.export_data")

    cnn_view.fear_and_greed_index(indicator="sps", export="")
 def call_feargreed(self, other_args: List[str]):
     """Process feargreed command"""
     cnn_view.fear_and_greed_index(other_args)
async def feargreed_command(ctx, indicator=""):
    """CNN Fear and Greed Index [CNN]"""

    try:
        # Debug user input
        if cfg.DEBUG:
            logger.debug("econ-futures")

        # Check for argument
        possible_indicators = ("", "jbd", "mv", "pco", "mm", "sps", "spb", "shd")

        if indicator not in possible_indicators:
            raise Exception(
                f"Select a valid indicator from {', '.join(possible_indicators)}"  # nosec
            )

        # Retrieve data
        fig = plt.figure(figsize=[1, 1], dpi=10)

        report, _ = cnn_model.get_feargreed_report(indicator, fig)
        cnn_view.fear_and_greed_index(indicator=indicator, export="png")
        plt.close("all")

        # Output data
        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)
            image_path = os.path.join(
                cfg.GST_PATH,
                "exports",
                "economy",
                f"feargreed_{now.strftime('%Y%m%d_%H%M%S')}.png",
            )
            i += 1

        embed = disnake.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:
            logger.error("Error when uploading the the image to Imgur.")

        await ctx.send(embed=embed)

    except Exception as e:
        logger.error("ERROR Economy: [CNN] Feargreed. %s", e)
        embed = disnake.Embed(
            title="ERROR Economy: [CNN] Feargreed",
            colour=cfg.COLOR,
            description=e,
        )
        embed.set_author(
            name=cfg.AUTHOR_NAME,
            icon_url=cfg.AUTHOR_ICON_URL,
        )

        await ctx.send(embed=embed, delete_after=30.0)
async def feargreed_command(ctx, arg=""):
    """Gets the fear greed data from GST and sends it

    Parameters
    -----------
    arg: str
        -h or help

    Returns
    -------
    discord message
        Sends a message containing an image of the fear & greed indicator to the user
    """

    try:
        # Debug
        if cfg.DEBUG:
            print(f"!stocks.economy.feargreed {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"""

            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)

            report, _ = cnn_model.get_feargreed_report("", fig)
            cnn_view.fear_and_greed_index(indicator="", export="png")

            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)
                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,
        )
        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)