Example #1
0
def fear_and_greed_index(indicator: str, export: str):
    """Display CNN Fear And Greed Index. [Source: CNN Business]

    Parameters
    ----------
    indicator : str
        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.
    export : str
        Export plot to png,jpg,pdf file
    """
    fig = plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI)

    report, im = cnn_model.get_feargreed_report(indicator, fig)

    console.print(report)

    if indicator:
        plt.imshow(im)

    export_data(
        export,
        os.path.dirname(os.path.abspath(__file__)),
        "feargreed",
    )

    if gtff.USE_ION:
        plt.ion()
    plt.show()
def test_get_feargreed_report(indicator, mocker, recorder):
    # MOCK IMSHOW
    mocker.patch(target="matplotlib.pyplot.imshow")

    fig = plt.figure(figsize=(8.0, 5.0), dpi=100)

    report, im = cnn_model.get_feargreed_report(indicator=indicator, fig=fig)

    assert report
    assert isinstance(report, str)
    assert im

    recorder.capture(report)
Example #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,
    }
Example #4
0
def fear_and_greed_index(indicator: str,
                         export: str,
                         external_axes: Optional[List[plt.Axes]] = None):
    """Display CNN Fear And Greed Index. [Source: CNN Business]

    Parameters
    ----------
    indicator : str
        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.
    export : str
        Export plot to png,jpg,pdf file
    external_axes : Optional[List[plt.Axes]], optional
        External axes (1 axis is expected in the list), by default None
    """
    if external_axes is None:
        fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)

    else:
        if len(external_axes) != 1:
            logger.error("Expected list of one axis item.")
            console.print("[red]Expected list of 1 axis item./n[/red]")
            return
        (ax, ) = external_axes

    report, im = cnn_model.get_feargreed_report(indicator, fig)

    console.print(report)

    # TODO: Reformat to new layout?
    theme.style_primary_axis(ax)
    if external_axes is None:
        theme.visualize_output()
    if indicator:
        ax.imshow(im)

    export_data(
        export,
        os.path.dirname(os.path.abspath(__file__)),
        "feargreed",
    )
Example #5
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
        )
    # Output data

    fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)

    report, im = cnn_model.get_feargreed_report(indicator, fig)
    ax.axes.xaxis.set_visible(False)
    ax.axes.yaxis.set_visible(False)

    if indicator:
        ax.imshow(im)

    imagefile = "feargreed.png"
    dataBytesIO = io.BytesIO()

    plt.savefig(dataBytesIO)
    plt.close("all")

    dataBytesIO.seek(0)
    imagefile = image_border(imagefile, base64=dataBytesIO)

    return {
        "title": "Economy: [CNN] Fear Geed Index",
        "imagefile": imagefile,
        "description": report,
    }
def fear_and_greed_index(indicator: str):
    """Display CNN Fear And Greed Index.

    Parameters
    ----------
    indicator : str
        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.
    """
    fig = plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI)

    report, im = cnn_model.get_feargreed_report(indicator, fig)

    print(report)

    if indicator:
        plt.imshow(im)

    if gtff.USE_ION:
        plt.ion()
    plt.show()
Example #7
0
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)