{"record":{"id":"616ee80d4900bd4e","repo":"OpenBB-finance/OpenBB","slug":"error-adding-trend-line-e","errorCode":null,"errorMessage":"Error adding trend line: {e}","messagePattern":"Error adding trend line: (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"openbb_platform/obbject_extensions/charting/openbb_charting/core/openbb_figure.py","lineNumber":266,"sourceCode":"                if column in data.columns:\n                    name = column.split(\"_\")[1].title()\n                    trend = data.copy().dropna()\n                    self.add_shape(\n                        type=\"line\",\n                        name=f\"{name} Trend\",\n                        x0=trend.index[0],\n                        y0=trend[column].iloc[0],\n                        x1=trend.index[-1],\n                        y1=trend[column].iloc[-1],\n                        line=dict(color=color, width=2),\n                        row=row,\n                        col=col,\n                        secondary_y=secondary_y,\n                        **kwargs,\n                    )\n\n        except Exception as e:\n            raise ValueError(f\"Error adding trend line: {e}\") from e\n\n    def add_histplot(  # pylint: disable=too-many-arguments,too-many-locals\n        self,\n        dataset: Union[\"ndarray\", \"Series\", TimeSeriesT],\n        name: str | list[str] | None = None,\n        colors: list[str] | None = None,\n        bins: int | str = 15,\n        curve: Literal[\"normal\", \"kde\"] = \"normal\",\n        show_curve: bool = True,\n        show_rug: bool = True,\n        show_hist: bool = True,\n        forecast: bool = False,\n        row: int = 1,\n        col: int = 1,\n    ) -> None:\n        \"\"\"Add a histogram with a curve and rug plot if desired.\n\n        Parameters","sourceCodeStart":248,"sourceCodeEnd":284,"githubUrl":"https://github.com/OpenBB-finance/OpenBB/blob/3e071fcc2cd9f891cac6040ae60296dba76dab46/openbb_platform/obbject_extensions/charting/openbb_charting/core/openbb_figure.py#L248-L284","documentation":"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).","triggerScenarios":"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.","commonSituations":"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.","solutions":["Read the chained cause (`__cause__`) — it names the actual failing operation; fix that (column name, index alignment, subplot coords).","Align the trend with the figure data before calling: trend = trend.reindex(df.index) and use the exact column label from the plotted DataFrame.","Verify subplot geometry: pass row/col only for subplots that exist, and secondary_y only on figures created with a secondary y-axis.","Catch ValueError around add_trendline so an optional decoration cannot kill the whole chart build."],"exampleFix":"# before\nfig.add_trendline(data=trend_df, \"Close\", row=2, col=1)  # ValueError: Error adding trend line: ...\n\n# after\nclose_col = next(c for c in df.columns if c.lower() == \"close\")\ntrend = trend.reindex(df.index)\ntry:\n    fig.add_trendline(data=trend.to_frame(close_col), close_col, row=1, col=1)\nexcept ValueError as e:\n    print(f\"trend skipped: {e}\")","handlingStrategy":"try-catch","validationCode":"trend = trend.reindex(df.index)\ncol = next((c for c in df.columns if c.lower() in (\"close\", \"adj close\", \"adj_close\")), None)\nif col is None:\n    raise ValueError(\"frame has no close column for trendline\")","typeGuard":"def trendline_ready(df: pd.DataFrame, trend: pd.Series) -> bool:\n    close_like = {c.lower() for c in df.columns} & {\"close\", \"adj close\", \"adj_close\"}\n    return bool(close_like) and trend.index.isin(df.index).any()","tryCatchPattern":"try:\n    fig.add_trendline(data=trend_df, \"close\", row=1, col=1)\nexcept ValueError as e:\n    logger.warning(\"trendline skipped: %s (cause: %s)\", e, e.__cause__)","preventionTips":["Reindex the trend Series onto the plotted DataFrame's index before calling add_trendline.","Use the exact column label present in the frame, not a casing variant.","Confirm subplot row/col exist (candles changes layout) before passing coordinates.","Treat trendlines as optional decoration: catch ValueError and continue charting."],"tags":["python","openbb","charting","plotly","data-alignment"],"backgroundTag":null,"analyzedSha":"3e071fcc2cd9f891cac6040ae60296dba76dab46","analyzedAt":"2026-08-14T23:40:48.960Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}