[V5] openbb-technical: Refactor for V5 & Add More Quick Win Endpoints (#7502)

* refactor openbb-technical for v5

* forward refs

* linting

* no python 3.15 in test matrix

* reame

* ty

* move all params to body

---------

Co-authored-by: deeleeramone <>
This commit is contained in:
Danglewood
2026-05-29 00:48:51 -07:00
committed by GitHub
parent cd7d602b8f
commit d3d33a219b
79 changed files with 87090 additions and 6460 deletions

View File

@@ -0,0 +1,32 @@
# openbb-technical Documentation
The technical extension exposes ~60 endpoints organised into four families:
| Family | What it does | URL prefix |
|---|---|---|
| `indicators/*` | Single-symbol overlays, oscillators, trend, volume, volatility, structure, statistics | `/` (root) |
| `signals/*` | Event detectors: crossovers, divergences, breakouts, candlestick patterns, regime | `/signals/` |
| `multi/*` | Multi-symbol correlation, screening, relative-rotation, multi-indicator composition, catalog | `/` (root, except `correlation_matrix` and `screen` which expose `multi.*`) |
| `relative_rotation` | JdK RS-Ratio + RS-Momentum for a benchmark-anchored basket | `/` (root) |
Every endpoint is reachable through three transports:
1. **Python**: `from openbb import obb; obb.technical.<endpoint>(...)`
2. **HTTP**: `POST http://localhost:8000/api/v1/technical/<endpoint>` (run `openbb-api` to start the server)
3. **CLI**: `openbb -i` then `/technical/<endpoint>`
## Where to start
- **First time?** [getting-started.md](./getting-started.md) shows installation, the three transports, and a 5-line example for each.
- **Building a strategy?** [user-guides/01-indicators.md](./user-guides/01-indicators.md) covers single-symbol indicator workflows.
- **Want trade signals?** [user-guides/02-signals.md](./user-guides/02-signals.md) covers the signals subrouter.
- **Working with a basket?** [user-guides/03-multi-symbol.md](./user-guides/03-multi-symbol.md) covers correlation, screening, and Relative Rotation Graphs.
- **Composing pipelines?** [user-guides/04-composition-and-discovery.md](./user-guides/04-composition-and-discovery.md) covers the `multi` and `indicators` (catalog) endpoints.
- **Looking up a specific endpoint?** [api-reference.md](./api-reference.md) lists every endpoint with its parameters, output columns, and a one-line description.
## Conventions
- **Input**: every data-consuming endpoint accepts the same shapes — `list[Data]`, `list[dict]`, `pandas.DataFrame`, `pandas.Series`, or `numpy.ndarray`. The library converts between them automatically.
- **Output**: every endpoint returns an `OBBject`. The numeric payload is on `.results` as a list of typed Pydantic models.
- **Validation**: every endpoint validates its inputs through a `XxxQueryParams` Pydantic class and emits its rows through a `XxxData` (or `XxxEvent`/`XxxSignal`) class. The class docstrings carry full NumPy-format `Parameters` and `Returns` sections.
- **Discovery**: the `indicators` endpoint introspects the registered router and returns a structured catalog — useful for building UI pickers, OpenAPI clients, or LLM tool-calls without hard-coding endpoint names.

View File

@@ -0,0 +1,165 @@
"""Regenerate ``docs/api-reference.md`` from the live router catalog.
Run from the extension root:
python docs/_generate_api_reference.py
The reference is auto-generated so that any new or modified endpoint is
reflected after a single command, without hand-editing the markdown.
"""
import pathlib
import re
from openbb import obb
_CLASS_PATTERN = re.compile(r"<class '([^']+)'>")
CATEGORY_ORDER: list[tuple[str, str, str]] = [
(
"overlay",
"Overlays",
"Price-smoothing and envelope indicators plotted on the same axis as price.",
),
("oscillator", "Oscillators", "Bounded momentum indicators."),
("trend", "Trend", "Direction and strength of the prevailing move."),
("volume", "Volume", "Volume-weighted indicators."),
(
"volatility",
"Volatility",
"Realised-volatility estimators and the ATR family.",
),
("structure", "Structure", "Price-action support/resistance levels."),
("stats", "Statistics", "Distributional and time-series diagnostics."),
(
"signal",
"Signals",
"Event detectors. Reachable under the `/signals/` URL prefix; in Python, via `obb.technical.signals.<name>`.",
),
(
"multi",
"Multi-Symbol and Utility",
"Cross-sectional, composition, and discovery endpoints.",
),
]
def type_str(t) -> str:
"""Render a Python type for the docs table."""
if t is None:
return ""
s = str(t) if not isinstance(t, type) else t.__name__
s = _CLASS_PATTERN.sub(lambda m: m.group(1).rsplit(".", 1)[-1], s)
s = s.replace("typing.", "").replace("datetime.", "")
return s.replace("|", "\\|")
def constraints_str(c: dict | None) -> str:
if not c:
return ""
return ", ".join(f"`{k}={v}`" for k, v in c.items())
def cell(s: str | None) -> str:
if not s:
return ""
return s.replace("|", "\\|").replace("\n", " ").strip()
def render() -> str:
# ``obb.technical`` is generated at runtime by the static-package builder
# and not visible to static type checkers.
catalog = obb.technical.indicators(category="all").results # ty: ignore[unresolved-attribute]
entries = catalog.indicators
by_cat: dict[str, list] = {}
for entry in entries:
by_cat.setdefault(entry.category, []).append(entry)
out: list[str] = []
out.append("# API Reference")
out.append("")
out.append(
"Auto-generated from the registered router by "
"`docs/_generate_api_reference.py`. Endpoint names match the Python "
"interface (`obb.technical.<name>` or `obb.technical.signals.<name>`) "
"and the HTTP path (`POST /api/v1/technical/<name>`)."
)
out.append("")
out.append(f"**Total endpoints**: {len(entries)}")
out.append("")
out.append(
"Each endpoint also takes `data` (the OHLC(V) price series) which is "
"omitted from the parameter tables below. `requires_columns` lists "
"the OHLC(V) columns the endpoint reads from `data`."
)
out.append("")
out.append("---")
out.append("")
for cat_key, cat_title, cat_blurb in CATEGORY_ORDER:
cat_entries = by_cat.get(cat_key, [])
if not cat_entries:
continue
out.append(f"## {cat_title}")
out.append("")
out.append(cat_blurb)
out.append("")
for entry in sorted(cat_entries, key=lambda e: e.name):
out.append(f"### `{entry.name}`")
out.append("")
first_line = (entry.description or "").strip().split("\n", 1)[
0
] or "(no description)"
out.append(f"_{first_line}_")
out.append("")
if entry.requires_columns:
cols = ", ".join(f"`{c}`" for c in entry.requires_columns)
out.append(f"**Required input columns**: {cols}")
out.append("")
if entry.params:
out.append("**Parameters** (in addition to `data`):")
out.append("")
out.append("| Name | Type | Default | Constraints | Description |")
out.append("|---|---|---|---|---|")
for p in entry.params:
ptype = type_str(p.type)
if p.choices:
ptype = (
"Literal[" + ", ".join(f'"{c}"' for c in p.choices) + "]"
)
default = (
f"`{p.default}`" if p.default is not None else "*required*"
)
cons = constraints_str(p.constraints)
out.append(
f"| `{p.name}` | `{ptype}` | {default} | {cons} | "
f"{cell(p.description)} |"
)
out.append("")
if entry.output_columns:
out.append(
"**Returns** — `OBBject` with `results` list of rows containing:"
)
out.append("")
out.append("| Column | Type | Nullable | Description |")
out.append("|---|---|---|---|")
for o in entry.output_columns:
otype = type_str(o.type)
nullable = "yes" if o.nullable else "no"
out.append(
f"| `{o.name}` | `{otype}` | {nullable} | {cell(o.description)} |"
)
out.append("")
return "\n".join(out) + "\n"
def main() -> None:
target = pathlib.Path(__file__).parent / "api-reference.md"
target.write_text(render())
if __name__ == "__main__":
main()

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,90 @@
# Getting Started
## Install
```bash
pip install openbb-technical
```
The extension depends on `openbb-core[pandas]`, `pandas-ta-openbb`, `scikit-learn`, `scipy`, and `statsmodels` — all installed transitively.
## Three ways to call an endpoint
Every endpoint is exposed identically through the Python SDK, the REST API, and the CLI. Pick whichever fits your workflow.
### 1. Python
```python
from openbb import obb
data = obb.equity.price.historical(
symbol="SPY", start_date="2024-01-01", provider="yfinance"
).results
result = obb.technical.rsi(data=data, length=14)
print(result.results[0]) # first row of the RSI series
df = result.to_df() # convert results to a DataFrame
```
### 2. REST API
Start the API server (defaults to `http://localhost:8000`):
```bash
openbb-api
```
POST to the endpoint. The `data` array is the request body; scalar args are query-string parameters:
```bash
curl -X POST 'http://localhost:8000/api/v1/technical/rsi?length=14' \
-H 'Content-Type: application/json' \
-d '[{"date":"2024-01-02","open":471.5,"high":473.7,"low":471.0,"close":472.6,"volume":78900},
{"date":"2024-01-03","open":472.5,"high":473.1,"low":468.7,"close":468.8,"volume":111200},
...]'
```
Endpoints that take more than one body argument (`screen`, `multi`, `correlation`, `relative_rotation`, `realized_volatility_compare`, `signals/candlestick_patterns`) wrap the body as `{"data": [...], "<other>": [...]}`.
### 3. CLI
```bash
openbb -i
> /technical/rsi --data <path_or_json> --length 14
```
The CLI auto-generates an argparse interface from each endpoint's signature, so `--help` after any command lists every parameter with its type and default.
## Working with returns
Every endpoint returns an `OBBject`. The interesting bits:
```python
result = obb.technical.bbands(data=data, length=20)
result.results # list[BbandsData] — one row per bar
result.to_df() # pandas DataFrame keyed by date
result.to_dict() # dict form
len(result.results) # row count
result.results[-1] # last row (most recent bar)
```
## Discovering what's available
The `indicators` endpoint introspects the router and returns a structured catalog:
```python
catalog = obb.technical.indicators(category="all").results
for entry in catalog.indicators:
print(entry.name, entry.category, [p.name for p in entry.params])
```
Filter by category — `overlay`, `oscillator`, `volatility`, `volume`, `trend`, `signal`, `structure`, `stats`, `multi`, or `all`.
## Next steps
- [Single-symbol indicator workflows](./user-guides/01-indicators.md)
- [Signal endpoints](./user-guides/02-signals.md)
- [Multi-symbol analysis](./user-guides/03-multi-symbol.md)
- [Multi-indicator composition + catalog](./user-guides/04-composition-and-discovery.md)
- [Full API reference](./api-reference.md)

View File

@@ -0,0 +1,139 @@
# Single-Symbol Indicators
The bulk of the extension — 38 endpoints — computes a technical indicator on a single OHLC(V) series. They're grouped by family below. Every example assumes:
```python
from openbb import obb
data = obb.equity.price.historical(
symbol="SPY", start_date="2022-01-01", provider="yfinance"
).results
```
## Overlays (15 endpoints)
Smooth or envelope the price series. Output overlays on the same axis as price.
```python
sma = obb.technical.sma(data=data, length=50).to_df()
ema = obb.technical.ema(data=data, length=20).to_df()
bb = obb.technical.bbands(data=data, length=20, std=2.0).to_df()
ich = obb.technical.ichimoku(data=data).to_df()
st = obb.technical.supertrend(data=data, length=10, multiplier=3.0).to_df()
```
Moving-average variants: `sma`, `ema`, `hma` (Hull), `wma` (Weighted), `zlma` (Zero-Lag), `tema` (Triple-EMA), `dema` (Double-EMA), `kama` (Kaufman Adaptive), `frama` (Fractal Adaptive), `vwma` (Volume-Weighted).
Bands / channels: `bbands` (Bollinger), `donchian`, `kc` (Keltner).
Composites: `ichimoku` (5-line cloud), `supertrend` (ATR-anchored trailing band).
## Oscillators (10 endpoints)
Bounded momentum indicators. Often consulted alongside an overlay for divergence signals.
```python
rsi = obb.technical.rsi(data=data, length=14).to_df()
stoch = obb.technical.stoch(data=data).to_df() # %K and %D
mfi = obb.technical.mfi(data=data, length=14).to_df() # volume-weighted RSI
```
All 10: `rsi`, `stoch` (Stochastic), `cci` (Commodity Channel), `fisher` (Fisher Transform), `cg` (Centre of Gravity), `williams_r`, `mfi` (Money Flow Index), `trix` (Triple Smoothed ROC), `ultimate_oscillator`, `awesome_oscillator`.
## Trend (5 endpoints)
Decompose the price series into direction + strength signals.
```python
macd = obb.technical.macd(data=data, fast=12, slow=26, signal=9).to_df()
adx = obb.technical.adx(data=data, length=14).to_df()
aroon = obb.technical.aroon(data=data, length=14).to_df()
```
`macd` (Moving Average Convergence/Divergence), `adx` (Average Directional Index), `di` (Directional Indicator +DI/-DI), `aroon`, `choppiness`.
## Volume (4 endpoints)
Use the volume column. Useful for confirming or invalidating price moves.
```python
obv = obb.technical.obv(data=data).to_df()
ad = obb.technical.ad(data=data).to_df()
vwap = obb.technical.vwap(data=data, anchor="D").to_df() # pandas offset alias
```
`obv` (On-Balance Volume), `ad` (Accumulation/Distribution), `adosc` (Chaikin A/D Oscillator), `vwap` (Volume-Weighted Average Price).
## Volatility (4 endpoints)
```python
atr = obb.technical.atr(data=data, length=14).to_df()
# All six realised-volatility estimators side by side
rv = obb.technical.realized_volatility_compare(data=data, window=30).to_df()
# Volatility cones — historical band of rolling vol vs. realised today
cones = obb.technical.cones(data=data, model="yang_zhang").to_df()
```
`atr` (Average True Range), `realized_volatility` (single estimator), `realized_volatility_compare` (all six estimators in one frame), `cones` (per-window realised vs. historical band).
Estimators available for `realized_volatility` and `cones`: `std` (close-to-close), `parkinson` (range-based), `garman_klass` (OHLC), `hodges_tompkins` (bias-corrected close-to-close), `rogers_satchell` (drift-invariant range), `yang_zhang` (minimum-variance composite).
## Structure (3 endpoints)
Price-action levels (support/resistance/pivot points).
```python
fib = obb.technical.fib(data=data, period=120).to_df()
dem = obb.technical.demark(data=data).to_df()
piv = obb.technical.pivot_points(data=data, method="classic", anchor="day").to_df()
```
`fib` (Fibonacci retracement), `demark` (sequential 9 setup), `pivot_points` (five methods: classic, fibonacci, woodie, camarilla, demark; three anchors: day, week, month).
## Statistics (6 endpoints)
Distributional and time-series diagnostics on a price or return series.
```python
clenow = obb.technical.clenow(data=data, period=90).to_df()
dd = obb.technical.drawdown(data=data).to_df()
stats = obb.technical.returns_stats(data=data, frequency="daily").to_df()
stat = obb.technical.stationarity(data=data).to_df()
hurst = obb.technical.hurst(data=data).to_df()
acf = obb.technical.autocorrelation(data=data, max_lag=20).to_df()
```
`clenow` (volatility-adjusted momentum), `drawdown` (peak-to-trough), `returns_stats` (skew, kurtosis, sharpe, sortino, etc.), `stationarity` (ADF + KPSS hypothesis tests), `hurst` (R/S and DFA exponents), `autocorrelation` (ACF + PACF with confidence bands).
## Common parameters
Every data-consuming endpoint accepts:
- `data` — the price series (`list[Data]` / DataFrame / records).
- `index` — column to use as the time index (default `"date"`).
- `target` — for endpoints that work on a single column, the column name (default `"close"`).
Overlay/oscillator endpoints expose a `length` (or `period`) parameter for the rolling window. Most also accept `offset` to shift the output. See the per-endpoint docstring (`help(obb.technical.<name>)`) for the full parameter list.
## Choosing an input shape
`pandas.DataFrame` is convenient if you're already in pandas:
```python
import pandas as pd
df = pd.read_csv("spy.csv")
obb.technical.rsi(data=df, length=14)
```
`list[dict]` is the simplest when reading from CSV or JSON without pandas:
```python
import csv
with open("spy.csv") as f:
records = list(csv.DictReader(f))
obb.technical.rsi(data=records, length=14)
```
Both produce identical output.

View File

@@ -0,0 +1,130 @@
# Signal Endpoints
The `/signals/` subrouter exposes six event-detection endpoints. Unlike the indicator endpoints (which return a dense per-bar series), these emit a **sparse list of detected events** — rows only on bars where the condition fires.
All examples assume:
```python
from openbb import obb
data = obb.equity.price.historical(
symbol="SPY", start_date="2022-01-01", provider="yfinance"
).results
```
## Crossovers
Detects moving-average crossover events between a fast and slow MA.
```python
events = obb.technical.signals.crossovers(
data=data,
fast_length=20,
slow_length=50,
mamode="sma", # or "ema", "wma", "hma", "zlma"
).results
```
Each event row carries: `date`, `direction` (`"bullish"` / `"bearish"`), `fast_value`, `slow_value`, `price`, `distance` (price gap between the two MAs at the crossover bar).
## Oscillator Signals
Labels every bar with a regime (`overbought` / `oversold` / `neutral`) for the chosen oscillator and flags the four boundary-crossing events.
```python
sig = obb.technical.signals.oscillator_signals(
data=data,
indicator="rsi", # or "mfi", "stoch", "williams_r", "cci"
length=14,
overbought_threshold=70.0, # optional override; defaults per indicator
oversold_threshold=30.0,
).results
```
This is a **dense** output (one row per bar) with boolean flags `crossed_into_overbought`, `crossed_into_oversold`, `crossed_out_of_overbought`, `crossed_out_of_oversold` — convenient for plotting shaded regimes and vertical event markers.
## Breakouts
Detects when price closes beyond a rolling-channel envelope.
```python
events = obb.technical.signals.breakouts(
data=data,
method="donchian", # rolling high/low; or "bollinger" (mean +/- stdev band)
length=20,
band_std=2.0, # only used for "bollinger"
).results
```
Each event row carries: `date`, `direction`, `price`, `band` (the breached level), `magnitude` (signed price - band), `bars_in_range` (consolidation length).
## Divergences
Detects classical bullish/bearish/hidden/exaggerated divergences between price and an oscillator across the last `lookback` bars.
```python
events = obb.technical.signals.divergences(
data=data,
indicator="rsi", # or "macd", "stoch", "cci"
indicator_length=14,
lookback=60,
swing_window=3, # bars on either side that define a swing high/low
).results
```
Each event row identifies the kind, the two swing dates that form the pattern, the indicator and price values at each swing, and the bar where the divergence was confirmed.
## Candlestick Patterns
Single-bar and two-bar pattern detection.
```python
events = obb.technical.signals.candlestick_patterns(
data=data,
patterns=["doji", "hammer", "shooting_star", "engulfing"], # None = all
).results
```
Each event row carries: `date`, `pattern` name, `direction` (`bullish` / `bearish` / `neutral`), `confidence` (0-1, based on body/wick ratios meeting textbook thresholds).
Supported patterns: `doji`, `hammer`, `inverted_hammer`, `hanging_man`, `shooting_star`, `bullish_engulfing`, `bearish_engulfing`, `morning_star`, `evening_star`, `three_white_soldiers`, `three_black_crows`, `harami_bullish`, `harami_bearish`, `piercing`, `dark_cloud_cover`. Pass `patterns=None` to scan for all of them.
## Regime
Classifies each bar into one of four regimes based on ADX strength and price trendiness.
```python
out = obb.technical.signals.regime(
data=data,
length=14,
adx_strong_threshold=25.0,
adx_weak_threshold=20.0,
).results
```
Regimes: `strong_trend`, `weak_trend`, `ranging`, `transition`. Each row also flags `regime_changed` on bars where the label shifts — useful for triggering position-sizing rules tied to regime persistence.
## Backtest pattern
The sparse event endpoints (`crossovers`, `breakouts`, `divergences`, `candlestick_patterns`) are designed to plug directly into a vectorised backtester:
```python
events = obb.technical.signals.crossovers(data=data, fast_length=20, slow_length=50).results
trades = [
e for e in events
if e.direction == "bullish" and e.distance > 0.5 # filter weak crossovers
]
```
The dense endpoints (`oscillator_signals`, `regime`) are designed for filter conditions:
```python
sig = obb.technical.signals.oscillator_signals(data=data, indicator="rsi", length=14).results
regime = obb.technical.signals.regime(data=data).results
# Only act on RSI crosses during a strong trend
combined = [
s for s, r in zip(sig, regime)
if s.crossed_into_overbought and r.regime == "strong_trend"
]
```

View File

@@ -0,0 +1,127 @@
# Multi-Symbol Analysis
Five endpoints take a long-format multi-symbol price series (one DataFrame with a `symbol` column) and produce cross-sectional or relative-strength output.
Example input shape:
```python
import pandas as pd
df = pd.read_csv("dow30.csv") # columns: date, symbol, open, high, low, close, volume
print(df.head())
# date open high low close volume symbol
# 0 2024-01-02 187.15 188.44 183.89 185.64 82488700 AAPL
# 1 2024-01-02 376.04 376.04 370.66 370.87 25258600 MSFT
# ...
data = df.to_dict(orient="records")
```
## Correlation (paired)
Returns the rolling Pearson, Spearman, or Kendall correlation of returns for specific symbol pairs.
```python
result = obb.technical.correlation(
data=data,
pairs=[("AAPL", "MSFT"), ("AAPL", "NVDA"), ("NVDA", "MSFT")],
window=60,
method="pearson",
).to_df()
```
Output is a long-format frame with one row per `(symbol_a, symbol_b, date)` tuple. With `window=None`, returns the single full-sample correlation per pair.
## Correlation Matrix (snapshot)
Builds a single point-in-time correlation matrix across every symbol in the input.
```python
result = obb.technical.correlation_matrix(
data=data,
window=60, # rolling window ending at as_of_date
method="spearman",
as_of_date="2024-06-28", # None = most recent date in input
).results[0]
print(result.symbols) # ['AAPL', 'AMZN', 'MSFT', ...]
print(result.matrix) # nested list, indexed by symbols order
```
## Screen
Filters a universe by indicator-driven predicates. Each condition specifies an indicator endpoint, the column to read, an operator, and a threshold.
```python
matches = obb.technical.screen(
data=data,
conditions=[
{
"indicator": "rsi",
"column": "close_RSI_14",
"operator": "lt",
"value": 30.0,
},
{
"indicator": "sma",
"column": "close_SMA_50",
"operator": "gt",
"value": 0.0,
},
],
combine="and", # "or" for union semantics
as_of_date="2024-06-28", # None = each symbol's latest bar
).results
```
Supported operators:
| Operator | `value` shape | Fires when |
|---|---|---|
| `gt`, `gte`, `lt`, `lte`, `eq` | scalar | latest value matches |
| `between` | `(low, high)` | `low <= latest <= high` |
| `crossed_above`, `crossed_below` | `(threshold, lookback)` | series crosses the threshold within the trailing `lookback` bars |
| `made_high`, `made_low` | `(0, lookback)` | latest is the max/min over the trailing `lookback` bars |
Each matched row carries the symbol, the as-of date used, how many conditions fired, and the indicator values at the trigger.
## Relative Rotation Graph
Computes the JdK RS-Ratio (relative-strength level) and RS-Momentum (relative-strength rate of change) for every constituent against a benchmark. Used to locate symbols in one of four rotational quadrants.
```python
# The benchmark symbol must be present in `data`. The canonical RRG setup is
# the benchmark (e.g. an index ETF) plus the constituents you want to rotate
# against it. If you load Dow 30 OHLCV, append SPY rows to `data` before this
# call, or pick one of the constituents as the benchmark.
rrg = obb.technical.relative_rotation(
data=data,
benchmark="AAPL", # any symbol present in `data`
study="price", # or "volume", "volatility"
long_period=252, # RS-Ratio standardisation window
short_period=21, # RS-Momentum standardisation window
window=21, # trail length retained in the output
trading_periods=252, # used by the volatility study
)
rrg.results.rs_ratios # one frame per symbol, indexed by date
rrg.results.rs_momentum # same shape
rrg.results.benchmark # echoed for charting
```
Quadrant interpretation (`x = RS-Ratio`, `y = RS-Momentum`, both centred at 100):
| RS-Ratio | RS-Momentum | Quadrant | Interpretation |
|---|---|---|---|
| > 100 | > 100 | Leading | Outperforming and accelerating |
| > 100 | < 100 | Weakening | Still outperforming but momentum is fading |
| < 100 | < 100 | Lagging | Underperforming with negative momentum |
| < 100 | > 100 | Improving | Underperforming but momentum is turning up |
Symbols rotate clockwise through the quadrants over time. The `window=21` trail draws the rotation arc on a chart.
## Input format constraints
- **`symbol` column required.** All multi-symbol endpoints group by it.
- **Long format only.** Each row is one (symbol, date) observation. Don't pre-pivot.
- **Daily data is the default assumption for `relative_rotation`.** It requires at least `long_period + window` bars per symbol (default ~273 daily bars). The volatility study needs roughly twice as much.
- **Identical date grids preferred.** Symbols whose date series don't fully overlap will be intersected pairwise; the correlation/RRG endpoints work on the intersection.

View File

@@ -0,0 +1,96 @@
# Composition and Discovery
Two utility endpoints round out the extension: `multi` runs many indicators on the same series in one call, and `indicators` introspects the registered router to return a machine-readable catalog.
## multi — many indicators in one call
`multi` dispatches a list of indicator requests against a single input series and merges every numeric output column onto a common date index. Useful for building a feature frame in one round trip.
```python
from openbb import obb
data = obb.equity.price.historical(symbol="SPY", start_date="2023-01-01").results
result = obb.technical.multi(
data=data,
indicators=[
{"indicator": "rsi", "params": {"length": 14}},
{"indicator": "macd", "params": {"fast": 12, "slow": 26, "signal": 9}},
{"indicator": "bbands", "params": {"length": 20, "std": 2.0}},
{"indicator": "atr", "params": {"length": 14}},
],
).to_df()
print(result.head())
# rsi.close_RSI_14 macd.MACD_12_26_9 macd.MACDh_12_26_9 bbands.BBL_20_2.0 ...
# date
# 2023-01-23 46.8 -2.13 0.41 388.74 ...
```
Output column naming is `"<indicator>.<column>"` so you can tell which endpoint produced which value.
Unknown indicator names are silently skipped (so a heterogeneous configuration tolerated). The valid names match the registered router endpoints; see `indicators` (below) for the canonical list.
### When to use multi vs. calling endpoints directly
- **Use `multi`** when you want a feature frame for downstream modelling — you avoid uploading the same OHLCV payload N times and you get one aligned DataFrame.
- **Call endpoints directly** when you care about the per-endpoint output shape (e.g. `bbands` returns three columns plus a bandwidth; the typed `BbandsData` row preserves that structure where `multi` collapses to a flat dict).
## indicators — programmatic catalog
The `indicators` endpoint returns a structured description of every registered router command — name, category, parameters with types and defaults, output columns, and the docstring summary line.
```python
catalog = obb.technical.indicators(category="all").results
print(len(catalog.indicators)) # total endpoints registered
for entry in catalog.indicators:
summary = entry.description.split("\n", 1)[0] # first line of the docstring
print(f"{entry.category:>10s} {entry.name:<20s} {summary}")
```
Filter by category to narrow the listing:
```python
overlays = obb.technical.indicators(category="overlay").results
oscillators = obb.technical.indicators(category="oscillator").results
signals = obb.technical.indicators(category="signal").results
```
Categories: `overlay`, `oscillator`, `volatility`, `volume`, `trend`, `signal`, `structure`, `stats`, `multi`, `all`.
### Per-entry shape
Each `IndicatorEntry` carries:
```python
entry = obb.technical.indicators(category="all").results.indicators[0]
entry.name # str — endpoint name as called via obb.technical.<name>
entry.category # str — one of the categories above
entry.description # str — full QueryParams class docstring (first line is the summary)
entry.requires_columns # list[str] — OHLC(V) columns the endpoint reads from `data`
entry.params # list[IndicatorParam] — every kwarg besides `data`
entry.output_columns # list[IndicatorOutputColumn] — every output column
entry.example_call # dict — a ready-to-invoke kwargs example with default values
```
`IndicatorParam` rows include `name`, `type` (the Python type repr), `default` (or `None` if required), `choices` (the literal values for `Literal[...]` typed fields, otherwise `None`), `description`, and a `constraints` dict carrying `gt`/`ge`/`lt`/`le` bounds where the field declares them.
`IndicatorOutputColumn` rows include `name` (the dict key in the output row), `type`, `nullable`, and `description`.
### Use cases
**Build a UI picker.** Render `entry.params` as form fields with the correct widget per type, with `choices` driving dropdowns and `constraints` (`ge`/`le`/`gt`/`lt`) driving spinners.
**Generate an OpenAPI client.** The catalog mirrors what the OpenAPI schema exposes, but at a higher abstraction level (no FastAPI body-wrapping confusion).
**Drive an LLM tool-call.** Pass the catalog as tool descriptions to a model; it can pick the right indicator and produce the correct `params` dict.
**Validate user input client-side.** Use `parameters[*].choices` and bounds to validate before hitting the server.
## Adding new indicators is automatic
The catalog introspects the registered router at request time, so any endpoint added to `openbb_technical/indicators/`, `openbb_technical/signals/`, or `openbb_technical/multi/` shows up automatically — no separate registry to maintain.
The `__category__` and `__output_columns__` class attributes on each `XxxQueryParams` class drive the category bucket and output-column documentation. Set them on any new endpoint to participate in the catalog.