OpenBB-finance/OpenBB · error · ValueError

Error adding trend line: {e}

Error message

Error adding trend line: {e}

What it means

OpenBBFigure.add_trendline wraps every exception raised while computing/drawing the trend line (openbb_figure.py:266) in `ValueError(f"Error adding trend line: {e}")`, chaining the original via `from e`. The inner exception is the real cause: typically a KeyError for a missing column, an index mismatch when the trend Series does not align with the figure data, or a plotly add_shape argument error (row/col out of range, bad secondary_y).

Source

Thrown at openbb_platform/obbject_extensions/charting/openbb_charting/core/openbb_figure.py:266

                if column in data.columns:
                    name = column.split("_")[1].title()
                    trend = data.copy().dropna()
                    self.add_shape(
                        type="line",
                        name=f"{name} Trend",
                        x0=trend.index[0],
                        y0=trend[column].iloc[0],
                        x1=trend.index[-1],
                        y1=trend[column].iloc[-1],
                        line=dict(color=color, width=2),
                        row=row,
                        col=col,
                        secondary_y=secondary_y,
                        **kwargs,
                    )

        except Exception as e:
            raise ValueError(f"Error adding trend line: {e}") from e

    def add_histplot(  # pylint: disable=too-many-arguments,too-many-locals
        self,
        dataset: Union["ndarray", "Series", TimeSeriesT],
        name: str | list[str] | None = None,
        colors: list[str] | None = None,
        bins: int | str = 15,
        curve: Literal["normal", "kde"] = "normal",
        show_curve: bool = True,
        show_rug: bool = True,
        show_hist: bool = True,
        forecast: bool = False,
        row: int = 1,
        col: int = 1,
    ) -> None:
        """Add a histogram with a curve and rug plot if desired.

        Parameters

View on GitHub (pinned to 3e071fcc2c)

Solutions

  1. Read the chained cause (`__cause__`) — it names the actual failing operation; fix that (column name, index alignment, subplot coords).
  2. Align the trend with the figure data before calling: trend = trend.reindex(df.index) and use the exact column label from the plotted DataFrame.
  3. Verify subplot geometry: pass row/col only for subplots that exist, and secondary_y only on figures created with a secondary y-axis.
  4. Catch ValueError around add_trendline so an optional decoration cannot kill the whole chart build.

Example fix

# before
fig.add_trendline(data=trend_df, "Close", row=2, col=1)  # ValueError: Error adding trend line: ...

# after
close_col = next(c for c in df.columns if c.lower() == "close")
trend = trend.reindex(df.index)
try:
    fig.add_trendline(data=trend.to_frame(close_col), close_col, row=1, col=1)
except ValueError as e:
    print(f"trend skipped: {e}")
Defensive patterns

Strategy: try-catch

Validate before calling

trend = trend.reindex(df.index)
col = next((c for c in df.columns if c.lower() in ("close", "adj close", "adj_close")), None)
if col is None:
    raise ValueError("frame has no close column for trendline")

Type guard

def trendline_ready(df: pd.DataFrame, trend: pd.Series) -> bool:
    close_like = {c.lower() for c in df.columns} & {"close", "adj close", "adj_close"}
    return bool(close_like) and trend.index.isin(df.index).any()

Try / catch

try:
    fig.add_trendline(data=trend_df, "close", row=1, col=1)
except ValueError as e:
    logger.warning("trendline skipped: %s (cause: %s)", e, e.__cause__)

Prevention

When it happens

Trigger: Calling fig.add_trendline(...) where `data`/`trend` references a column not present in the plotted DataFrame, the trend index does not overlap the x-axis data, or row/col/secondary_y point to a subplot that does not exist.

Common situations: Passing a trend computed on a differently-normalized frame (e.g. percentage vs price), using an OHLC frame whose column is 'close' while the trend Series is named 'Close', or targeting a subplot row that was never created because candles=False changed the layout.

Related errors


AI-assisted analysis of OpenBB-finance/OpenBB@3e071fcc2c (2026-08-14). Data as JSON: /api/errors/616ee80d4900bd4e. Report an issue: GitHub.