Exemple #1
0
def display_real_gdp(
    interval: str,
    start_year: int = 2010,
    raw: bool = False,
    export: str = "",
    external_axes: Optional[List[plt.Axes]] = None,
):
    """Display US GDP from AlphaVantage

    Parameters
    ----------
    interval : str
        Interval for GDP.  Either "a" or "q"
    start_year : int, optional
        Start year for plot, by default 2010
    raw : bool, optional
        Flag to show raw data, by default False
    export : str, optional
        Format to export data, by default ""
    external_axes : Optional[List[plt.Axes]], optional
        External axes (1 axis is expected in the list), by default None
    """
    gdp_full = alphavantage_model.get_real_gdp(interval)

    if gdp_full.empty:
        return
    gdp = gdp_full[gdp_full.date >= f"{start_year}-01-01"]
    int_string = "Annual" if interval == "a" else "Quarterly"
    year_str = str(start_year) if interval == "a" else str(
        list(gdp.date)[-1].year)

    if external_axes is None:
        _, ax = plt.subplots(figsize=plot_autoscale(), dpi=cfp.PLOT_DPI)

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

    ax.plot(gdp.date, gdp.GDP, marker="o")
    ax.set_title(f"{int_string} US GDP ($B) from {year_str}")
    ax.set_ylabel("US GDP ($B) ")
    theme.style_primary_axis(ax)
    if external_axes is None:
        theme.visualize_output()

    export_data(
        export,
        os.path.dirname(os.path.abspath(__file__)),
        "gdp",
        gdp_full,
    )
    if raw:
        print_rich_table(gdp.head(20),
                         headers=["Date", "GDP"],
                         show_index=False,
                         title="US GDP")
def display_real_gdp(interval: str,
                     start_year: int = 2010,
                     raw: bool = False,
                     export: str = ""):
    """Display US GDP from AlphaVantage

    Parameters
    ----------
    interval : str
        Interval for GDP.  Either "a" or "q"
    start_year : int, optional
        Start year for plot, by default 2010
    raw : bool, optional
        Flag to show raw data, by default False
    export : str, optional
        Format to export data, by default ""
    """
    gdp_full = alphavantage_model.get_real_gdp(interval)
    if gdp_full.empty:
        print("Error getting data.  Check API Key")
        return
    gdp = gdp_full[gdp_full.date >= f"{start_year}-01-01"]
    int_string = "Annual" if interval == "a" else "Quarterly"
    year_str = str(start_year) if interval == "a" else str(
        list(gdp.date)[-1].year)
    fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=cfp.PLOT_DPI)
    ax.plot(gdp.date, gdp.GDP, marker="o", c="dodgerblue")
    ax.set_xlabel("Date")
    ax.set_title(f"{int_string} US GDP ($B) from {year_str}")
    ax.set_ylabel("US GDP ($B) ")
    ax.grid("on")
    fig.tight_layout()
    if gtff.USE_ION:
        plt.ion()
    plt.show()

    export_data(
        export,
        os.path.dirname(os.path.abspath(__file__)),
        "gdp",
        gdp_full,
    )
    if raw:
        if gtff.USE_TABULATE_DF:
            print(
                tabulate(
                    gdp.head(20),
                    headers=["Date", "GDP"],
                    tablefmt="fancy_grid",
                    showindex=False,
                ))
        else:
            print(gdp.head(20).to_string())
    print("")
def test_get_real_gdp_no_response(mocker):
    # MOCK GET
    mock_response = requests.Response()
    mock_response.status_code = 400
    mocker.patch(target="requests.get",
                 new=mocker.Mock(return_value=mock_response))

    result_df = alphavantage_model.get_real_gdp(interval="a")

    assert isinstance(result_df, pd.DataFrame)
    assert result_df.empty
def test_get_real_gdp(recorder):
    result_df = alphavantage_model.get_real_gdp(interval="a")

    recorder.capture(result_df)