コード例 #1
0
def test_ema_cross_strategy(mocker):
    yf_download = stocks_helper.yf.download

    def mock_yf_download(*args, **kwargs):
        kwargs["threads"] = False
        return yf_download(*args, **kwargs)

    mocker.patch("yfinance.download", side_effect=mock_yf_download)

    ticker = "PM"
    start = datetime.strptime("2020-12-01", "%Y-%m-%d")
    end = datetime.strptime("2020-12-02", "%Y-%m-%d")
    df_stock = stocks_helper.load_ticker(ticker=ticker,
                                         start_date=start,
                                         end_date=end)
    back_test_instance = bt_model.ema_cross_strategy(
        ticker=ticker,
        df_stock=df_stock,
        short_length=2,
        long_length=2,
        spy_bt=True,
        no_bench=False,
        shortable=True,
    )
    assert isinstance(back_test_instance, bt.backtest.Result)
コード例 #2
0
def display_ema_cross(
    ticker: str,
    df_stock: pd.DataFrame,
    short_ema: int,
    long_ema: int,
    spy_bt: bool = True,
    no_bench: bool = False,
    shortable: bool = True,
    export: str = "",
    external_axes: Optional[List[plt.Axes]] = None,
):  # pylint: disable=R0913
    """Strategy where we go long/short when EMA(short) is greater than/less than EMA(short)

    Parameters
    ----------
    ticker : str
        Stock ticker
    df_stock : pd.Dataframe
        Dataframe of prices
    short_ema : int
        Length of short ema window
    long_ema : int
        Length of long ema window
    spy_bt : bool
        Boolean to add spy comparison
    no_bench : bool
        Boolean to not show buy and hold comparison
    shortable : bool
        Boolean to allow for selling of the stock at cross
    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
    """
    # This plot has 1 axis
    if not external_axes:
        _, 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 one axis item./n[/red]")
            return
        (ax, ) = external_axes

    res = bt_model.ema_cross_strategy(ticker, df_stock, short_ema, long_ema,
                                      spy_bt, no_bench, shortable)
    res.plot(title=f"EMA Cross for EMA({short_ema})/EMA({long_ema})", ax=ax)

    theme.style_primary_axis(ax)

    if not external_axes:
        theme.visualize_output()

    export_data(export, os.path.dirname(os.path.abspath(__file__)),
                "ema_cross", res.stats)
コード例 #3
0
def display_ema_cross(
    ticker: str,
    df_stock: pd.DataFrame,
    short_ema: int,
    long_ema: int,
    spy_bt: bool = True,
    no_bench: bool = False,
    shortable: bool = True,
    export: str = "",
):
    """Strategy where we go long/short when EMA(short) is greater than/less than EMA(short)

    Parameters
    ----------
    ticker : str
        Stock ticker
    df_stock : pd.Dataframe
        Dataframe of prices
    short_ema : int
        Length of short ema window
    long_ema : int
        Length of long ema window
    spy_bt : bool
        Boolean to add spy comparison
    no_bench : bool
        Boolean to not show buy and hold comparison
    shortable : bool
        Boolean to allow for selling of the stock at cross
    export : str
        Format to export data
    """
    res = bt_model.ema_cross_strategy(
        ticker, df_stock, short_ema, long_ema, spy_bt, no_bench, shortable
    )
    fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
    res.plot(title=f"EMA Cross for EMA({short_ema})/EMA({long_ema})", ax=ax)
    ax.grid(b=True, which="major", color="#666666", linestyle="-")
    ax.set_xlim([df_stock.index[0], df_stock.index[-1]])
    fig.tight_layout()
    if gtff.USE_ION:
        plt.ion()
    plt.show()
    print(res.display(), "\n")
    export_data(
        export, os.path.dirname(os.path.abspath(__file__)), "ema_cross", res.stats
    )