Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature/heikin-ashi-candles: Adds a flag for Heikin Ashi Candles on stocks/candle #4979

Merged
merged 14 commits into from
May 11, 2023

Conversation

deeleeramone
Copy link
Contributor

@deeleeramone deeleeramone commented May 5, 2023

Description

This PR adds a flag for showing Heikin Ashi candles from the /stocks/candle command.

  • Summary of the change / bug fix.

Updates files:

  • stocks_helper.py
  • stocks_controller.py

Minor details are updated, such as this description.

  -p, --prepost         Pre/After market hours. Only works for 'yf' source, and intraday data (default: False)
(🦋) /stocks/ $ candle --help

usage: candle [-t TICKER] [-p] [--sort {open,high,low,close,adjclose,volume,dividends,stock_splits}] [-r] [--raw] [--trend] [--ma MOV_AVG] [--ha] [--log] [-h] [--export EXPORT]
              [--sheet-name SHEET_NAME [SHEET_NAME ...]] [-l LIMIT]

Shows historic price and volume for the asset.

options:
  -t TICKER, --ticker TICKER
                        Ticker to analyze. (default: None)
  -p, --prepost         Pre/After market hours. Only works for intraday data. (default: False)
  --sort {open,high,low,close,adjclose,volume,dividends,stock_splits}
                        Choose a column to sort by. Only works when raw data is displayed. (default: )
  -r, --reverse         Data is sorted in descending order by default. Reverse flag will sort it in an ascending way. Only works when raw data is displayed. (default: False)
  --raw                 Shows raw data instead of a chart. (default: False)
  --trend               Flag to add high and low trends to candle. (default: False)
  --ma MOV_AVG          Add moving average in number of days to plot and separate by a comma. Value for ma (moving average) keyword needs to be greater than 1. (default: None)
  --ha                  Flag to show Heikin Ashi candles. (default: False)
  --log                 Plot with y axis on log scale (default: False)
  -h, --help            show this help message (default: False)
  --export EXPORT       Export raw data into csv, json, xlsx and figure into png, jpg, pdf, svg (default: )
  --sheet-name SHEET_NAME [SHEET_NAME ...]
                        Name of excel sheet to save data to. Only valid for .xlsx files. (default: None)
  -l LIMIT, --limit LIMIT
                        Number of entries to show in data. (default: 20)

For more information and examples, use 'about candle' to access the related guide.

Also touched is the default title, removing the arbitrary default label, "Stock".

Screenshot 2023-05-04 at 9 20 01 PM

  • Screenshot of the feature or the bug before/after fix, if applicable.

Regular:

/stocks/load AAPL -i 15 --start 2023-05-01/candle

Screenshot 2023-05-04 at 6 57 06 PM

Heikin Ashi:

candle --ha

Screenshot 2023-05-04 at 6 58 43 PM

  • Relevant motivation and context.

  • An option to smooth noise in a candle chart.

  • This could become a synced preference in Hub that aligns with the Bot.

How has this been tested?

  • Make sure affected commands still run in terminal
  • Ensure the SDK still works
Signature:     
openbb.stocks.candle(
    symbol: str,
    data: Optional[pandas.core.frame.DataFrame] = None,
    add_trend: bool = False,
    ma: Optional[Iterable[int]] = None,
    asset_type: str = '',
    start_date: Union[datetime.datetime, str, NoneType] = None,
    interval: int = 1440,
    end_date: Union[datetime.datetime, str, NoneType] = None,
    prepost: bool = False,
    source: str = 'YahooFinance',
    weekly: bool = False,
    monthly: bool = False,
    ha: Optional[bool] = False,
    external_axes: bool = False,
    raw: bool = False,
    yscale: str = 'linear',
) -> Optional[openbb_terminal.core.plots.plotly_helper.OpenBBFigure]
Call signature: openbb.stocks.candle(*args: Any, **kwargs: Any) -> Any
Type:           display_candle
String form:    <openbb_terminal.stocks.stocks_helper.Operation object at 0x10559f340>
File:           ~/GitHub/OpenBBTerminal/openbb_terminal/stocks/stocks_helper.py
Docstring:     
Show candle plot of loaded ticker.

Checklist:

Others

  • I have performed a self-review of my own code.
  • I have commented my code, particularly in hard-to-understand areas.

@reviewpad reviewpad bot added the feat XS Extra small feature label May 5, 2023
@deeleeramone deeleeramone added the enhancement Enhancement label May 5, 2023
@deeleeramone deeleeramone marked this pull request as ready for review May 5, 2023 04:34
@jose-donato jose-donato requested a review from tehcoderer May 5, 2023 11:35
@tehcoderer
Copy link
Contributor

if you want to use the code from bot you can do this

def heikin_ashi(df_data: pd.DataFrame) -> pd.DataFrame:
    """Attempts to calaculate heikin ashi based on given stock ticker data frame."""

    HA_df = df_data.copy()

    # Close column
    HA_df["Close"] = round(
        ((df_data["Open"] + df_data["High"] + df_data["Low"] + df_data["Close"]) / 4), 2
    )
    HA_df.iat[0, 0] = round(
        ((df_data["Open"].iloc[0] + df_data["Close"].iloc[0]) / 2), 2
    )

    # Open column
    for i in range(1, len(df_data)):
        HA_df.iat[i, 0] = round(((HA_df.iat[i - 1, 0] + HA_df.iat[i - 1, 3]) / 2), 2)

    # High and Low column
    HA_df["High"] = HA_df.loc[:, ["Open", "Close"]].join(df_data["High"]).max(axis=1)
    HA_df["Low"] = HA_df.loc[:, ["Open", "Close"]].join(df_data["Low"]).min(axis=1)

    return HA_df

has easy return

    data = heikin_ashi(data)

@deeleeramone
Copy link
Contributor Author

deeleeramone commented May 6, 2023

if you want to use the code from bot you can do this

Pretty much the same thing as what pandas-ta does, except you are dividing, and he is multiplying:

def ha(open_, high, low, close, offset=None, **kwargs):
    """Candle Type: Heikin Ashi"""
    # Validate Arguments
    open_ = verify_series(open_)
    high = verify_series(high)
    low = verify_series(low)
    close = verify_series(close)
    offset = get_offset(offset)

    # Calculate Result
    m = close.size
    df = DataFrame({
        "HA_open": 0.5 * (open_.iloc[0] + close.iloc[0]),
        "HA_high": high,
        "HA_low": low,
        "HA_close": 0.25 * (open_ + high + low + close),
    })

    for i in range(1, m):
        df["HA_open"][i] = 0.5 * (df["HA_open"][i - 1] + df["HA_close"][i - 1])

    df["HA_high"] = df[["HA_open", "HA_high", "HA_close"]].max(axis=1)
    df["HA_low"] = df[["HA_open", "HA_low", "HA_close"]].min(axis=1)

    # Offset
    if offset != 0:
        df = df.shift(offset)

    # Handle fills
    if "fillna" in kwargs:
        df.fillna(kwargs["fillna"], inplace=True)
    if "fill_method" in kwargs:
        df.fillna(method=kwargs["fill_method"], inplace=True)

    # Name and Categorize it
    df.name = "Heikin-Ashi"
    df.category = "candles"

    return df

@jmaslek jmaslek enabled auto-merge May 11, 2023 00:28
@jmaslek jmaslek added this pull request to the merge queue May 11, 2023
Merged via the queue into develop with commit 0e0de86 May 11, 2023
@piiq piiq deleted the feature/heikin-ashi-candles branch June 4, 2023 11:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement Enhancement feat XS Extra small feature
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants