コード例 #1
0
def display_bbands(
    ohlc: pd.DataFrame,
    ticker: str = "",
    length: int = 15,
    n_std: float = 2,
    mamode: str = "sma",
    export: str = "",
    external_axes: Optional[List[plt.Axes]] = None,
):
    """Show bollinger bands

    Parameters
    ----------
    ohlc : pd.DataFrame
        Dataframe of stock prices
    ticker : str
        Ticker
    length : int
        Length of window to calculate BB
    n_std : float
        Number of standard deviations to show
    mamode : str
        Method of calculating average
    export : str
        Format of export file
    external_axes : Optional[List[plt.Axes]], optional
        External axes (1 axis is expected in the list), by default None
    """
    df_ta = volatility_model.bbands(ohlc["Adj Close"], length, n_std, mamode)
    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 not external_axes:
        _, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
    else:
        if len(external_axes) != 1:
            console.print("[red]Expected list of 2 axis items./n[/red]")
            return
        (ax, ) = external_axes

    ax.plot(
        plot_data.index,
        plot_data["Adj Close"].values,
    )
    ax.plot(
        plot_data.index,
        plot_data[df_ta.columns[0]].values,
        theme.down_color,
        linewidth=0.7,
    )
    ax.plot(plot_data.index,
            plot_data[df_ta.columns[1]].values,
            ls="--",
            linewidth=0.7)
    ax.plot(
        plot_data.index,
        plot_data[df_ta.columns[2]].values,
        theme.up_color,
        linewidth=0.7,
    )
    ax.set_title(f"{ticker} Bollinger Bands")
    ax.set_xlim(plot_data.index[0], plot_data.index[-1])
    ax.set_ylabel("Share Price ($)")
    ax.legend([ticker, df_ta.columns[0], df_ta.columns[1], df_ta.columns[2]])
    ax.fill_between(df_ta.index,
                    df_ta.iloc[:, 0].values,
                    df_ta.iloc[:, 2].values,
                    alpha=0.1)
    theme.style_primary_axis(
        ax,
        data_index=plot_data.index.to_list(),
        tick_labels=plot_data["date"].to_list(),
    )

    if external_axes is None:
        theme.visualize_output()

    export_data(
        export,
        os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),
        "bbands",
        df_ta,
    )
コード例 #2
0
def view_bbands(
    ticker: str,
    s_interval: str,
    df_stock: pd.DataFrame,
    length: int,
    n_std: float,
    mamode: str,
    export: str = "",
):
    """Show bollinger bands

    Parameters
    ----------
    ticker : str
        Ticker
    s_interval : str
        Interval of stock data
    df_stock : pd.DataFrame
        Dataframe of stock prices
    length : int
        Length of window to calculate BB
    n_std : float
        Number of standard deviations to show
    mamode : str
        Method of calculating average
    export : str
        Format of export file
    """
    df_ta = volatility_model.bbands(s_interval, df_stock, length, n_std,
                                    mamode)

    fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
    if s_interval == "1440min":
        ax.plot(df_stock.index, df_stock["Adj Close"].values, color="k", lw=3)
    else:
        ax.plot(df_stock.index, df_stock["Close"].values, color="k", lw=3)
    ax.plot(df_ta.index, df_ta.iloc[:, 0].values, "r", lw=2)
    ax.plot(df_ta.index, df_ta.iloc[:, 1].values, "b", lw=1.5, ls="--")
    ax.plot(df_ta.index, df_ta.iloc[:, 2].values, "g", lw=2)
    ax.set_title(f"{ticker} Bollinger Bands")
    ax.set_xlim(df_stock.index[0], df_stock.index[-1])
    ax.set_xlabel("Time")
    ax.set_ylabel("Share Price ($)")

    ax.legend([ticker, df_ta.columns[0], df_ta.columns[1], df_ta.columns[2]])
    ax.fill_between(
        df_ta.index,
        df_ta.iloc[:, 0].values,
        df_ta.iloc[:, 2].values,
        alpha=0.1,
        color="b",
    )
    ax.grid(b=True, which="major", color="#666666", linestyle="-")

    if gtff.USE_ION:
        plt.ion()

    plt.gcf().autofmt_xdate()
    fig.tight_layout(pad=1)

    plt.show()
    print("")

    export_data(
        export,
        os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),
        "bbands",
        df_ta,
    )
コード例 #3
0
ファイル: bbands.py プロジェクト: hbqdev/GamestonkTerminal
async def bbands_command(ctx,
                         ticker="",
                         length="5",
                         n_std="2",
                         mamode="sma",
                         start="",
                         end=""):
    """Displays chart with bollinger bands [Yahoo Finance]"""

    try:

        # Debug
        if cfg.DEBUG:
            # pylint: disable=logging-too-many-args
            logger.debug(
                "!stocks.ta.bbands %s %s %s %s %s %s",
                ticker,
                length,
                n_std,
                mamode,
                start,
                end,
            )

        # Check for argument
        possible_ma = [
            "dema",
            "ema",
            "fwma",
            "hma",
            "linreg",
            "midpoint",
            "pwma",
            "rma",
            "sinwma",
            "sma",
            "swma",
            "t3",
            "tema",
            "trima",
            "vidya",
            "wma",
            "zlma",
        ]

        if ticker == "":
            raise Exception("Stock ticker is required")

        if start == "":
            start = datetime.now() - timedelta(days=365)
        else:
            start = datetime.strptime(start, cfg.DATE_FORMAT)

        if end == "":
            end = datetime.now()
        else:
            end = datetime.strptime(end, cfg.DATE_FORMAT)

        if not length.lstrip("-").isnumeric():
            raise Exception("Number has to be an integer")
        length = float(length)
        if not n_std.lstrip("-").isnumeric():
            raise Exception("Number has to be an integer")
        n_std = float(n_std)

        if mamode not in possible_ma:
            raise Exception("Invalid ma entered")

        ticker = ticker.upper()
        df_stock = discordbot.helpers.load(ticker, start)
        if df_stock.empty:
            raise Exception("Stock ticker is invalid")

        # Retrieve Data
        df_stock = df_stock.loc[(df_stock.index >= start)
                                & (df_stock.index < end)]

        df_ta = volatility_model.bbands(df_stock["Adj Close"], length, n_std,
                                        mamode)

        # Output Data
        bbu = df_ta.columns[2].replace("_", " ")
        bbm = df_ta.columns[1].replace("_", " ")
        bbl = df_ta.columns[0].replace("_", " ")

        fig = go.Figure()
        fig.add_trace(
            go.Scatter(
                name=f"{bbu}",
                x=df_ta.index,
                y=df_ta.iloc[:, 2].values,
                opacity=1,
                mode="lines",
                line_color="indigo",
            ), )
        fig.add_trace(
            go.Scatter(
                name=f"{bbl}",
                x=df_ta.index,
                y=df_ta.iloc[:, 0].values,
                opacity=1,
                mode="lines",
                line_color="indigo",
                fill="tonexty",
                fillcolor="rgba(74, 0, 128, 0.2)",
            ), )
        fig.add_trace(
            go.Scatter(
                name=f"{bbm}",
                x=df_ta.index,
                y=df_ta.iloc[:, 1].values,
                opacity=1,
                line=dict(
                    width=1.5,
                    dash="dash",
                ),
            ), )
        fig.add_trace(
            go.Scatter(
                name=f"{ticker}",
                x=df_stock.index,
                y=df_stock["Adj Close"],
                line=dict(color="#fdc708", width=2),
                opacity=1,
            ), )
        fig.update_layout(
            margin=dict(l=0, r=0, t=50, b=20),
            template=cfg.PLT_TA_STYLE_TEMPLATE,
            colorway=cfg.PLT_TA_COLORWAY,
            title=f"{ticker} Bollinger Bands ({mamode.upper()})",
            title_x=0.5,
            yaxis_title="Stock Price ($)",
            xaxis_title="Time",
            yaxis=dict(fixedrange=False, ),
            xaxis=dict(
                rangeslider=dict(visible=False),
                type="date",
            ),
            dragmode="pan",
            legend=dict(yanchor="top", y=0.99, xanchor="left", x=0.01),
        )
        config = dict({"scrollZoom": True})
        imagefile = "ta_bbands.png"

        # Check if interactive settings are enabled
        plt_link = ""
        if cfg.INTERACTIVE:
            html_ran = random.randint(69, 69420)
            fig.write_html(f"in/bbands_{html_ran}.html", config=config)
            plt_link = f"[Interactive]({cfg.INTERACTIVE_URL}/bbands_{html_ran}.html)"

        fig.update_layout(
            width=800,
            height=500,
        )
        fig.write_image(imagefile)

        img = Image.open(imagefile)
        print(img.size)
        im_bg = Image.open(cfg.IMG_BG)
        h = img.height + 240
        w = img.width + 520

        # Paste fig onto background img and autocrop background
        img = img.resize((w, h), Image.ANTIALIAS)
        x1 = int(0.5 * im_bg.size[0]) - int(0.5 * img.size[0])
        y1 = int(0.5 * im_bg.size[1]) - int(0.5 * img.size[1])
        x2 = int(0.5 * im_bg.size[0]) + int(0.5 * img.size[0])
        y2 = int(0.5 * im_bg.size[1]) + int(0.5 * img.size[1])
        img = img.convert("RGB")
        im_bg.paste(img, box=(x1 - 5, y1, x2 - 5, y2))
        im_bg.save(imagefile, "PNG", quality=100)
        image = Image.open(imagefile)
        image = autocrop_image(image, 0)
        image.save(imagefile, "PNG", quality=100)

        image = disnake.File(imagefile)

        print(f"Image {imagefile}")
        if cfg.DEBUG:
            logger.debug("Image: %s", imagefile)
        title = f"Stocks: Bollinger-Bands {ticker}"
        embed = disnake.Embed(title=title,
                              description=plt_link,
                              colour=cfg.COLOR)
        embed.set_image(url=f"attachment://{imagefile}")
        embed.set_author(
            name=cfg.AUTHOR_NAME,
            icon_url=cfg.AUTHOR_ICON_URL,
        )
        os.remove(imagefile)

        await ctx.send(embed=embed, file=image)

    except Exception as e:
        embed = disnake.Embed(
            title="ERROR Stocks: Bollinger-Bands",
            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)
コード例 #4
0
ファイル: bbands.py プロジェクト: sinyeeftw/GamestonkTerminal
def bbands_command(ticker="",
                   length="5",
                   n_std="2",
                   mamode="sma",
                   start="",
                   end=""):
    """Displays chart with bollinger bands [Yahoo Finance]"""

    # Debug
    if cfg.DEBUG:
        # pylint: disable=logging-too-many-args
        logger.debug(
            "ta-bbands %s %s %s %s %s %s",
            ticker,
            length,
            n_std,
            mamode,
            start,
            end,
        )

    # Check for argument
    possible_ma = [
        "dema",
        "ema",
        "fwma",
        "hma",
        "linreg",
        "midpoint",
        "pwma",
        "rma",
        "sinwma",
        "sma",
        "swma",
        "t3",
        "tema",
        "trima",
        "vidya",
        "wma",
        "zlma",
    ]

    if ticker == "":
        raise Exception("Stock ticker is required")

    if start == "":
        start = datetime.now() - timedelta(days=365)
    else:
        start = datetime.strptime(start, cfg.DATE_FORMAT)

    if end == "":
        end = datetime.now()
    else:
        end = datetime.strptime(end, cfg.DATE_FORMAT)

    if not length.lstrip("-").isnumeric():
        raise Exception("Number has to be an integer")
    length = float(length)
    if not n_std.lstrip("-").isnumeric():
        raise Exception("Number has to be an integer")
    n_std = float(n_std)

    if mamode not in possible_ma:
        raise Exception("Invalid ma entered")

    ticker = ticker.upper()
    df_stock = helpers.load(ticker, start)
    if df_stock.empty:
        raise Exception("Stock ticker is invalid")

    # Retrieve Data
    df_stock = df_stock.loc[(df_stock.index >= start) & (df_stock.index < end)]

    df_ta = volatility_model.bbands(df_stock["Adj Close"], length, n_std,
                                    mamode)

    # Output Data
    bbu = df_ta.columns[2].replace("_", " ")
    bbm = df_ta.columns[1].replace("_", " ")
    bbl = df_ta.columns[0].replace("_", " ")

    fig = go.Figure()
    fig.add_trace(
        go.Scatter(
            name=f"{bbu}",
            x=df_ta.index,
            y=df_ta.iloc[:, 2].values,
            opacity=1,
            mode="lines",
            line_color="indigo",
        ), )
    fig.add_trace(
        go.Scatter(
            name=f"{bbl}",
            x=df_ta.index,
            y=df_ta.iloc[:, 0].values,
            opacity=1,
            mode="lines",
            line_color="indigo",
            fill="tonexty",
            fillcolor="rgba(74, 0, 128, 0.2)",
        ), )
    fig.add_trace(
        go.Scatter(
            name=f"{bbm}",
            x=df_ta.index,
            y=df_ta.iloc[:, 1].values,
            opacity=1,
            line=dict(
                width=1.5,
                dash="dash",
            ),
        ), )
    fig.add_trace(
        go.Scatter(
            name=f"{ticker}",
            x=df_stock.index,
            y=df_stock["Adj Close"],
            line=dict(color="#fdc708", width=2),
            opacity=1,
        ), )
    fig.update_layout(
        margin=dict(l=0, r=0, t=50, b=20),
        template=cfg.PLT_TA_STYLE_TEMPLATE,
        colorway=cfg.PLT_TA_COLORWAY,
        title=f"{ticker} Bollinger Bands ({mamode.upper()})",
        title_x=0.5,
        yaxis_title="Stock Price ($)",
        xaxis_title="Time",
        yaxis=dict(fixedrange=False, ),
        xaxis=dict(
            rangeslider=dict(visible=False),
            type="date",
        ),
        dragmode="pan",
        legend=dict(yanchor="top", y=0.99, xanchor="left", x=0.01),
    )
    config = dict({"scrollZoom": True})
    imagefile = "ta_bbands.png"

    # Check if interactive settings are enabled
    plt_link = ""
    if cfg.INTERACTIVE:
        html_ran = helpers.uuid_get()
        fig.write_html(f"in/bbands_{html_ran}.html", config=config)
        plt_link = f"[Interactive]({cfg.INTERACTIVE_URL}/bbands_{html_ran}.html)"

    fig.update_layout(
        width=800,
        height=500,
    )

    imagefile = helpers.image_border(imagefile, fig=fig)

    return {
        "title": f"Stocks: Bollinger-Bands {ticker}",
        "description": plt_link,
        "imagefile": imagefile,
    }
コード例 #5
0
def bbands_command(
    ticker="",
    interval: int = 15,
    past_days: int = 0,
    length="20",
    n_std: float = 2.0,
    ma_mode="sma",
    start="",
    end="",
    extended_hours: bool = False,
    heikin_candles: bool = False,
    news: bool = False,
):
    """Displays chart with bollinger bands [Yahoo Finance]"""

    # Debug
    if imps.DEBUG:
        # pylint: disable=logging-too-many-args
        logger.debug(
            "ta bbands %s %s %s %s %s %s %s %s %s %s",
            ticker,
            past_days,
            length,
            n_std,
            ma_mode,
            start,
            end,
            extended_hours,
            heikin_candles,
            news,
        )

    # Check for argument
    possible_ma = [
        "dema",
        "ema",
        "fwma",
        "hma",
        "linreg",
        "midpoint",
        "pwma",
        "rma",
        "sinwma",
        "sma",
        "swma",
        "t3",
        "tema",
        "trima",
        "vidya",
        "wma",
        "zlma",
    ]

    if ticker == "":
        raise Exception("Stock ticker is required")

    if not length.lstrip("-").isnumeric():
        raise Exception("Number has to be an integer")
    ta_length = float(length)
    n_std = float(n_std)

    if ma_mode not in possible_ma:
        raise Exception("Invalid ma entered")

    # Retrieve Data
    df_stock, start, end, bar_start = load_candle.stock_data(
        ticker=ticker,
        interval=interval,
        past_days=past_days,
        extended_hours=extended_hours,
        start=start,
        end=end,
        heikin_candles=heikin_candles,
    )

    if df_stock.empty:
        raise Exception("No Data Found")

    df_ta = df_stock.loc[(df_stock.index >= start) & (df_stock.index < end)]
    df_ta = df_ta.join(
        volatility_model.bbands(df_ta["Adj Close"], ta_length, n_std, ma_mode))

    # Output Data
    if interval != 1440:
        df_ta = df_ta.loc[(df_ta.index >= bar_start) & (df_ta.index < end)]
    df_ta = df_ta.fillna(0.0)

    plot = load_candle.candle_fig(df_ta, ticker, interval, extended_hours,
                                  news)
    title = f"<b>{plot['plt_title']} Bollinger Bands ({ma_mode.upper()})</b>"
    fig = plot["fig"]
    idx = 6 if interval != 1440 else 11

    fig.add_trace(
        go.Scatter(
            name=f"BBU_{length}_{n_std}",
            x=df_ta.index,
            y=df_ta.iloc[:, (idx + 2)].values,
            opacity=1,
            mode="lines",
            line_color="indigo",
        ),
        secondary_y=True,
        row=1,
        col=1,
    )
    fig.add_trace(
        go.Scatter(
            name=f"BBL_{length}_{n_std}",
            x=df_ta.index,
            y=df_ta.iloc[:, idx].values,
            opacity=1,
            mode="lines",
            line_color="indigo",
            fill="tonexty",
            fillcolor="rgba(74, 0, 128, 0.2)",
        ),
        secondary_y=True,
        row=1,
        col=1,
    )
    fig.add_trace(
        go.Scatter(
            name=f"BBM_{length}_{n_std}",
            x=df_ta.index,
            y=df_ta.iloc[:, (idx + 1)].values,
            opacity=1,
            line=dict(
                width=1.5,
                dash="dash",
            ),
        ),
        secondary_y=True,
        row=1,
        col=1,
    )
    fig.update_layout(
        margin=dict(l=0, r=0, t=50, b=20),
        template=imps.PLT_TA_STYLE_TEMPLATE,
        colorway=imps.PLT_TA_COLORWAY,
        title=title,
        title_x=0.1,
        title_font_size=14,
        dragmode="pan",
    )
    imagefile = "ta_bbands.png"

    # Check if interactive settings are enabled
    plt_link = ""
    if imps.INTERACTIVE:
        plt_link = imps.inter_chart(fig, imagefile, callback=False)

    fig.update_layout(
        width=800,
        height=500,
    )

    imagefile = imps.image_border(imagefile, fig=fig)

    return {
        "title": f"Stocks: Bollinger-Bands {ticker.upper()}",
        "description": plt_link,
        "imagefile": imagefile,
    }
コード例 #6
0
ファイル: bbands.py プロジェクト: aia/GamestonkTerminal
async def bbands_command(ctx,
                         ticker="",
                         length="5",
                         n_std="2",
                         mamode="sma",
                         start="",
                         end=""):
    """Displays chart with bollinger bands [Yahoo Finance]"""

    try:

        # Debug
        if cfg.DEBUG:
            # pylint: disable=logging-too-many-args
            logger.debug(
                "!stocks.ta.bbands %s %s %s %s %s %s",
                ticker,
                length,
                n_std,
                mamode,
                start,
                end,
            )

        # Check for argument
        possible_ma = [
            "dema",
            "ema",
            "fwma",
            "hma",
            "linreg",
            "midpoint",
            "pwma",
            "rma",
            "sinwma",
            "sma",
            "swma",
            "t3",
            "tema",
            "trima",
            "vidya",
            "wma",
            "zlma",
        ]

        if ticker == "":
            raise Exception("Stock ticker is required")

        if start == "":
            start = datetime.now() - timedelta(days=365)
        else:
            start = datetime.strptime(start, cfg.DATE_FORMAT)

        if end == "":
            end = datetime.now()
        else:
            end = datetime.strptime(end, cfg.DATE_FORMAT)

        if not length.lstrip("-").isnumeric():
            raise Exception("Number has to be an integer")
        length = float(length)
        if not n_std.lstrip("-").isnumeric():
            raise Exception("Number has to be an integer")
        n_std = float(n_std)

        if mamode not in possible_ma:
            raise Exception("Invalid ma entered")

        ticker = ticker.upper()
        df_stock = discordbot.helpers.load(ticker, start)
        if df_stock.empty:
            raise Exception("Stock ticker is invalid")

        # Retrieve Data
        df_stock = df_stock.loc[(df_stock.index >= start)
                                & (df_stock.index < end)]

        df_ta = volatility_model.bbands(df_stock["Adj Close"], length, n_std,
                                        mamode)

        # Output Data
        fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
        ax.plot(df_stock.index, df_stock["Adj Close"].values, color="k", lw=3)
        ax.plot(df_ta.index, df_ta.iloc[:, 0].values, "r", lw=2)
        ax.plot(df_ta.index, df_ta.iloc[:, 1].values, "b", lw=1.5, ls="--")
        ax.plot(df_ta.index, df_ta.iloc[:, 2].values, "g", lw=2)
        ax.set_title(f"{ticker} Bollinger Bands")
        ax.set_xlim(df_stock.index[0], df_stock.index[-1])
        ax.set_xlabel("Time")
        ax.set_ylabel("Share Price ($)")

        ax.legend(
            [ticker, df_ta.columns[0], df_ta.columns[1], df_ta.columns[2]])
        ax.fill_between(
            df_ta.index,
            df_ta.iloc[:, 0].values,
            df_ta.iloc[:, 2].values,
            alpha=0.1,
            color="b",
        )
        ax.grid(b=True, which="major", color="#666666", linestyle="-")

        plt.gcf().autofmt_xdate()
        fig.tight_layout(pad=1)

        plt.savefig("ta_bbands.png")
        uploaded_image = gst_imgur.upload_image("ta_bbands.png",
                                                title="something")
        image_link = uploaded_image.link
        if cfg.DEBUG:
            logger.debug("Image URL: %s", image_link)
        title = "Stocks: Bollinger-Bands " + ticker
        embed = discord.Embed(title=title, colour=cfg.COLOR)
        embed.set_author(
            name=cfg.AUTHOR_NAME,
            icon_url=cfg.AUTHOR_ICON_URL,
        )
        embed.set_image(url=image_link)
        os.remove("ta_bbands.png")

        await ctx.send(embed=embed)

    except Exception as e:
        embed = discord.Embed(
            title="ERROR Stocks: Bollinger-Bands",
            colour=cfg.COLOR,
            description=e,
        )
        embed.set_author(
            name=cfg.AUTHOR_NAME,
            icon_url=cfg.AUTHOR_ICON_URL,
        )

        await ctx.send(embed=embed)