예제 #1
0
def display_fisher(
    ohlc: pd.DataFrame,
    length: int = 14,
    s_ticker: str = "",
    export: str = "",
    external_axes: Optional[List[plt.Axes]] = None,
):
    """Display Fisher Indicator

    Parameters
    ----------
    ohlc : pd.DataFrame
        Dataframe of prices
    length : int
        Length of window
    s_ticker : str
        Ticker string
    export : str
        Format to export data
    external_axes : Optional[List[plt.Axes]], optional
        External axes (3 axes are expected in the list), by default None
    """
    df_ta = momentum_model.fisher(ohlc["High"], ohlc["Low"], length)
    plot_data = pd.merge(ohlc,
                         df_ta,
                         how="outer",
                         left_index=True,
                         right_index=True)
    plot_data = reindex_dates(plot_data)

    # This plot has 3 axes
    if not external_axes:
        _, axes = plt.subplots(2,
                               1,
                               sharex=True,
                               figsize=plot_autoscale(),
                               dpi=PLOT_DPI)
        ax1, ax2 = axes
        ax3 = ax2.twinx()
    else:
        if len(external_axes) != 3:
            logger.error("Expected list of three axis items.")
            console.print("[red]Expected list of 3 axis items./n[/red]")
            return
        ax1, ax2, ax3 = external_axes

    ax1.set_title(f"{s_ticker} Fisher Transform")
    ax1.plot(plot_data.index, plot_data["Adj Close"].values)
    ax1.set_xlim(plot_data.index[0], plot_data.index[-1])
    ax1.set_ylabel("Price")
    theme.style_primary_axis(
        ax1,
        data_index=plot_data.index.to_list(),
        tick_labels=plot_data["date"].to_list(),
    )

    ax2.plot(
        plot_data.index,
        plot_data[df_ta.columns[0]].values,
        label="Fisher",
    )
    ax2.plot(
        plot_data.index,
        plot_data[df_ta.columns[1]].values,
        label="Signal",
    )
    ax2.set_xlim(plot_data.index[0], plot_data.index[-1])
    theme.style_primary_axis(
        ax2,
        data_index=plot_data.index.to_list(),
        tick_labels=plot_data["date"].to_list(),
    )

    ax3.set_ylim(ax2.get_ylim())
    ax3.axhspan(2, ax2.get_ylim()[1], facecolor=theme.down_color, alpha=0.2)
    ax3.axhspan(ax2.get_ylim()[0], -2, facecolor=theme.up_color, alpha=0.2)
    ax3.axhline(2, color=theme.down_color, ls="--")
    ax3.axhline(-2, color=theme.up_color, ls="--")
    theme.style_twin_axis(ax3)

    ax2.set_yticks([-2, 0, 2])
    ax2.set_yticklabels(["-2 STDEV", "0", "+2 STDEV"])
    ax2.legend()

    if external_axes is None:
        theme.visualize_output()

    export_data(
        export,
        os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),
        "fisher",
        df_ta,
    )
예제 #2
0
def display_cci(
    ohlc: pd.DataFrame,
    length: int = 14,
    scalar: float = 0.0015,
    s_ticker: str = "",
    export: str = "",
    external_axes: Optional[List[plt.Axes]] = None,
):
    """Display CCI Indicator

    Parameters
    ----------

    ohlc : pd.DataFrame
        Dataframe of OHLC
    length : int
        Length of window
    scalar : float
        Scalar variable
    s_ticker : str
        Stock ticker
    export : str
        Format to export data
    external_axes : Optional[List[plt.Axes]], optional
        External axes (2 axes are expected in the list), by default None
    """
    df_ta = momentum_model.cci(ohlc["High"], ohlc["Low"], ohlc["Adj Close"],
                               length, scalar)
    plot_data = pd.merge(ohlc,
                         df_ta,
                         how="outer",
                         left_index=True,
                         right_index=True)
    plot_data = reindex_dates(plot_data)

    # This plot has 2 axes
    if external_axes is None:
        _, (ax1, ax2) = plt.subplots(2,
                                     1,
                                     figsize=plot_autoscale(),
                                     sharex=True,
                                     dpi=PLOT_DPI)
    else:
        if len(external_axes) != 2:
            logger.error("Expected list of two axis items.")
            console.print("[red]Expected list of 2 axis items./n[/red]")
            return
        ax1, ax2 = external_axes

    ax1.set_title(f"{s_ticker} CCI")
    ax1.plot(
        plot_data.index,
        plot_data["Adj Close"].values,
    )
    ax1.set_xlim(plot_data.index[0], plot_data.index[-1])
    ax1.set_ylabel("Share Price ($)")

    theme.style_primary_axis(
        ax1,
        data_index=plot_data.index.to_list(),
        tick_labels=plot_data["date"].to_list(),
    )

    ax2.plot(plot_data.index, plot_data[df_ta.columns[0]].values)
    ax2.set_xlim(plot_data.index[0], plot_data.index[-1])
    ax2.axhspan(100, ax2.get_ylim()[1], facecolor=theme.down_color, alpha=0.2)
    ax2.axhspan(ax2.get_ylim()[0], -100, facecolor=theme.up_color, alpha=0.2)

    theme.style_primary_axis(
        ax2,
        data_index=plot_data.index.to_list(),
        tick_labels=plot_data["date"].to_list(),
    )

    ax3 = ax2.twinx()
    ax3.set_ylim(ax2.get_ylim())
    ax3.axhline(100, color=theme.down_color, ls="--")
    ax3.axhline(-100, color=theme.up_color, ls="--")

    theme.style_twin_axis(ax3)

    ax2.set_yticks([-100, 100])
    ax2.set_yticklabels(["OVERSOLD", "OVERBOUGHT"])

    if external_axes is None:
        theme.visualize_output()

    export_data(
        export,
        os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),
        "cci",
        df_ta,
    )
예제 #3
0
def display_stoch(
    ohlc: pd.DataFrame,
    fastkperiod: int = 14,
    slowdperiod: int = 3,
    slowkperiod: int = 3,
    s_ticker: str = "",
    export: str = "",
    external_axes: Optional[List[plt.Axes]] = None,
) -> None:
    """Plot stochastic oscillator signal

    Parameters
    ----------
    ohlc : pd.DataFrame
        Dataframe of prices
    fastkperiod : int
        Fast k period
    slowdperiod : int
        Slow d period
    slowkperiod : int
        Slow k period
    s_ticker : str
        Stock ticker
    export : str
        Format to export data
    external_axes : Optional[List[plt.Axes]], optional
        External axes (3 axes are expected in the list), by default None
    """
    df_ta = momentum_model.stoch(
        ohlc["High"],
        ohlc["Low"],
        ohlc["Adj Close"],
        fastkperiod,
        slowdperiod,
        slowkperiod,
    )
    # This plot has 3 axes
    if not external_axes:
        _, axes = plt.subplots(2,
                               1,
                               sharex=True,
                               figsize=plot_autoscale(),
                               dpi=PLOT_DPI)
        ax1, ax2 = axes
        ax3 = ax2.twinx()
    else:
        if len(external_axes) != 3:
            logger.error("Expected list of three axis items.")
            console.print("[red]Expected list of 3 axis items./n[/red]")
            return
        ax1, ax2, ax3 = external_axes

    plot_data = pd.merge(ohlc,
                         df_ta,
                         how="outer",
                         left_index=True,
                         right_index=True)
    plot_data = reindex_dates(plot_data)

    ax1.plot(plot_data.index, plot_data["Adj Close"].values)

    ax1.set_title(
        f"Stochastic Relative Strength Index (STOCH RSI) on {s_ticker}")
    ax1.set_xlim(plot_data.index[0], plot_data.index[-1])
    ax1.set_ylabel("Share Price ($)")
    theme.style_primary_axis(
        ax1,
        data_index=plot_data.index.to_list(),
        tick_labels=plot_data["date"].to_list(),
    )

    ax2.plot(plot_data.index, plot_data[df_ta.columns[0]].values)
    ax2.plot(plot_data.index, plot_data[df_ta.columns[1]].values, ls="--")
    ax2.set_xlim(plot_data.index[0], plot_data.index[-1])
    theme.style_primary_axis(
        ax2,
        data_index=plot_data.index.to_list(),
        tick_labels=plot_data["date"].to_list(),
    )

    ax3.set_ylim(ax2.get_ylim())
    ax3.axhspan(80, 100, facecolor=theme.down_color, alpha=0.2)
    ax3.axhspan(0, 20, facecolor=theme.up_color, alpha=0.2)
    ax3.axhline(80, color=theme.down_color, ls="--")
    ax3.axhline(20, color=theme.up_color, ls="--")
    theme.style_twin_axis(ax3)

    ax2.set_yticks([20, 80])
    ax2.set_yticklabels(["OVERSOLD", "OVERBOUGHT"])
    ax2.legend([f"%K {df_ta.columns[0]}", f"%D {df_ta.columns[1]}"])

    if external_axes is None:
        theme.visualize_output()

    export_data(
        export,
        os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),
        "stoch",
        df_ta,
    )
예제 #4
0
def display_covid_ov(
    country,
    raw: bool = False,
    limit: int = 10,
    export: str = "",
    external_axes: Optional[List[plt.Axes]] = None,
) -> None:
    """Show historical cases and deaths by country

    Parameters
    ----------
    country: str
        Country to get data for
    raw: bool
        Flag to display raw data
    limit: int
        Number of raw data to show
    export: str
        Format to export data
    external_axes : Optional[List[plt.Axes]], optional
        External axes (2 axis is expected in the list), by default None
    """
    cases = covid_model.get_global_cases(country) / 1_000
    deaths = covid_model.get_global_deaths(country)
    ov = pd.concat([cases, deaths], axis=1)
    ov.columns = ["Cases", "Deaths"]

    # This plot has 2 axes
    if external_axes is None:
        _, ax1 = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
        ax2 = ax1.twinx()
    else:
        if len(external_axes) != 2:
            console.print("[red]Expected list of 1 axis item./n[/red]")
            return
        ax1, ax2 = external_axes

    ax1.plot(cases.index, cases, color=theme.up_color, alpha=0.2)
    ax1.plot(cases.index, cases.rolling(7).mean(), color=theme.up_color)
    ax1.set_ylabel("Cases (1k)")
    theme.style_primary_axis(ax1)
    ax1.yaxis.set_label_position("left")

    ax2.plot(deaths.index, deaths, color=theme.down_color, alpha=0.2)
    ax2.plot(deaths.index, deaths.rolling(7).mean(), color=theme.down_color)
    ax2.set_title(f"Overview for {country.upper()}")
    ax2.set_xlabel("Date")
    ax2.set_ylabel("Deaths")
    theme.style_twin_axis(ax2)
    ax2.yaxis.set_label_position("right")

    ax1.set_xlim(ov.index[0], ov.index[-1])
    legend = ax2.legend(ov.columns)
    legend.legendHandles[1].set_color(theme.down_color)
    legend.legendHandles[0].set_color(theme.up_color)

    if external_axes is None:
        theme.visualize_output()

    if raw:
        ov.index = [x.strftime("%Y-%m-%d") for x in ov.index]
        print_rich_table(
            ov.tail(limit),
            headers=[x.title() for x in ov.columns],
            show_index=True,
            index_name="Date",
            title=f"[bold]{country} COVID Numbers[/bold]",
        )
        console.print("")

    if export:
        export_data(export, os.path.dirname(os.path.abspath(__file__)), "ov",
                    ov)