diff --git a/docs/indicators-data.md b/docs/indicators-data.md new file mode 100644 index 0000000..ce14241 --- /dev/null +++ b/docs/indicators-data.md @@ -0,0 +1,219 @@ +# Ind* indicator widgets: plotting your own data + +The 250 Ind* indicators -- RSI, MACD, Bollinger Bands, ADX, Guppy +MMA, the whole palette -- all draw from the same data model as the +Stock chart widgets, and all take real data the same way: +`set_series()` for bars you already hold in Python, or `load_csv()` +for an OHLCV file. Each kind recomputes its own lines from the loaded +bars; nothing is hard-coded to the demo series any more. + +This is the companion to `stock-charts-data.md`: same bar model, same +CSV spec, same series API (single slot -- indicators have no +second/third symbol). Read that doc for the CSV format details; this +doc covers what is different about indicators. + +## Data model + +A bar is a 5-tuple of floats: + +```python +(open, high, low, close, volume) +``` + +That is the whole model. There is no timestamp on a bar: the x-axis +plots bar index (0, 1, 2, ...), like the C demo. The CSV loader +parses and validates the date column but does not store it. + +## Template data: what ships inside each widget + +With no data fed in, every indicator renders the built-in +deterministic demo series, so the designer and the generated example +draw immediately: + +- `lightgui.xframe.stock.demo_series(n=250, seed=42)` -- an exact + port of C `xframe::make_seeded_series(250)` (StockData.h): a + xorshift64* random walk starting at 100.0. Same `(n, seed)` gives + identical bars on every run. + +## How the lines are computed + +`lightgui/xframe/indicators.py` is generated, not hand-written: the +transpiler in `tools/transpile_indicators.py` translates the C +component `ind_*` function for each kind +(`widgets/components/Ind*/Ind*.h` in the C repo) into Python, one +function per kind, plus the shared helpers they call. The generated +module carries a `INDICATOR_INFO` registry per kind: which function +to call, whether it takes whole bars or closes, its default +parameters, and which of its outputs are plotted lines. + +The transpiled code is numerically verified against the C++ reference: +all 250 kinds, on the seeded demo series, agree with the C++ +component dump to within 1e-9 relative, including the NaN warm-up +patterns (see "Tests and screenshots" below). The Python port follows +the per-component `ind_*` functions, not the separate StockChart +overlay registry in the C repo -- the two disagree systematically +(different warm-up and seeding), and the components are the ones the +widgets actually plot. + +Most kinds plot one line. The multi-line kinds plot all of theirs: + +| Kinds | Lines | +| --- | --- | +| MACD, Bollinger Bands, Keltner Channels, Donchian Channels, and other band/channel kinds | 2-3 (e.g. macd/signal/histogram, upper/middle/lower) | +| Guppy MMA | 12 (six fast + six slow EMAs) | +| Moving Average Ribbon | 6 | +| Klinger Volume Oscillator | 2 (KVO + signal) | + +Line colours cycle through the 14-colour palette from the Rust +`xframe-indicators` `plot.rs` `PLOT_PALETTE` (blue, orange, purple, +teal, magenta, brown, green, red, steel blue, olive, grey, gold, +indigo, brick). Lines are polylines with gaps where the indicator has +no value yet (NaN warm-up). Pattern/marker kinds whose values are +isolated single-bar pivots (FractalUp/Down, ZigZag) draw those points +as filled dots -- a polyline alone would leave no mark. + +## API + +All of this lives on `IndicatorWidget` (`lightgui/xframe/core.py`), +mirroring the `StockWidget` API with a single series slot: + +```python +widget.set_series(bars) # replace the series +widget.get_series() # bars currently plotted (a copy) +widget.populate(bars) # alias for set_series +widget.clear() # empty the series +widget.add_point(bar) # append one bar, return new count +widget.load_csv(path) # load an OHLCV CSV, return bar count +widget.item_count() # number of bars plotted +widget.get_lines(params=None) # plotted lines for the current series +``` + +- `bars` is a list of `(open, high, low, close, volume)` tuples/lists + of numbers, or dicts with `open`/`high`/`low`/`close`/`volume` + keys. Bad bars raise `ValueError` (same validation as the chart + widgets: wrong length, non-numeric, `high` below open/close, `low` + above open/close, negative volume). +- `set_series(None)` reverts to the built-in demo series. +- `clear()` empties the series; the widget then draws a "No data -- + call set_series() or load_csv()" placeholder instead of lines until + `populate()` / `set_series()` refills it (or `set_series(None)` + restores the demo). +- `add_point()` appends to the series. If no own series was set yet + it starts a fresh series -- it does NOT extend the demo series. +- `get_lines()` returns the plotted lines for the current series: a + list of float lists, one value per bar, NaN where the indicator has + no value yet, in plot order. `params` overrides the kind's default + parameters positionally (e.g. `get_lines([7])` for RSI(7)). + Returns `[]` when the series was cleared. This is the same + computation the widget draws; use it in tests or in a generated + program that needs the numbers, not just the picture. +- Series data is runtime state only: it is NOT saved in `.fdj` + files, and it has no Inspector row. A project reloaded in the + designer shows the demo series again until the generated program + loads its data. + +The compute functions are also usable directly, without a widget: + +```python +from lightgui.xframe import indicators +from lightgui.xframe.stock import demo_series, load_csv + +bars = load_csv("prices.csv") +lines = indicators.compute_lines("IndRSI", bars) # [rsi] +macd = indicators.compute_lines("IndMACD", bars) # [macd, signal, hist] +indicators.indicator_names() # all 250 kinds, in palette order +``` + +`compute_lines(kind, bars, params=None)` takes OHLCV bars (or, for +the closes-only kinds, it extracts closes internally). The default +parameters are the ones the C smoke tests use for that kind. + +## CSV format + +Identical to the chart widgets: `load_csv(source)` in +`lightgui/xframe/stock.py`, `source` a path or a file-like object, +`date,open,high,low,close,volume` with an optional header matched by +name (aliases `timestamp`/`time`/`datetime`, `o`/`h`/`l`/`c`, +`vol`/`v`). See `stock-charts-data.md` for the full spec and +validation rules. A ready-made file lives in the repo: +`tests/data/ohlcv_30.csv` -- 30 weekday bars, 2026-01-05 to +2026-02-13, opening at 100.00 and closing at 95.71. + +## Working example + +A complete program: one window, one RSI indicator, CSV data. Run it +from the repo root: + +```python +#!/usr/bin/env python3 +"""Plot an OHLCV CSV file in an IndRSI indicator.""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from lightgui.xframe import core # noqa: E402 + +widget = core.create("IndRSI", "rsi_001", 0, 0, 400, 300) +widget.load_csv("tests/data/ohlcv_30.csv") +print("bars:", widget.item_count()) +print("rsi[29]:", widget.get_lines()[0][29]) + +# ... hand widget to a window/canvas as usual; it draws the RSI line +# for the loaded bars. Without load_csv it would draw the RSI of the +# built-in demo series instead. +``` + +Every committed example in `examples/ind*.py` draws its kind on the +demo series; adding one `widget.load_csv(...)` line after the +`create(...)` call (as `tools/ind_csv_shots.py` does) switches it to +file data. + +## Clear / populate workflow + +```python +widget.clear() # placeholder: "No data -- ..." +widget.populate(bars) # back to lines +widget.set_series(None) # back to the demo series +``` + +## Limits + +- **Warm-up:** most indicators need some bars before their first + finite value (RSI(14) from bar 14, Bollinger from bar 20, ADX from + bar 26). On a short file the lines start with NaNs -- that is the + indicator, not missing data. 36 of the 250 kinds need more than 30 + bars for any finite value at all (multi-stage smoothing such as + TEMA/TRIX/KST, 52-bar Senkou Span B, Klinger slow EMA 55, Guppy + long leg 60); feed them a longer file. +- **Parameters:** the defaults are the C smoke-test parameters for + each kind. `get_lines(params)` overrides them positionally, but + there is no per-kind parameter editor on the widget yet -- the + values are not Inspector props. +- **One series per indicator:** unlike the multi-symbol charts, an + indicator has a single series slot; there is no second/third + symbol. +- **Series is runtime state only** (see API above): not saved in + `.fdj`, no Inspector row. + +## Tests and screenshots + +- `tests/test_indicators_csv.py` (17 tests): the series API + (set/get round-trip, `set_series(None)` restores the demo, + `add_point`, `clear`/`populate`, `item_count`, `load_csv` and its + error paths), golden spot values against the C++ reference (RSI, + MACD, Bollinger, SMA, EMA, ATR), a parameter override, load + + recompute for all 250 kinds on the demo series and the 30-bar CSV, + and rendering -- every kind draws demo and CSV data headless, the + CSV render differs from the demo render, a one-bar series draws, + and a cleared series draws the placeholder. +- `tools/transpile_indicators.py` -- the transpiler that generates + `lightgui/xframe/indicators.py` from the C repo. Its verification + pass (compare every kind's `compute_lines` output against the C++ + component dump on the seeded demo series) must read **250 / 250 + kinds match** before the generated module is committed. +- `tools/ind_csv_shots.py` -- Xvfb screenshots of all 250 kinds with + the 30-bar CSV loaded, each compared (ImageMagick RMSE) against its + template-data golden in `tools/visreg/goldens/`. A large RMSE means + the CSV data is what is plotted. Run from the repo root: + `python3 tools/ind_csv_shots.py`. diff --git a/lightgui/xframe/core.py b/lightgui/xframe/core.py index cade819..32caf07 100644 --- a/lightgui/xframe/core.py +++ b/lightgui/xframe/core.py @@ -2020,10 +2020,223 @@ class ChartWidget(Widget): class IndicatorWidget(Widget): + """One of the 250 Ind* indicators (archetype Indicator). + + Draws the indicator's computed lines from OHLCV bars. The bars + come from the widget's own series when set (``set_series`` / + ``load_csv`` / ``populate``), else from the built-in deterministic + demo series -- the same fallback the StockWidget chart widgets + use. The series is runtime state only, never saved in .fdj. + + The lines themselves are computed by + ``lightgui.xframe.indicators.compute_lines`` (transpiled from the + C component ``ind_*`` functions; see tools/transpile_indicators.py + and lightgui/xframe/indicators.py), so every kind recomputes from + the loaded data instead of the built-in demo lines. + """ + ARCHETYPE = "Indicator" + # Plot palette: the 14 line colours from the Rust + # xframe-indicators plot.rs PLOT_PALETTE, in order. Line j of a + # kind uses _PLOT_PALETTE[j % 14]. + _PLOT_PALETTE = ( + (0.13, 0.35, 0.85), # blue + (0.95, 0.55, 0.10), # orange + (0.55, 0.25, 0.80), # purple + (0.00, 0.60, 0.60), # teal + (0.85, 0.20, 0.55), # magenta + (0.55, 0.35, 0.15), # brown + (0.20, 0.65, 0.25), # green + (0.80, 0.15, 0.15), # red + (0.10, 0.55, 0.80), # steel blue + (0.65, 0.65, 0.10), # olive + (0.35, 0.35, 0.35), # grey + (0.90, 0.70, 0.10), # gold + (0.25, 0.25, 0.70), # indigo + (0.60, 0.20, 0.20), # brick + ) + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # Own series: None means "use the built-in demo series"; + # a list (possibly empty) is data the user fed in. + self._series = None + + # --- data ingestion (mirrors StockWidget, single slot) -------------- + def set_series(self, bars): + """Replace the series this indicator computes from. + + *bars* is a list of (open, high, low, close, volume) tuples + (or dicts with those keys), or None to revert to the built-in + demo series. The indicator recomputes its lines from the new + data on the next draw. Marks the widget dirty so the host + redraws. + """ + self._series = _stock_mod._validate_bars(bars) + self._mark_dirty() + + def populate(self, bars): + """Alias for ``set_series``: fill the indicator with *bars*. + + The clear/populate pair: ``widget.clear()`` empties the + series, ``widget.populate(bars)`` (or ``set_series``) refills + it. + """ + self.set_series(bars) + + def get_series(self): + """The bars this indicator currently plots: the widget's own + series when set, else the built-in demo series. Returns a + copy, so callers cannot mutate the plotted data. + """ + return list(_ind_mod._bars(self)) + + def add_point(self, bar): + """Append one (open, high, low, close, volume) bar to the + series and return the new bar count. + + If no own series was set yet, this starts a fresh series + (it does NOT extend the demo series). + """ + bar = _stock_mod._validate_bars([bar], what="add_point")[0] + if self._series is None: + self._series = [] + self._series.append(bar) + self._mark_dirty() + return len(self._series) + + def clear(self): + """Empty the series. A cleared widget draws the no-data + placeholder until ``populate`` / ``set_series`` refills it + (or ``set_series(None)`` restores the demo series). + """ + self._series = [] + self._mark_dirty() + + def load_csv(self, source): + """Load OHLCV bars from a CSV file into this indicator. + + *source* is a path or a file-like object; see + ``lightgui.xframe.stock.load_csv`` for the format (the same + ``date,open,high,low,close,volume`` spec the chart widgets + use). Returns the number of bars loaded. Raises ValueError + naming the offending row on bad data, and leaves the previous + series untouched in that case. + """ + bars = _stock_mod.load_csv(source) + self.set_series(bars) + return len(bars) + + def item_count(self): + """Number of bars this indicator currently plots.""" + return len(_ind_mod._bars(self)) + + def get_lines(self, params=None): + """The plotted lines for the current series, as a list of + float lists (one per bar, NaN where the indicator has no + value yet), in plot order. *params* overrides the kind's + default parameters positionally. An empty list means the + series was cleared; a kind this widget does not know returns + the panel fallback (no lines). + """ + kind = self._ind_kind() + if kind is None: + return [] + bars = _ind_mod._bars(self) + if not bars: + return [] + return _ind_mod.compute_lines(kind, bars, params) + + def _ind_kind(self): + """Registry name (``IndRSI``) for this widget's kind, or None + when the kind is not one of the 250 indicators.""" + kind = self.kind + if kind in _ind_mod.INDICATOR_INFO: + return kind + if ("Ind" + kind) in _ind_mod.INDICATOR_INFO: + return "Ind" + kind + return None + def _draw(self, cr): - _draw_panel(cr, self) + # A cleared series draws the no-data placeholder instead of + # lines: compute_lines would index into an empty series. + if self._series is not None and len(self._series) == 0: + _stock_mod._no_data(cr, self) + return + kind = self._ind_kind() + if kind is None: + _draw_panel(cr, self) + return + bars = _ind_mod._bars(self) + lines = _ind_mod.compute_lines(kind, bars) + _bg(cr, self, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55)) + _wtext(cr, self, self.pkind, self.width / 2, 16, size=12, + align="center", rgb=(0.4, 0.4, 0.4), + max_width=self.width - 12) + # Plot area below the header. + px, py = 6, 24 + pw, ph = max(1, self.width - 12), max(1, self.height - 30) + n = len(bars) + if n == 0 or ph <= 0: + return + lo, hi = None, None + for values in lines: + for v in values: + if v is None or v != v: + continue + lo = v if lo is None else min(lo, v) + hi = v if hi is None else max(hi, v) + if lo is None: + return + if hi <= lo: + hi = lo + 1.0 + pad = (hi - lo) * 0.05 or 0.5 + lo -= pad + hi += pad + + def _x(i): + return px + (i + 0.5) * pw / n + + def _y(v): + return py + ph - (v - lo) / (hi - lo) * ph + + for j, values in enumerate(lines): + colour = self._PLOT_PALETTE[j % len(self._PLOT_PALETTE)] + cr.save() + _rgb(cr, colour) + cr.set_line_width(2.0) + started = False + for i in range(min(n, len(values))): + v = values[i] + if v is None or v != v: + started = False + continue + if not started: + cr.move_to(_x(i), _y(v)) + started = True + else: + cr.line_to(_x(i), _y(v)) + cr.stroke() + cr.restore() + # Isolated finite points (pattern/marker kinds such as + # FractalUp/Down and ZigZag, whose values are single-bar + # pivots) would otherwise draw nothing: a move_to with no + # line_to leaves no mark. Draw them as filled dots. + cr.save() + _rgb(cr, colour) + for i in range(min(n, len(values))): + v = values[i] + if v is None or v != v: + continue + prev_nan = i == 0 or values[i - 1] is None \ + or values[i - 1] != values[i - 1] + next_nan = i + 1 >= len(values) or values[i + 1] is None \ + or values[i + 1] != values[i + 1] + if prev_nan and next_nan: + cr.arc(_x(i), _y(v), 3, 0, 2 * math.pi) + cr.fill() + cr.restore() class InstrumentWidget(Widget): @@ -2428,6 +2641,7 @@ def is_known_kind(kind): _KIND_CLASSES = {} from lightgui.xframe import stock as _stock_mod +from lightgui.xframe import indicators as _ind_mod from lightgui.xframe import instruments as _inst_mod # Keyed by registry NAME (see lookup()): the Stock* names draw in # StockWidget, the Inst* names in InstWidget. Everything else keeps diff --git a/lightgui/xframe/indicators.py b/lightgui/xframe/indicators.py new file mode 100644 index 0000000..95a6425 --- /dev/null +++ b/lightgui/xframe/indicators.py @@ -0,0 +1,4662 @@ +"""Technical indicators (250): per-kind compute functions. + +Transpiled from the LightGUI C repo (``widgets/components/Ind*/Ind*.h``) +by ``tools/transpile_indicators.py`` -- DO NOT EDIT BY HAND; regenerate. +Each ``ind_*`` function is the C++ widget's own compute: it takes the +OHLCV bars (or the closes) plus its parameters and returns one series +per plotted line (or a result object with named line fields), with the +C++ NaN warm-up semantics (NaN until the window is full, non-finite +inputs skipped, never averaged in). + +Feeding real data: ``IndicatorWidget`` (``lightgui/xframe/core.py``) +holds the series and calls :func:`compute_lines` on every draw, so a +``load_csv`` / ``set_series`` / ``add_point`` immediately recomputes the +lines from the loaded OHLCV data. With no loaded series the widget +plots the built-in deterministic demo series (``stock.demo_series``, +seed 42, 250 bars), exactly as the C++ widgets do with +``make_seeded_series(250)``. + +``INDICATOR_INFO`` maps each palette kind to its compute function, the +series it consumes (``bars`` or ``closes``), its default parameters, +and which lines of the result it plots. +""" + +import math +from types import SimpleNamespace + +from lightgui.xframe.stock import demo_series + + +def _fmax(a, b): + """``std::max`` on doubles: NaN is ignored (the other operand wins).""" + if isinstance(a, float) and math.isnan(a): + return b + if isinstance(b, float) and math.isnan(b): + return a + return a if a > b else b + + +def _fmin(a, b): + """``std::min`` on doubles: NaN is ignored (the other operand wins).""" + if isinstance(a, float) and math.isnan(a): + return b + if isinstance(b, float) and math.isnan(b): + return a + return a if a < b else b + + +def _closes(bars): + return [b[3] for b in bars] + + +def _opens(bars): + return [b[0] for b in bars] + + +def _highs(bars): + return [b[1] for b in bars] + + +def _lows(bars): + return [b[2] for b in bars] + + +def _volumes(bars): + return [b[4] for b in bars] + + +def _typical(bars): + return [(b[1] + b[2] + b[3]) / 3.0 for b in bars] + + +# --- shared helpers (deduped by body hash) --- +# C++ provenance: lightgui 9088092 + +def adx_v(s, p): + dx = list(dx_v(s, p)) + o = [float("nan")] * (len(s)) + if (p < 1): + p = 1 + ssum = 0.0 + cnt = 0 + for i in range(0, len(s)): + if (not math.isfinite(dx[i])): + continue + cnt += 1 + ssum += dx[i] + if (cnt == p): + o[i] = (ssum / p) + elif (cnt > p): + o[i] = (o[(i - 1)] + ((dx[i] - o[(i - 1)]) / p)) + return o + +def atr(s, p): + return ema_wilder(tr(s), p) + +def atr_v(s, p): + tr = list(tr_v(s)) + o = [float("nan")] * (len(s)) + if (p < 1): + p = 1 + acc = 0.0 + for i in range(0, len(s)): + acc += tr[i] + if ((i + 1) == int(p)): + o[i] = (acc / p) + elif ((i + 1) > int(p)): + o[i] = (o[(i - 1)] + ((tr[i] - o[(i - 1)]) / p)) + return o + +def di_minus_v(s, p): + o = [float("nan")] * (len(s)) + if (p < 1): + p = 1 + sp = 0.0 + sm = 0.0 + st = 0.0 + for i in range(0, len(s)): + pdm = 0.0 + mdm = 0.0 + tr = 0.0 + pdm, mdm, tr = dm_tr(s, i) + sp += pdm + sm += mdm + st += tr + if ((i + 1) == int(p)): + o[i] = (((100.0 * (sm / p)) / (st / p)) if (st > 0.0) else 0.0) + elif ((i + 1) > int(p)): + sp = ((sp - (sp / p)) + pdm) + sm = ((sm - (sm / p)) + mdm) + st = ((st - (st / p)) + tr) + o[i] = (((100.0 * sm) / st) if (st > 0.0) else 0.0) + return o + +def di_plus_v(s, p): + o = [float("nan")] * (len(s)) + if (p < 1): + p = 1 + sp = 0.0 + sm = 0.0 + st = 0.0 + for i in range(0, len(s)): + pdm = 0.0 + mdm = 0.0 + tr = 0.0 + pdm, mdm, tr = dm_tr(s, i) + sp += pdm + sm += mdm + st += tr + if ((i + 1) == int(p)): + o[i] = (((100.0 * (sp / p)) / (st / p)) if (st > 0.0) else 0.0) + elif ((i + 1) > int(p)): + sp = ((sp - (sp / p)) + pdm) + sm = ((sm - (sm / p)) + mdm) + st = ((st - (st / p)) + tr) + o[i] = (((100.0 * sp) / st) if (st > 0.0) else 0.0) + return o + +def dm_tr(s, i): + pdm = 0.0 + mdm = 0.0 + tr = 0.0 + if (i == 0): + tr = (s[0][1] - s[0][2]) + return (pdm, mdm, tr) + up = (s[i][1] - s[(i - 1)][1]) + dn = (s[(i - 1)][2] - s[i][2]) + if ((up > dn) and (up > 0.0)): + pdm = up + if ((dn > up) and (dn > 0.0)): + mdm = dn + a = (s[i][1] - s[i][2]) + b = abs((s[i][1] - s[(i - 1)][3])) + c = abs((s[i][2] - s[(i - 1)][3])) + tr = max(a, max(b, c)) + return (pdm, mdm, tr) + +def dx_v(s, p): + plus = list(di_plus_v(s, p)) + minus = list(di_minus_v(s, p)) + o = [float("nan")] * (len(s)) + for i in range(0, len(s)): + if ((not math.isfinite(plus[i])) or (not math.isfinite(minus[i]))): + continue + sum_ = (plus[i] + minus[i]) + o[i] = (((100.0 * abs((plus[i] - minus[i]))) / sum_) if (sum_ > 0.0) else 0.0) + return o + +def ema_239a7b94(v, p): + o = [float("nan")] * (len(v)) + if (not v): + return o + k = (2.0 / (p + 1)) + e = v[0] + for i in range(0, len(v)): + e = (v[0] if (i == 0) else (e + (k * (v[i] - e)))) + if (i >= int((p - 1))): + o[i] = e + return o + +def ema_51fe74d0(v, p): + o = [float("nan")] * (len(v)) + if (p <= 0): + return o + if (p == 1): + return v + a = (2.0 / (p + 1.0)) + prev = 0.0 + have = False + run = 0 + s = 0.0 + for i in range(0, len(v)): + if (not math.isfinite(v[i])): + run = 0 + s = 0.0 + have = False + continue + s += v[i] + run += 1 + if ((not have) and (run >= p)): + prev = (s / p) + o[i] = prev + have = True + elif have: + prev = ((a * v[i]) + ((1.0 - a) * prev)) + o[i] = prev + return o + +def ema_v(x, p): + o = [float("nan")] * (len(x)) + if (p < 1): + p = 1 + if (not x): + return o + k = (2.0 / (p + 1.0)) + cnt = 0 + s = 0.0 + prev = float("nan") + for i in range(0, len(x)): + if (not math.isfinite(x[i])): + continue + if (not math.isfinite(prev)): + s += x[i] + cnt += 1 + if (cnt == p): + prev = (s / p) + o[i] = prev + else: + prev = ((x[i] * k) + (prev * (1.0 - k))) + o[i] = prev + return o + +def ema_wilder(v, p): + o = [float("nan")] * (len(v)) + if (not v): + return o + s = 0.0 + e = 0.0 + for i in range(0, len(v)): + s += v[i] + if (i == int((p - 1))): + e = (s / p) + elif (i >= int(p)): + e = (e + ((v[i] - e) / p)) + if (i >= int((p - 1))): + o[i] = e + return o + +def fin(v): + return math.isfinite(v) + +def fin_v(v): + return math.isfinite(v) + +def hh(v, p): + o = [float("nan")] * (len(v)) + for i in range(0, len(v)): + if (i < int((p - 1))): + continue + m = v[i] + for k in range(1, p): + m = max(m, v[(i - int(k))]) + o[i] = m + return o + +def highest(v, i, p): + m = (-1e300) + for k in range(0, min(p, (i + 1))): + m = max(m, v[(i - int(k))]) + return m + +def highest_v(x, i, p): + m = (-1e300) + lo = (((i + 1) - int(p)) if ((i + 1) >= int(p)) else 0) + for j in range(lo, (i + 1)): + m = max(m, x[j]) + return m + +def linreg_parts(x, i, p): + slope = 0.0 + icept = 0.0 + value = 0.0 + rsq = float("nan") + if ((p < 2) or ((i + 1) < int(p))): + return (slope, icept, value, rsq) + sx = 0.0 + sy = 0.0 + sxx = 0.0 + sxy = 0.0 + for j in range(0, p): + xv = float(j) + yv = x[((i - int((p - 1))) + int(j))] + sx += xv + sy += yv + sxx += (xv * xv) + sxy += (xv * yv) + den = ((float(p) * sxx) - (sx * sx)) + if (den == 0.0): + return (slope, icept, value, rsq) + slope = (((float(p) * sxy) - (sx * sy)) / den) + icept = ((sy - (slope * sx)) / p) + value = (icept + (slope * (p - 1))) + ymean = (sy / p) + sst = 0.0 + sse = 0.0 + for j in range(0, p): + yv = x[((i - int((p - 1))) + int(j))] + fit = (icept + (slope * j)) + sst += ((yv - ymean) * (yv - ymean)) + sse += ((yv - fit) * (yv - fit)) + rsq = ((1.0 - (sse / sst)) if (sst > 0.0) else 1.0) + return (slope, icept, value, rsq) + +def linreg_r2_at(v, i, p): + mean = 0 + for k in range(0, p): + mean += v[((i - int((p - 1))) + int(k))] + mean /= p + ss_tot = 0 + ss_res = 0 + slope = linreg_slope_at(v, i, p) + inter = (mean - ((slope * (p - 1)) / 2.0)) + for k in range(0, p): + y = v[((i - int((p - 1))) + int(k))] + fit = (inter + (slope * k)) + ss_tot += ((y - mean) * (y - mean)) + ss_res += ((y - fit) * (y - fit)) + return (0.0 if (ss_tot == 0.0) else (1.0 - (ss_res / ss_tot))) + +def linreg_slope_at(v, i, p): + sx = 0 + sy = 0 + sxx = 0 + sxy = 0 + for k in range(0, p): + x = float(k) + y = v[((i - int((p - 1))) + int(k))] + sx += x + sy += y + sxx += (x * x) + sxy += (x * y) + den = ((float(p) * sxx) - (sx * sx)) + return (0.0 if (den == 0.0) else (((float(p) * sxy) - (sx * sy)) / den)) + +def linreg_value_at(v, i, p): + sx = 0 + sy = 0 + sxx = 0 + sxy = 0 + for k in range(0, p): + x = float(k) + y = v[((i - int((p - 1))) + int(k))] + sx += x + sy += y + sxx += (x * x) + sxy += (x * y) + den = ((float(p) * sxx) - (sx * sx)) + if (den == 0.0): + return (sy / p) + slope = (((float(p) * sxy) - (sx * sy)) / den) + inter = ((sy - (slope * sx)) / p) + return (inter + (slope * (p - 1))) + +def ll(v, p): + o = [float("nan")] * (len(v)) + for i in range(0, len(v)): + if (i < int((p - 1))): + continue + m = v[i] + for k in range(1, p): + m = min(m, v[(i - int(k))]) + o[i] = m + return o + +def logret(c): + o = [0.0] * (len(c)) + for i in range(1, len(c)): + if ((c[i] > 0) and (c[(i - 1)] > 0)): + o[i] = math.log((c[i] / c[(i - 1)])) + return o + +def lowest(v, i, p): + m = 1e300 + for k in range(0, min(p, (i + 1))): + m = min(m, v[(i - int(k))]) + return m + +def lowest_v(x, i, p): + m = 1e300 + lo = (((i + 1) - int(p)) if ((i + 1) >= int(p)) else 0) + for j in range(lo, (i + 1)): + m = min(m, x[j]) + return m + +def mid_v(hi, lo, p): + o = [float("nan")] * (len(hi)) + for i in range(0, len(hi)): + if ((i + 1) >= int(p)): + o[i] = ((highest_v(hi, i, p) + lowest_v(lo, i, p)) / 2.0) + return o + +def nan_v(): + return float("nan") + +def nanv(): + return float("nan") + +def rsi_series(c, p): + n = len(c) + o = [float("nan")] * (n) + if ((n < int((p + 1))) or (p <= 0)): + return o + g = [0.0] * (n) + l = [0.0] * (n) + for i in range(1, n): + d = (c[i] - c[(i - 1)]) + g[i] = (d if (d > 0) else 0.0) + l[i] = ((-d) if (d < 0) else 0.0) + ag = list(wilder(g, p)) + al = list(wilder(l, p)) + for i in range(0, n): + if ((not math.isfinite(ag[i])) or (not math.isfinite(al[i]))): + continue + den = (ag[i] + al[i]) + o[i] = (50.0 if (den == 0.0) else ((100.0 * ag[i]) / den)) + return o + +def sma_30e386ad(v, p): + o = [float("nan")] * (len(v)) + if (p <= 0): + return o + if (p == 1): + return v + for i in range(0, len(v)): + if (i < int((p - 1))): + continue + s = 0.0 + ok = True + for k in range(0, p): + if (not math.isfinite(v[(i - int(k))])): + ok = False + else: + s += v[(i - int(k))] + if ok: + o[i] = (s / p) + return o + +def sma_58520e20(v, p): + o = [float("nan")] * (len(v)) + if (p <= 1): + return v + s = 0.0 + for i in range(0, len(v)): + s += v[i] + if (i >= int(p)): + s -= v[(i - int(p))] + if (i >= int((p - 1))): + o[i] = (s / p) + return o + +def sma_v(x, p): + o = [float("nan")] * (len(x)) + if (p < 1): + p = 1 + for i in range(0, len(x)): + if ((i + 1) < int(p)): + continue + s = 0.0 + ok = True + for j in range(0, p): + v = x[(i - int(j))] + if (not math.isfinite(v)): + ok = False + break + s += v + if ok: + o[i] = (s / p) + return o + +def smma_v(x, p): + o = [float("nan")] * (len(x)) + if (p < 1): + p = 1 + if (not x): + return o + cnt = 0 + s = 0.0 + prev = float("nan") + for i in range(0, len(x)): + if (not math.isfinite(x[i])): + continue + if (not math.isfinite(prev)): + s += x[i] + cnt += 1 + if (cnt == p): + prev = (s / p) + o[i] = prev + else: + prev = (prev + ((x[i] - prev) / p)) + o[i] = prev + return o + +def stddev_7bc07ae7(v, p): + o = [float("nan")] * (len(v)) + m = list(sma_58520e20(v, p)) + sq = [0.0] * (len(v)) + for i in range(0, len(v)): + sq[i] = (v[i] * v[i]) + ms = list(sma_58520e20(sq, p)) + for i in range(0, len(v)): + if math.isfinite(m[i]): + var = (ms[i] - (m[i] * m[i])) + o[i] = math.sqrt((var if (var > 0) else 0.0)) + return o + +def stddev_8463129b(v, p): + o = [float("nan")] * (len(v)) + if (p <= 1): + return o + m = list(sma_30e386ad(v, p)) + for i in range(0, len(v)): + if (not math.isfinite(m[i])): + continue + ok = True + for k in range(0, p): + if (not math.isfinite(v[(i - int(k))])): + ok = False + if (not ok): + continue + s = 0.0 + for k in range(0, p): + d = (v[(i - int(k))] - m[i]) + s += (d * d) + o[i] = math.sqrt((s / p)) + return o + +def stoch_k(h, l, c, p): + o = [float("nan")] * (len(c)) + for i in range(0, len(c)): + if (i < int((p - 1))): + continue + hh = highest(h, i, p) + ll = lowest(l, i, p) + if (hh == ll): + o[i] = 50.0 + continue + o[i] = ((100.0 * (c[i] - ll)) / (hh - ll)) + return o + +def super_smoother(v, p): + o = [float("nan")] * (len(v)) + if (p < 2): + return v + pi = 3.141592653589793 + a1 = math.exp((((-1.414) * pi) / p)) + b1 = ((2.0 * a1) * math.cos(((1.414 * pi) / p))) + c2 = b1 + c3 = ((-a1) * a1) + c1 = ((1.0 - c2) - c3) + for i in range(0, len(v)): + if (not math.isfinite(v[i])): + continue + pm1 = (v[(i - 1)] if ((i >= 1) and math.isfinite(v[(i - 1)])) else v[i]) + o1 = (o[(i - 1)] if ((i >= 1) and math.isfinite(o[(i - 1)])) else 0.0) + o2 = (o[(i - 2)] if ((i >= 2) and math.isfinite(o[(i - 2)])) else 0.0) + if (i < 2): + o[i] = v[i] + continue + o[i] = ((((c1 * (v[i] + pm1)) / 2.0) + (c2 * o1)) + (c3 * o2)) + return o + +def tr(s): + o = [float("nan")] * (len(s)) + for i in range(0, len(s)): + if (i == 0): + o[i] = (s[i][1] - s[i][2]) + else: + o[i] = max([(s[i][1] - s[i][2]), abs((s[i][1] - s[(i - 1)][3])), abs((s[i][2] - s[(i - 1)][3]))]) + return o + +def tr_v(s): + o = [0.0] * (len(s)) + for i in range(0, len(s)): + if (i == 0): + o[i] = (s[i][1] - s[i][2]) + continue + a = (s[i][1] - s[i][2]) + b = abs((s[i][1] - s[(i - 1)][3])) + c = abs((s[i][2] - s[(i - 1)][3])) + o[i] = max(a, max(b, c)) + return o + +def wilder(v, p): + o = [float("nan")] * (len(v)) + if (p <= 0): + return o + a = (1.0 / p) + prev = 0.0 + have = False + run = 0 + s = 0.0 + for i in range(0, len(v)): + if (not math.isfinite(v[i])): + run = 0 + s = 0.0 + have = False + continue + s += v[i] + run += 1 + if ((not have) and (run >= p)): + prev = (s / p) + o[i] = prev + have = True + elif have: + prev = ((a * v[i]) + ((1.0 - a) * prev)) + o[i] = prev + return o + +def wma_v(x, p): + o = [float("nan")] * (len(x)) + if (p < 1): + p = 1 + wsum = ((float(p) * (p + 1)) / 2.0) + for i in range(0, len(x)): + if ((i + 1) < int(p)): + continue + s = 0.0 + ok = True + for j in range(0, p): + v = x[(i - int(j))] + if (not math.isfinite(v)): + ok = False + break + s += (v * (p - j)) + if ok: + o[i] = (s / wsum) + return o + +# --- per-kind compute functions --- + +def ind_adx(series, period): + return adx_v(series, period) + +def ind_adxr(series, period): + a = list(adx_v(series, period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if ((math.isfinite(a[i]) and (i >= int(period))) and math.isfinite(a[(i - int(period))])): + o[i] = ((a[i] + a[(i - int(period))]) / 2.0) + return o + +def ind_alma(closes, period, offset, sigma): + o = [float("nan")] * (len(closes)) + if (period < 1): + period = 1 + m = (offset * (period - 1)) + w = [0.0] * (int(period)) + ws = 0.0 + for i in range(0, period): + w[int(i)] = math.exp(((-((i - m) * (i - m))) / ((2.0 * sigma) * sigma))) + ws += w[int(i)] + for i in range(0, len(closes)): + if ((i + 1) < int(period)): + continue + s = 0.0 + for j in range(0, period): + s += (closes[((i - int((period - 1))) + int(j))] * w[int(j)]) + o[i] = (s / ws) + return o + +def ind_apo(closes, fast=12, slow=26): + ef = list(ema_51fe74d0(closes, fast)) + es = list(ema_51fe74d0(closes, slow)) + out = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if (math.isfinite(ef[i]) and math.isfinite(es[i])): + out[i] = (ef[i] - es[i]) + return out + +def ind_atr(series, period=14): + return atr(series, period) + +def ind_accelerator_oscillator(s, fast=5, slow=34, smooth=5): + h = list(_highs(s)) + l = list(_lows(s)) + med = [float("nan")] * (len(h)) + for i in range(0, len(h)): + med[i] = ((h[i] + l[i]) / 2.0) + f = list(sma_30e386ad(med, fast)) + sl = list(sma_30e386ad(med, slow)) + ao = [float("nan")] * (len(med)) + for i in range(0, len(med)): + if (math.isfinite(f[i]) and math.isfinite(sl[i])): + ao[i] = (f[i] - sl[i]) + sm = list(sma_30e386ad(ao, smooth)) + out = [float("nan")] * (len(med)) + for i in range(0, len(med)): + if (math.isfinite(ao[i]) and math.isfinite(sm[i])): + out[i] = (ao[i] - sm[i]) + return out + +def ind_accumulation_distribution_line(series, period=1): + o = [float("nan")] * (len(series)) + acc = 0.0 + for i in range(0, len(series)): + range_ = (series[i][1] - series[i][2]) + clv = ((((series[i][3] - series[i][2]) - (series[i][1] - series[i][3])) / range_) if (range_ != 0.0) else 0.0) + acc += (clv * series[i][4]) + o[i] = acc + return o + +def ind_accumulative_swing_index(series, limitMove): + o = [float("nan")] * (len(series)) + if (limitMove <= 0.0): + limitMove = 1.0 + acc = 0.0 + for i in range(1, len(series)): + b = series[i] + p = series[(i - 1)] + rnum = abs((b[1] - p[3])) + rden = abs((b[2] - p[3])) + r = max(rnum, max(rden, (b[1] - b[2]))) + k = max(rnum, rden) + num = (((b[3] - p[3]) + (0.5 * (b[3] - b[0]))) + (0.25 * (p[3] - p[0]))) + si = ((((50.0 * num) / r) * (k / limitMove)) if (r > 0.0) else 0.0) + acc += si + o[i] = acc + return o + +def ind_adaptive_cyber_cycle(closes, dummy=0): + n = len(closes) + out = [float("nan")] * (n) + sm = [0.0] * (n) + cy = [0.0] * (n) + cyc = [0.0] * (n) + for i in range(0, n): + c0 = closes[i] + c1 = (closes[(i - 1)] if (i >= 1) else c0) + c2 = (closes[(i - 2)] if (i >= 2) else c0) + c3 = (closes[(i - 3)] if (i >= 3) else c0) + sm[i] = ((((c0 + (2.0 * c1)) + (2.0 * c2)) + c3) / 6.0) + for i in range(0, n): + a = 0.07 + if (i >= 50): + cross = 0 + for k in range((i - 49), i): + if ((cyc[k] >= 0.0) != (cyc[(k - 1)] >= 0.0)): + cross += 1 + p = (20.0 if (cross == 0) else (98.0 / cross)) + if (p < 10.0): + p = 10.0 + if (p > 40.0): + p = 40.0 + a = ((0.07 * 20.0) / p) + if (a < 0.02): + a = 0.02 + if (a > 0.20): + a = 0.20 + s1 = (sm[(i - 1)] if (i >= 1) else sm[i]) + s2 = (sm[(i - 2)] if (i >= 2) else sm[i]) + y1 = (cy[(i - 1)] if (i >= 1) else 0.0) + y2 = (cy[(i - 2)] if (i >= 2) else 0.0) + cy[i] = (((((1.0 - (a / 2.0)) * (1.0 - (a / 2.0))) * ((sm[i] - (2.0 * s1)) + s2)) + ((2.0 * (1.0 - a)) * y1)) - (((1.0 - a) * (1.0 - a)) * y2)) + cyc[i] = cy[i] + if (i >= 7): + out[i] = cy[i] + return out + +def ind_adaptive_rsi(closes, period=14): + n = len(closes) + out = [float("nan")] * (n) + if (n < 12): + return out + ag = 0.0 + al = 0.0 + have = False + for i in range(1, n): + d = (closes[i] - closes[(i - 1)]) + g = (d if (d > 0) else 0.0) + l = ((-d) if (d < 0) else 0.0) + eff = 0.0 + if (i >= 10): + dir = abs((closes[i] - closes[(i - 10)])) + vol = 0.0 + for k in range((i - 9), (i + 1)): + vol += abs((closes[k] - closes[(k - 1)])) + eff = (0.0 if (vol == 0.0) else (dir / vol)) + p = int(round((5.0 + ((1.0 - eff) * 25.0)))) + if (p < 5): + p = 5 + if (p > 30): + p = 30 + a = (1.0 / p) + if (not have): + if (i >= int(period)): + sg = 0.0 + sl = 0.0 + for k in range(((i - int(period)) + 1), (i + 1)): + dd = (closes[k] - closes[(k - 1)]) + sg += (dd if (dd > 0) else 0.0) + sl += ((-dd) if (dd < 0) else 0.0) + ag = (sg / period) + al = (sl / period) + have = True + else: + continue + else: + ag = ((a * g) + ((1.0 - a) * ag)) + al = ((a * l) + ((1.0 - a) * al)) + den = (ag + al) + out[i] = (50.0 if (den == 0.0) else ((100.0 * ag) / den)) + return out + +def ind_alligator_jaw(closes, period, shift): + s = list(smma_v(closes, period)) + o = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if ((i >= int(shift)) and math.isfinite(s[(i - int(shift))])): + o[i] = s[(i - int(shift))] + return o + +def ind_alligator_lips(closes, period, shift): + s = list(smma_v(closes, period)) + o = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if ((i >= int(shift)) and math.isfinite(s[(i - int(shift))])): + o[i] = s[(i - int(shift))] + return o + +def ind_alligator_teeth(closes, period, shift): + s = list(smma_v(closes, period)) + o = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if ((i >= int(shift)) and math.isfinite(s[(i - int(shift))])): + o[i] = s[(i - int(shift))] + return o + +def ind_anchored_vwap(series, period=50): + tp = list(_typical(series)) + o = [float("nan")] * (len(series)) + anchor = int(max(0, (period - 1))) + if (anchor >= len(series)): + anchor = ((len(series) - 1) if (len(series) > 0) else 0) + pv = 0.0 + vv = 0.0 + for i in range(anchor, len(series)): + pv += (tp[i] * series[i][4]) + vv += series[i][4] + if (vv != 0.0): + o[i] = (pv / vv) + return o + +def ind_aroon_down(series, period): + o = [float("nan")] * (len(series)) + lo = list(_lows(series)) + for i in range(0, len(series)): + if ((i + 1) < int(period)): + continue + since = 0 + m = 1e300 + for j in range(0, period): + if (lo[(i - int(j))] <= m): + m = lo[(i - int(j))] + since = j + o[i] = ((100.0 * (period - since)) / period) + return o + +def ind_aroon_osc(series, period): + o = [float("nan")] * (len(series)) + hi = list(_highs(series)) + lo = list(_lows(series)) + for i in range(0, len(series)): + if ((i + 1) < int(period)): + continue + su = 0 + sd = 0 + m = (-1e300) + for j in range(0, period): + if (hi[(i - int(j))] >= m): + m = hi[(i - int(j))] + su = j + m = 1e300 + for j in range(0, period): + if (lo[(i - int(j))] <= m): + m = lo[(i - int(j))] + sd = j + o[i] = ((100.0 * (sd - su)) / period) + return o + +def ind_aroon_up(series, period): + o = [float("nan")] * (len(series)) + hi = list(_highs(series)) + for i in range(0, len(series)): + if ((i + 1) < int(period)): + continue + since = 0 + m = (-1e300) + for j in range(0, period): + if (hi[(i - int(j))] >= m): + m = hi[(i - int(j))] + since = j + o[i] = ((100.0 * (period - since)) / period) + return o + +def ind_autocorrelation(series, period=20): + lr = list(logret(_closes(series))) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (i < int(period)): + continue + mean = 0.0 + n = 0 + for j in range(0, period): + if math.isfinite(lr[(i - int(j))]): + mean += lr[(i - int(j))] + n += 1 + if (n < period): + continue + mean /= n + num = 0.0 + den = 0.0 + for j in range(0, period): + d = (lr[(i - int(j))] - mean) + den += (d * d) + for j in range(1, period): + num += ((lr[(i - int(j))] - mean) * (lr[((i - int(j)) - 1)] - mean)) + o[i] = ((num / den) if (den != 0.0) else 0.0) + return o + +def ind_awesome_oscillator(s, fast=5, slow=34): + h = list(_highs(s)) + l = list(_lows(s)) + med = [float("nan")] * (len(h)) + for i in range(0, len(h)): + med[i] = ((h[i] + l[i]) / 2.0) + f = list(sma_30e386ad(med, fast)) + sl = list(sma_30e386ad(med, slow)) + out = [float("nan")] * (len(med)) + for i in range(0, len(med)): + if (math.isfinite(f[i]) and math.isfinite(sl[i])): + out[i] = (f[i] - sl[i]) + return out + +def ind_balance_of_power(s, period=14): + o = list(_opens(s)) + c = list(_closes(s)) + h = list(_highs(s)) + l = list(_lows(s)) + bop = [float("nan")] * (len(c)) + for i in range(0, len(c)): + bop[i] = (0.0 if (h[i] == l[i]) else ((c[i] - o[i]) / (h[i] - l[i]))) + return sma_30e386ad(bop, period) + +def ind_bear_power(s, period=13): + l = list(_lows(s)) + c = list(_closes(s)) + e = list(ema_51fe74d0(c, period)) + out = [float("nan")] * (len(c)) + for i in range(0, len(c)): + if math.isfinite(e[i]): + out[i] = (l[i] - e[i]) + return out + +def ind_bollinger_bands(series, period=20, mult=2.0): + c = list(_closes(series)) + m = list(sma_58520e20(c, period)) + sd = list(stddev_7bc07ae7(c, period)) + r = SimpleNamespace(upper=[], middle=[], lower=[]) + r.upper = [float("nan")] * (len(series)) + r.middle = list(m) + r.lower = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if math.isfinite(m[i]): + r.upper[i] = (m[i] + (mult * sd[i])) + r.lower[i] = (m[i] - (mult * sd[i])) + return r + +def ind_bollinger_bandwidth(series, period=20, mult=2.0): + c = list(_closes(series)) + m = list(sma_58520e20(c, period)) + sd = list(stddev_7bc07ae7(c, period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (math.isfinite(m[i]) and (m[i] != 0.0)): + o[i] = (((2.0 * mult) * sd[i]) / m[i]) + return o + +def ind_bollinger_percent_b(series, period=20, mult=2.0): + c = list(_closes(series)) + m = list(sma_58520e20(c, period)) + sd = list(stddev_7bc07ae7(c, period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if math.isfinite(m[i]): + up = (m[i] + (mult * sd[i])) + lo = (m[i] - (mult * sd[i])) + if (up != lo): + o[i] = ((series[i][3] - lo) / (up - lo)) + return o + +def ind_bull_power(s, period=13): + h = list(_highs(s)) + c = list(_closes(s)) + e = list(ema_51fe74d0(c, period)) + out = [float("nan")] * (len(c)) + for i in range(0, len(c)): + if math.isfinite(e[i]): + out[i] = (h[i] - e[i]) + return out + +def ind_cci(s, period=20): + tp = list(_typical(s)) + m = list(sma_30e386ad(tp, period)) + out = [float("nan")] * (len(tp)) + for i in range(0, len(tp)): + if (not math.isfinite(m[i])): + continue + ok = True + for k in range(0, period): + if (not math.isfinite(tp[(i - int(k))])): + ok = False + if (not ok): + continue + md = 0.0 + for k in range(0, period): + md += abs((tp[(i - int(k))] - m[i])) + md /= period + out[i] = (0.0 if (md == 0.0) else ((tp[i] - m[i]) / (0.015 * md))) + return out + +def ind_camarilla_pivot_points(series, period=1): + r = SimpleNamespace(pivot=[], r1=[], s1=[]) + r.pivot = [float("nan")] * (len(series)) + r.r1 = [float("nan")] * (len(series)) + r.s1 = [float("nan")] * (len(series)) + for i in range(1, len(series)): + range_ = (series[(i - 1)][1] - series[(i - 1)][2]) + p = (((series[(i - 1)][1] + series[(i - 1)][2]) + series[(i - 1)][3]) / 3.0) + r.pivot[i] = p + r.r1[i] = (series[(i - 1)][3] + ((range_ * 1.1) / 12.0)) + r.s1[i] = (series[(i - 1)][3] - ((range_ * 1.1) / 12.0)) + return r + +def ind_center_of_gravity(closes, period=10): + n = len(closes) + out = [float("nan")] * (n) + for i in range(int((period - 1)), n): + num = 0.0 + den = 0.0 + for k in range(0, period): + w = float((k + 1)) + num += (w * closes[(i - int(k))]) + den += closes[(i - int(k))] + out[i] = (0.0 if (den == 0.0) else ((-num) / den)) + return out + +def ind_chaikin_money_flow(series, period=20): + mf = [0.0] * (len(series)) + vol = [0.0] * (len(series)) + for i in range(0, len(series)): + range_ = (series[i][1] - series[i][2]) + clv = ((((series[i][3] - series[i][2]) - (series[i][1] - series[i][3])) / range_) if (range_ != 0.0) else 0.0) + mf[i] = (clv * series[i][4]) + vol[i] = series[i][4] + sm = list(sma_58520e20(mf, period)) + sv = list(sma_58520e20(vol, period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (math.isfinite(sm[i]) and (sv[i] != 0.0)): + o[i] = (sm[i] / sv[i]) + return o + +def ind_chaikin_oscillator(series, period=14): + adl = [0.0] * (len(series)) + acc = 0.0 + for i in range(0, len(series)): + range_ = (series[i][1] - series[i][2]) + clv = ((((series[i][3] - series[i][2]) - (series[i][1] - series[i][3])) / range_) if (range_ != 0.0) else 0.0) + acc += (clv * series[i][4]) + adl[i] = acc + fast = list(ema_239a7b94(adl, 3)) + slow = list(ema_239a7b94(adl, 10)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (math.isfinite(fast[i]) and math.isfinite(slow[i])): + o[i] = (fast[i] - slow[i]) + return o + +def ind_chaikin_volatility(series, period=10): + hl = [0.0] * (len(series)) + for i in range(0, len(series)): + hl[i] = (series[i][1] - series[i][2]) + e = list(ema_239a7b94(hl, period)) + o = [float("nan")] * (len(series)) + for i in range(int(period), len(series)): + if ((math.isfinite(e[i]) and math.isfinite(e[(i - int(period))])) and (e[(i - int(period))] != 0.0)): + o[i] = ((100.0 * (e[i] - e[(i - int(period))])) / e[(i - int(period))]) + return o + +def ind_chande_forecast_oscillator(closes, period=5): + out = [float("nan")] * (len(closes)) + for i in range(int((period - 1)), len(closes)): + if (closes[i] == 0.0): + continue + out[i] = ((100.0 * (closes[i] - linreg_value_at(closes, i, period))) / closes[i]) + return out + +def ind_chande_kroll_stop(series, period, mult): + atr = list(atr_v(series, period)) + o = [float("nan")] * (len(series)) + hi = list(_highs(series)) + for i in range(0, len(series)): + if (((i + 1) >= int(period)) and math.isfinite(atr[i])): + o[i] = (highest_v(hi, i, period) - (mult * atr[i])) + return o + +def ind_chande_momentum_oscillator(closes, period=20): + n = len(closes) + out = [float("nan")] * (n) + for i in range(int(period), n): + up = 0.0 + dn = 0.0 + for k in range(((i - int(period)) + 1), (i + 1)): + d = (closes[k] - closes[(k - 1)]) + if (d > 0): + up += d + else: + dn -= d + out[i] = (0.0 if ((up + dn) == 0.0) else ((100.0 * (up - dn)) / (up + dn))) + return out + +def ind_chandelier_exit(series, period=22, mult=3.0): + h = list(_highs(series)) + l = list(_lows(series)) + a = list(atr(series, period)) + r = SimpleNamespace(long_exit=[], short_exit=[]) + r.long_exit = list(hh(h, period)) + r.short_exit = list(ll(l, period)) + for i in range(0, len(series)): + if (math.isfinite(r.long_exit[i]) and math.isfinite(a[i])): + r.long_exit[i] = (r.long_exit[i] - (mult * a[i])) + if (math.isfinite(r.short_exit[i]) and math.isfinite(a[i])): + r.short_exit[i] = (r.short_exit[i] + (mult * a[i])) + return r + +def ind_chandelier_long(series, period, mult): + atr = list(atr_v(series, period)) + o = [float("nan")] * (len(series)) + hi = list(_highs(series)) + for i in range(0, len(series)): + if (((i + 1) >= int(period)) and math.isfinite(atr[i])): + o[i] = (highest_v(hi, i, period) - (mult * atr[i])) + return o + +def ind_chandelier_short(series, period, mult): + atr = list(atr_v(series, period)) + o = [float("nan")] * (len(series)) + lo = list(_lows(series)) + for i in range(0, len(series)): + if (((i + 1) >= int(period)) and math.isfinite(atr[i])): + o[i] = (lowest_v(lo, i, period) + (mult * atr[i])) + return o + +def ind_chikou_span(closes, period): + o = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if ((i + int(period)) < len(closes)): + o[i] = closes[(i + int(period))] + return o + +def ind_choppiness_index(s, period=14): + n = len(s) + out = [float("nan")] * (n) + for i in range(int((period - 1)), n): + tr = 0.0 + hh = (-1e300) + ll = 1e300 + for k in range(0, period): + j = (i - int(k)) + h = s[j][1] + l = s[j][2] + t = (h - l) + if (j > 0): + t = max(t, abs((h - s[(j - 1)][3]))) + t = max(t, abs((l - s[(j - 1)][3]))) + tr += t + hh = max(hh, h) + ll = min(ll, l) + range_ = (hh - ll) + if ((range_ <= 0.0) or (tr <= 0.0)): + continue + out[i] = ((100.0 * math.log10((tr / range_))) / math.log10(float(period))) + return out + +def ind_close_volatility(series, period=20): + lr = list(logret(_closes(series))) + sd = list(stddev_7bc07ae7(lr, period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if math.isfinite(sd[i]): + o[i] = (100.0 * sd[i]) + return o + +def ind_connors_rsi(s, period=3): + n = len(s) + out = [float("nan")] * (n) + closes = list(_closes(s)) + r1 = list(rsi_series(closes, 3)) + streak = [0.0] * (n) + for i in range(1, n): + if (closes[i] > closes[(i - 1)]): + streak[i] = ((streak[(i - 1)] + 1) if (streak[(i - 1)] >= 0) else 1) + elif (closes[i] < closes[(i - 1)]): + streak[i] = ((streak[(i - 1)] - 1) if (streak[(i - 1)] <= 0) else (-1)) + else: + streak[i] = 0 + r2 = list(rsi_series(streak, 2)) + roc = [float("nan")] * (n) + for i in range(1, n): + roc[i] = ((100.0 * (closes[i] - closes[(i - 1)])) / closes[(i - 1)]) + for i in range(0, n): + if (((not math.isfinite(r1[i])) or (not math.isfinite(r2[i]))) or (i < 100)): + continue + cnt = 0 + for k in range(0, 100): + if (math.isfinite(roc[(i - int(k))]) and (roc[(i - int(k))] <= roc[i])): + cnt += 1 + out[i] = (((r1[i] + r2[i]) + cnt) / 3.0) + return out + +def ind_coppock_curve(closes, roc1=14, roc2=11, wma=10): + out = [float("nan")] * (len(closes)) + def roc(p): + o = [float("nan")] * (len(closes)) + for i in range(int(p), len(closes)): + if (closes[(i - int(p))] != 0.0): + o[i] = ((100.0 * (closes[i] - closes[(i - int(p))])) / closes[(i - int(p))]) + return o + a = roc(roc1) + b = roc(roc2) + sum_ = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if (math.isfinite(a[i]) and math.isfinite(b[i])): + sum_[i] = (a[i] + b[i]) + wsum = ((float(wma) * (wma + 1)) / 2.0) + for i in range(int((wma - 1)), len(closes)): + s = 0.0 + ok = True + for k in range(0, wma): + if (not math.isfinite(sum_[(i - int(k))])): + ok = False + s += ((wma - k) * sum_[(i - int(k))]) + if ok: + out[i] = (s / wsum) + return out + +def ind_correlation(series, period=20): + c = list(_closes(series)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (i < int((period - 1))): + continue + mx = ((period - 1) / 2.0) + my = 0.0 + for j in range(0, period): + my += c[(i - int(j))] + my /= period + num = 0.0 + dx = 0.0 + dy = 0.0 + for j in range(0, period): + x = (j - mx) + y = (c[((i - int((period - 1))) + int(j))] - my) + num += (x * y) + dx += (x * x) + dy += (y * y) + den = math.sqrt((dx * dy)) + o[i] = ((num / den) if (den != 0.0) else 0.0) + return o + +def ind_correlation_coefficient(closes, period=14): + out = [float("nan")] * (len(closes)) + for i in range(int((period - 1)), len(closes)): + mx = 0.0 + my = 0.0 + for k in range(0, period): + mx += closes[((i - int((period - 1))) + int(k))] + my += float((k + 1)) + mx /= period + my /= period + sxy = 0.0 + sxx = 0.0 + syy = 0.0 + for k in range(0, period): + dx = (closes[((i - int((period - 1))) + int(k))] - mx) + dy = (float((k + 1)) - my) + sxy += (dx * dy) + sxx += (dx * dx) + syy += (dy * dy) + out[i] = (0.0 if ((sxx == 0.0) or (syy == 0.0)) else (sxy / math.sqrt((sxx * syy)))) + return out + +def ind_covariance(series, period=20): + c = list(_closes(series)) + v = list(_volumes(series)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (i < int((period - 1))): + continue + mc = 0.0 + mv = 0.0 + for j in range(0, period): + mc += c[(i - int(j))] + mv += v[(i - int(j))] + mc /= period + mv /= period + s = 0.0 + for j in range(0, period): + s += ((c[(i - int(j))] - mc) * (v[(i - int(j))] - mv)) + o[i] = (s / period) + return o + +def ind_cumulative_volume_delta(series, period=1): + o = [float("nan")] * (len(series)) + acc = 0.0 + for i in range(0, len(series)): + range_ = (series[i][1] - series[i][2]) + clv = ((((series[i][3] - series[i][2]) - (series[i][1] - series[i][3])) / range_) if (range_ != 0.0) else 0.0) + acc += (clv * series[i][4]) + o[i] = acc + return o + +def ind_cutler_rsi(closes, period=14): + n = len(closes) + out = [float("nan")] * (n) + if ((n < int((period + 1))) or (period <= 0)): + return out + g = [0.0] * (n) + l = [0.0] * (n) + for i in range(1, n): + d = (closes[i] - closes[(i - 1)]) + g[i] = (d if (d > 0) else 0.0) + l[i] = ((-d) if (d < 0) else 0.0) + ag = list(sma_30e386ad(g, period)) + al = list(sma_30e386ad(l, period)) + for i in range(0, n): + if ((not math.isfinite(ag[i])) or (not math.isfinite(al[i]))): + continue + den = (ag[i] + al[i]) + out[i] = (50.0 if (den == 0.0) else ((100.0 * ag[i]) / den)) + return out + +def ind_cyber_cycle(closes, dummy=0): + n = len(closes) + out = [float("nan")] * (n) + a = 0.07 + sm = [0.0] * (n) + cy = [0.0] * (n) + for i in range(0, n): + c0 = closes[i] + c1 = (closes[(i - 1)] if (i >= 1) else c0) + c2 = (closes[(i - 2)] if (i >= 2) else c0) + c3 = (closes[(i - 3)] if (i >= 3) else c0) + sm[i] = ((((c0 + (2.0 * c1)) + (2.0 * c2)) + c3) / 6.0) + s1 = (sm[(i - 1)] if (i >= 1) else sm[i]) + s2 = (sm[(i - 2)] if (i >= 2) else sm[i]) + y1 = (cy[(i - 1)] if (i >= 1) else 0.0) + y2 = (cy[(i - 2)] if (i >= 2) else 0.0) + cy[i] = (((((1.0 - (a / 2.0)) * (1.0 - (a / 2.0))) * ((sm[i] - (2.0 * s1)) + s2)) + ((2.0 * (1.0 - a)) * y1)) - (((1.0 - a) * (1.0 - a)) * y2)) + if (i >= 7): + out[i] = cy[i] + return out + +def ind_dema(closes, period): + e1 = list(ema_v(closes, period)) + e2 = list(ema_v(e1, period)) + o = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if (math.isfinite(e1[i]) and math.isfinite(e2[i])): + o[i] = ((2.0 * e1[i]) - e2[i]) + return o + +def ind_dpo(closes, period): + sma = list(sma_v(closes, period)) + o = [float("nan")] * (len(closes)) + shift = ((period // 2) + 1) + for i in range(0, len(closes)): + if (i < int(shift)): + continue + if math.isfinite(sma[(i - int(shift))]): + o[i] = (closes[i] - sma[(i - int(shift))]) + return o + +def ind_dss(s, period=10, smooth=3): + h = list(_highs(s)) + l = list(_lows(s)) + c = list(_closes(s)) + k = list(stoch_k(h, l, c, period)) + return ema_51fe74d0(ema_51fe74d0(k, smooth), smooth) + +def ind_dx(series, period): + return dx_v(series, period) + +def ind_demarker(s, period=14): + n = len(s) + dmax = [0.0] * (n) + dmin = [0.0] * (n) + for i in range(1, n): + up = (s[i][1] - s[(i - 1)][1]) + dn = (s[(i - 1)][2] - s[i][2]) + dmax[i] = (up if ((up > 0.0) and (up > dn)) else 0.0) + dmin[i] = (dn if ((dn > 0.0) and (dn > up)) else 0.0) + amax = list(sma_30e386ad(dmax, period)) + amin = list(sma_30e386ad(dmin, period)) + out = [float("nan")] * (n) + for i in range(0, n): + if ((not math.isfinite(amax[i])) or (not math.isfinite(amin[i]))): + continue + den = (amax[i] + amin[i]) + out[i] = (50.0 if (den == 0.0) else ((100.0 * amax[i]) / den)) + return out + +def ind_decycler(closes, period=10): + hp = [float("nan")] * (len(closes)) + m48 = list(sma_30e386ad(closes, 48)) + for i in range(0, len(closes)): + if math.isfinite(m48[i]): + hp[i] = (closes[i] - m48[i]) + ss = list(super_smoother(hp, period)) + out = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if (math.isfinite(ss[i]) and math.isfinite(m48[i])): + out[i] = (ss[i] + m48[i]) + return out + +def ind_demand_index(series, period=14): + bp = [0.0] * (len(series)) + sp = [0.0] * (len(series)) + for i in range(0, len(series)): + range_ = (series[i][1] - series[i][2]) + clv = ((((series[i][3] - series[i][2]) - (series[i][1] - series[i][3])) / range_) if (range_ != 0.0) else 0.0) + mf = (clv * series[i][4]) + if (mf >= 0): + bp[i] = mf + else: + sp[i] = (-mf) + sbp = list(sma_58520e20(bp, period)) + ssp = list(sma_58520e20(sp, period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + tot = (sbp[i] + ssp[i]) + if (math.isfinite(sbp[i]) and (tot != 0.0)): + o[i] = ((100.0 * (sbp[i] - ssp[i])) / tot) + return o + +def ind_detrended_price_oscillator(closes, period=20): + m = list(sma_30e386ad(closes, period)) + shift = ((period // 2) + 1) + out = [float("nan")] * (len(closes)) + for i in range(int(shift), len(closes)): + j = (i - int(shift)) + if math.isfinite(m[j]): + out[i] = (closes[i] - m[j]) + return out + +def ind_disparity_index(closes, period=20): + m = list(sma_30e386ad(closes, period)) + out = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if (math.isfinite(m[i]) and (m[i] != 0.0)): + out[i] = ((100.0 * (closes[i] - m[i])) / m[i]) + return out + +def ind_dominant_cycle(closes, dummy=0): + n = len(closes) + out = [float("nan")] * (n) + a = 0.07 + sm = [0.0] * (n) + cy = [0.0] * (n) + for i in range(0, n): + c0 = closes[i] + c1 = (closes[(i - 1)] if (i >= 1) else c0) + c2 = (closes[(i - 2)] if (i >= 2) else c0) + c3 = (closes[(i - 3)] if (i >= 3) else c0) + sm[i] = ((((c0 + (2.0 * c1)) + (2.0 * c2)) + c3) / 6.0) + s1 = (sm[(i - 1)] if (i >= 1) else sm[i]) + s2 = (sm[(i - 2)] if (i >= 2) else sm[i]) + y1 = (cy[(i - 1)] if (i >= 1) else 0.0) + y2 = (cy[(i - 2)] if (i >= 2) else 0.0) + cy[i] = (((((1.0 - (a / 2.0)) * (1.0 - (a / 2.0))) * ((sm[i] - (2.0 * s1)) + s2)) + ((2.0 * (1.0 - a)) * y1)) - (((1.0 - a) * (1.0 - a)) * y2)) + for i in range(50, n): + cross = 0 + for k in range((i - 49), (i + 1)): + if ((cy[k] >= 0.0) != (cy[(k - 1)] >= 0.0)): + cross += 1 + p = (20.0 if (cross == 0) else (100.0 / cross)) + if (p < 10.0): + p = 10.0 + if (p > 40.0): + p = 40.0 + out[i] = p + return out + +def ind_dominant_cycle_period(series, period=50): + c = list(_closes(series)) + m = list(sma_58520e20(c, 10)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if ((i < int((period - 1))) or (not math.isfinite(m[i]))): + continue + crossings = 0 + prev = 0.0 + have_prev = False + for j in range((i - int((period - 1))), (i + 1)): + if (not math.isfinite(m[j])): + continue + d = (c[j] - m[j]) + if (have_prev and (((prev < 0) and (d >= 0)) or ((prev > 0) and (d <= 0)))): + crossings += 1 + prev = d + have_prev = True + if (crossings > 0): + o[i] = ((2.0 * period) / crossings) + return o + +def ind_donchian_channels(series, period=20): + h = list(_highs(series)) + l = list(_lows(series)) + r = SimpleNamespace(upper=[], middle=[], lower=[]) + r.upper = list(hh(h, period)) + r.lower = list(ll(l, period)) + r.middle = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if math.isfinite(r.upper[i]): + r.middle[i] = ((r.upper[i] + r.lower[i]) / 2.0) + return r + +def ind_donchian_lower(series, period): + o = [float("nan")] * (len(series)) + lo = list(_lows(series)) + for i in range(0, len(series)): + if ((i + 1) >= int(period)): + o[i] = lowest_v(lo, i, period) + return o + +def ind_donchian_middle(series, period): + o = [float("nan")] * (len(series)) + hi = list(_highs(series)) + lo = list(_lows(series)) + for i in range(0, len(series)): + if ((i + 1) >= int(period)): + o[i] = ((highest_v(hi, i, period) + lowest_v(lo, i, period)) / 2.0) + return o + +def ind_donchian_upper(series, period): + o = [float("nan")] * (len(series)) + hi = list(_highs(series)) + for i in range(0, len(series)): + if ((i + 1) >= int(period)): + o[i] = highest_v(hi, i, period) + return o + +def ind_double_stochastic(s, period=14, short_period=5, smooth=3): + h = list(_highs(s)) + l = list(_lows(s)) + c = list(_closes(s)) + k1 = list(stoch_k(h, l, c, period)) + k2 = list(stoch_k(h, l, c, short_period)) + avg = [float("nan")] * (len(c)) + for i in range(0, len(c)): + if (math.isfinite(k1[i]) and math.isfinite(k2[i])): + avg[i] = ((k1[i] + k2[i]) / 2.0) + return sma_30e386ad(avg, smooth) + +def ind_dynamic_momentum_index(closes, period=14): + n = len(closes) + out = [float("nan")] * (n) + if (n < 15): + return out + sd5 = list(stddev_8463129b(closes, 5)) + sd14 = list(stddev_8463129b(closes, 14)) + ag = 0.0 + al = 0.0 + have = False + for i in range(1, n): + d = (closes[i] - closes[(i - 1)]) + g = (d if (d > 0) else 0.0) + l = ((-d) if (d < 0) else 0.0) + ratio = 1.0 + if ((math.isfinite(sd5[i]) and math.isfinite(sd14[i])) and (sd14[i] != 0.0)): + ratio = (sd5[i] / sd14[i]) + p = int(round((period * ratio))) + if (p < 5): + p = 5 + if (p > 30): + p = 30 + a = (1.0 / p) + if (not have): + if (i >= int(period)): + sg = 0.0 + sl = 0.0 + for k in range(((i - int(period)) + 1), (i + 1)): + dd = (closes[k] - closes[(k - 1)]) + sg += (dd if (dd > 0) else 0.0) + sl += ((-dd) if (dd < 0) else 0.0) + ag = (sg / period) + al = (sl / period) + have = True + else: + continue + else: + ag = ((a * g) + ((1.0 - a) * ag)) + al = ((a * l) + ((1.0 - a) * al)) + den = (ag + al) + out[i] = (50.0 if (den == 0.0) else ((100.0 * ag) / den)) + return out + +def ind_ema(closes, period): + return ema_v(closes, period) + +def ind_ease_of_movement(series, period=14): + raw = [0.0] * (len(series)) + for i in range(1, len(series)): + mid = ((series[i][1] + series[i][2]) / 2.0) + pmid = ((series[(i - 1)][1] + series[(i - 1)][2]) / 2.0) + box = ((series[i][4] / 1000000.0) / (series[i][1] - series[i][2])) + if (box != 0.0): + raw[i] = ((mid - pmid) / box) + return sma_58520e20(raw, period) + +def ind_efficiency_ratio(series, period=10): + c = list(_closes(series)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (i < int(period)): + continue + net = abs((c[i] - c[(i - int(period))])) + tot = 0.0 + for j in range(0, period): + tot += abs((c[(i - int(j))] - c[((i - int(j)) - 1)])) + o[i] = ((net / tot) if (tot != 0.0) else 0.0) + return o + +def ind_ehlers_decycler(closes, period): + o = [float("nan")] * (len(closes)) + if (period < 2): + period = 2 + pi = 3.141592653589793 + w = (((0.707 * 2.0) * pi) / period) + a1 = (((math.cos(w) + math.sin(w)) - 1.0) / math.sin(w)) + def px(i, lag): + return (closes[(i - lag)] if (i >= lag) else closes[0]) + hp1 = 0.0 + hp2 = 0.0 + dec_prev = 0.0 + c = (1.0 - (a1 / 2.0)) + for i in range(0, len(closes)): + hp = ((((c * c) * ((px(i, 0) - (2.0 * px(i, 1))) + px(i, 2))) + ((2.0 * (1.0 - a1)) * hp1)) - (((1.0 - a1) * (1.0 - a1)) * hp2)) + dec = (((a1 / 2.0) * (hp + hp1)) + ((1.0 - a1) * dec_prev)) + hp2 = hp1 + hp1 = hp + dec_prev = dec + o[i] = dec + return o + +def ind_ehlers_smoothed_rsi(closes, period=14): + rsi = list(rsi_series(closes, period)) + return super_smoother(rsi, period) + +def ind_ehlers_super_smoother(closes, period): + o = [float("nan")] * (len(closes)) + if (period < 2): + period = 2 + if (len(closes) < 3): + return o + pi = 3.141592653589793 + a1 = math.exp((((-1.4142135623730951) * pi) / period)) + b1 = ((2.0 * a1) * math.cos(((1.4142135623730951 * pi) / period))) + c2 = b1 + c3 = ((-a1) * a1) + c1 = ((1.0 - c2) - c3) + s1 = closes[1] + s2 = closes[0] + for i in range(2, len(closes)): + v = ((((c1 * (closes[i] + closes[(i - 1)])) / 2.0) + (c2 * s1)) + (c3 * s2)) + s2 = s1 + s1 = v + o[i] = v + return o + +def ind_ehlers_trendline(closes, alpha): + o = [float("nan")] * (len(closes)) + a = alpha + c1 = (a - ((a * a) / 4.0)) + c2 = ((0.5 * a) * a) + c3 = (a - ((0.75 * a) * a)) + c4 = (2.0 * (1.0 - a)) + c5 = ((1.0 - a) * (1.0 - a)) + def px(i, lag): + return (closes[(i - lag)] if (i >= lag) else closes[0]) + def pv(i, lag): + return (o[(i - lag)] if ((i >= lag) and math.isfinite(o[(i - lag)])) else 0.0) + for i in range(0, len(closes)): + if (i < 2): + o[i] = closes[i] + continue + o[i] = (((((c1 * px(i, 0)) + (c2 * px(i, 1))) - (c3 * px(i, 2))) + (c4 * pv(i, 1))) - (c5 * pv(i, 2))) + return o + +def ind_elder_force_index(s, period=13): + c = list(_closes(s)) + v = list(_volumes(s)) + f = [float("nan")] * (len(c)) + for i in range(1, len(c)): + f[i] = ((c[i] - c[(i - 1)]) * v[i]) + return ema_51fe74d0(f, period) + +def ind_elder_impulse(s, ema_period=13, fast=12, slow=26): + c = list(_closes(s)) + e = list(ema_51fe74d0(c, ema_period)) + ef = list(ema_51fe74d0(c, fast)) + es = list(ema_51fe74d0(c, slow)) + macd = [float("nan")] * (len(c)) + for i in range(0, len(c)): + if (math.isfinite(ef[i]) and math.isfinite(es[i])): + macd[i] = (ef[i] - es[i]) + hist = list(ema_51fe74d0(macd, 9)) + sig = [float("nan")] * (len(c)) + for i in range(0, len(c)): + if (math.isfinite(macd[i]) and math.isfinite(hist[i])): + sig[i] = (macd[i] - hist[i]) + out = [float("nan")] * (len(c)) + for i in range(2, len(c)): + if ((((not math.isfinite(e[i])) or (not math.isfinite(e[(i - 1)]))) or (not math.isfinite(sig[i]))) or (not math.isfinite(sig[(i - 1)]))): + continue + up = ((e[i] > e[(i - 1)]) and (sig[i] > sig[(i - 1)])) + dn = ((e[i] < e[(i - 1)]) and (sig[i] < sig[(i - 1)])) + out[i] = (1.0 if up else ((-1.0) if dn else 0.0)) + return out + +def ind_elder_ray_bear(series, period): + ema = list(ema_v(_closes(series), period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if math.isfinite(ema[i]): + o[i] = (series[i][2] - ema[i]) + return o + +def ind_elder_ray_bull(series, period): + ema = list(ema_v(_closes(series), period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if math.isfinite(ema[i]): + o[i] = (series[i][1] - ema[i]) + return o + +def ind_elder_safe_zone(series, period, mult): + atr = list(atr_v(series, period)) + o = [float("nan")] * (len(series)) + lo = list(_lows(series)) + for i in range(0, len(series)): + if (((i + 1) >= int(period)) and math.isfinite(atr[i])): + o[i] = (lowest_v(lo, i, period) - (mult * atr[i])) + return o + +def ind_ergodic_oscillator(closes, long_period=5, short_period=3): + mom = [float("nan")] * (len(closes)) + absmom = [float("nan")] * (len(closes)) + for i in range(1, len(closes)): + mom[i] = (closes[i] - closes[(i - 1)]) + absmom[i] = abs(mom[i]) + num = list(ema_51fe74d0(ema_51fe74d0(mom, long_period), short_period)) + den = list(ema_51fe74d0(ema_51fe74d0(absmom, long_period), short_period)) + out = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if ((math.isfinite(num[i]) and math.isfinite(den[i])) and (den[i] != 0.0)): + out[i] = ((100.0 * num[i]) / den[i]) + return out + +def ind_even_better_sinewave(closes, period=10, hp_period=48): + hp = [float("nan")] * (len(closes)) + m = list(sma_30e386ad(closes, hp_period)) + for i in range(0, len(closes)): + if math.isfinite(m[i]): + hp[i] = (closes[i] - m[i]) + rf = list(super_smoother(hp, period)) + n = len(closes) + r = SimpleNamespace(sine=[], lead_sine=[]) + r.sine = [float("nan")] * (n) + r.lead_sine = [float("nan")] * (n) + for i in range(1, n): + if ((not math.isfinite(rf[i])) or (not math.isfinite(rf[(i - 1)]))): + continue + q = (rf[i] - rf[(i - 1)]) + mag = math.sqrt(((rf[i] * rf[i]) + (q * q))) + if (mag == 0.0): + continue + r.sine[i] = (rf[i] / mag) + r.lead_sine[i] = (q / mag) + return r + +def ind_fama(closes, fastlimit, slowlimit): + det = [0.0] * (len(closes)) + def cp(i, lag): + return (closes[(i - lag)] if (i >= lag) else closes[0]) + def dp(i, lag): + return (det[(i - lag)] if (i >= lag) else 0.0) + for i in range(0, len(closes)): + det[i] = (((((0.0962 * cp(i, 0)) + (0.5769 * cp(i, 2))) - (0.5769 * cp(i, 4))) - (0.0962 * cp(i, 6))) * 0.54) + alpha = [slowlimit] * (len(closes)) + for i in range(0, len(closes)): + q1 = ((((0.0962 * det[i]) + (0.5769 * dp(i, 2))) - (0.5769 * dp(i, 4))) - (0.0962 * dp(i, 6))) + i1 = dp(i, 3) + phase = math.atan2(q1, i1) + a = (slowlimit + ((fastlimit - slowlimit) * (abs(phase) / 3.141592653589793))) + if (a < slowlimit): + a = slowlimit + if (a > fastlimit): + a = fastlimit + alpha[i] = a + mama = [float("nan")] * (len(closes)) + prev = float("nan") + for i in range(0, len(closes)): + if (not math.isfinite(prev)): + prev = closes[i] + mama[i] = prev + else: + prev = ((alpha[i] * closes[i]) + ((1.0 - alpha[i]) * prev)) + mama[i] = prev + o = [float("nan")] * (len(closes)) + fprev = float("nan") + for i in range(0, len(closes)): + if (not math.isfinite(mama[i])): + continue + if (not math.isfinite(fprev)): + fprev = mama[i] + o[i] = fprev + continue + fa = (0.5 * alpha[i]) + fprev = ((fa * mama[i]) + ((1.0 - fa) * fprev)) + o[i] = fprev + return o + +def ind_frama(closes, period): + o = [float("nan")] * (len(closes)) + if (period < 2): + period = 2 + half = (period // 2) + prev = float("nan") + for i in range(0, len(closes)): + if ((i + 1) < int(period)): + continue + n1 = (highest_v(closes, i, half) - lowest_v(closes, i, half)) + n2 = 0.0 + for j in range((((i + 1) - int(half)) + 1), (i + 1)): + n2 += abs((closes[j] - closes[(j - 1)])) + n3 = 0.0 + for j in range((((i + 1) - int(period)) + 1), ((i - int(half)) + 1)): + n3 += abs((closes[j] - closes[(j - 1)])) + n = (((n1 + n2) + n3) / 2.0) + hh = highest_v(closes, i, period) + ll = lowest_v(closes, i, period) + dim = (((math.log(n) - math.log((hh - ll))) / math.log(2.0)) if ((n > 0.0) and ((hh - ll) > 0.0)) else 1.0) + alpha = math.exp(((-4.6) * (dim - 1.0))) + if (alpha < 0.01): + alpha = 0.01 + if (alpha > 1.0): + alpha = 1.0 + if (not math.isfinite(prev)): + prev = closes[i] + o[i] = prev + continue + prev = (prev + (alpha * (closes[i] - prev))) + o[i] = prev + return o + +def ind_fibonacci_pivot_points(series, period=1): + r = SimpleNamespace(pivot=[], r1=[], s1=[]) + r.pivot = [float("nan")] * (len(series)) + r.r1 = [float("nan")] * (len(series)) + r.s1 = [float("nan")] * (len(series)) + for i in range(1, len(series)): + range_ = (series[(i - 1)][1] - series[(i - 1)][2]) + p = (((series[(i - 1)][1] + series[(i - 1)][2]) + series[(i - 1)][3]) / 3.0) + r.pivot[i] = p + r.r1[i] = (p + (0.382 * range_)) + r.s1[i] = (p - (0.382 * range_)) + return r + +def ind_fisher_transform(closes, period=10): + out = [float("nan")] * (len(closes)) + prev = 0.0 + for i in range(0, len(closes)): + if (i < int((period - 1))): + continue + hi = highest(closes, i, period) + lo = lowest(closes, i, period) + x = (0.0 if (hi == lo) else (((2.0 * (closes[i] - lo)) / (hi - lo)) - 1.0)) + if (x > 0.999): + x = 0.999 + if (x < (-0.999)): + x = (-0.999) + f = ((0.5 * math.log(((1.0 + x) / (1.0 - x)))) + (0.5 * prev)) + out[i] = f + prev = f + return out + +def ind_fractal_dimension(series, period=50): + c = list(_closes(series)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (i < int((period - 1))): + continue + mean = 0.0 + for j in range(0, period): + mean += c[(i - int(j))] + mean /= period + mx = (-1e300) + mn = 1e300 + sq = 0.0 + dev = 0.0 + for j in range(0, period): + dev += (c[(i - int(j))] - mean) + mx = max(mx, dev) + mn = min(mn, dev) + d = (c[(i - int(j))] - mean) + sq += (d * d) + sd = math.sqrt((sq / period)) + rs = (((mx - mn) / sd) if (sd > 0) else 0.0) + if (rs > 0): + o[i] = (2.0 - (math.log(rs) / math.log((period / 2.0)))) + return o + +def ind_fractal_dimension_index(closes, period): + o = [float("nan")] * (len(closes)) + if (period < 2): + period = 2 + for i in range(0, len(closes)): + if ((i + 1) < int(period)): + continue + sum_ = 0.0 + for j in range((((i + 1) - int(period)) + 1), (i + 1)): + sum_ += abs((closes[j] - closes[(j - 1)])) + if (sum_ <= 0.0): + o[i] = 1.0 + continue + o[i] = (1.0 + ((math.log(sum_) - math.log(2.0)) / math.log(float(period)))) + return o + +def ind_fractal_down(series): + o = [float("nan")] * (len(series)) + for i in range(2, (len(series) - 2)): + l = series[i][2] + if ((((l < series[(i - 1)][2]) and (l < series[(i - 2)][2])) and (l < series[(i + 1)][2])) and (l < series[(i + 2)][2])): + o[i] = l + return o + +def ind_fractal_up(series): + o = [float("nan")] * (len(series)) + for i in range(2, (len(series) - 2)): + h = series[i][1] + if ((((h > series[(i - 1)][1]) and (h > series[(i - 2)][1])) and (h > series[(i + 1)][1])) and (h > series[(i + 2)][1])): + o[i] = h + return o + +def ind_gann_hilo_activator(s, period=3): + n = len(s) + out = [float("nan")] * (n) + up = True + have = False + act = 0.0 + for i in range(int(period), n): + hi = (-1e300) + lo = 1e300 + for k in range(1, (period + 1)): + hi = max(hi, s[(i - int(k))][1]) + lo = min(lo, s[(i - int(k))][2]) + if (not have): + up = True + act = lo + have = True + if up: + if (s[i][3] < act): + up = False + act = hi + else: + act = lo + else: + if (s[i][3] > act): + up = True + act = lo + else: + act = hi + out[i] = act + return out + +def ind_gann_swing_oscillator(s, dummy=0): + n = len(s) + out = [float("nan")] * (n) + state = 0.0 + for i in range(1, n): + up = ((s[i][1] > s[(i - 1)][1]) and (s[i][2] > s[(i - 1)][2])) + dn = ((s[i][1] < s[(i - 1)][1]) and (s[i][2] < s[(i - 1)][2])) + if up: + state = 1.0 + elif dn: + state = (-1.0) + out[i] = state + return out + +def ind_garman_klass_volatility(series, period=20): + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (i < int((period - 1))): + continue + s = 0.0 + ok = True + for j in range(0, period): + b = series[(i - int(j))] + if ((((b[1] <= 0) or (b[2] <= 0)) or (b[0] <= 0)) or (b[3] <= 0)): + ok = False + break + lhl = math.log((b[1] / b[2])) + lco = math.log((b[3] / b[0])) + s += (((0.5 * lhl) * lhl) - ((((2.0 * math.log(2.0)) - 1.0) * lco) * lco)) + if (ok and (s > 0)): + o[i] = ((100.0 * math.sqrt((s / period))) * math.sqrt(252.0)) + elif ok: + o[i] = 0.0 + return o + +def ind_gator(closes): + r = SimpleNamespace(upper=[], lower=[]) + def shifted(p, sh): + s = list(smma_v(closes, p)) + o = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if ((i >= int(sh)) and math.isfinite(s[(i - int(sh))])): + o[i] = s[(i - int(sh))] + return o + jaw = shifted(13, 8) + teeth = shifted(8, 5) + lips = shifted(5, 3) + r.upper = [float("nan")] * (len(closes)) + r.lower = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if (math.isfinite(jaw[i]) and math.isfinite(teeth[i])): + r.upper[i] = abs((jaw[i] - teeth[i])) + if (math.isfinite(teeth[i]) and math.isfinite(lips[i])): + r.lower[i] = (-abs((teeth[i] - lips[i]))) + return r + +def ind_gaussian_ma(closes, period): + o = [float("nan")] * (len(closes)) + if (period < 1): + period = 1 + sigma = (period / 6.0) + centre = ((period - 1) / 2.0) + ws = 0.0 + w = [0.0] * (int(period)) + for i in range(0, period): + w[int(i)] = math.exp((((-0.5) * ((i - centre) * (i - centre))) / (sigma * sigma))) + ws += w[int(i)] + for i in range(0, len(closes)): + if ((i + 1) < int(period)): + continue + s = 0.0 + for j in range(0, period): + s += (closes[((i - int((period - 1))) + int(j))] * w[int(j)]) + o[i] = (s / ws) + return o + +def ind_gopalakrishnan_range_index(series, period=20): + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (i < int((period - 1))): + continue + s = 0.0 + ok = True + for j in range(0, period): + b = series[(i - int(j))] + if ((b[1] <= 0) or (b[2] <= 0)): + ok = False + break + s += math.log((b[1] / b[2])) + if ok: + o[i] = ((100.0 * s) / period) + return o + +def ind_guppy_mma(closes): + r = SimpleNamespace(lines=[]) + ps = [3, 5, 8, 10, 12, 15, 30, 35, 40, 45, 50, 60] + for k in range(0, 12): + r.lines.append(ema_v(closes, ps[k])) + return r + +def ind_hma(closes, period): + w1 = list(wma_v(closes, (period // 2))) + w2 = list(wma_v(closes, period)) + d = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if (math.isfinite(w1[i]) and math.isfinite(w2[i])): + d[i] = ((2.0 * w1[i]) - w2[i]) + sq = int(math.sqrt(float(period))) + if (sq < 1): + sq = 1 + return wma_v(d, sq) + +def ind_half_trend(series, amplitude, channelDeviation): + atr = list(atr_v(series, 100)) + o = [float("nan")] * (len(series)) + if (not series): + return o + up = 0.0 + dn = 0.0 + trend_up = True + for i in range(0, len(series)): + if (not math.isfinite(atr[i])): + continue + hh = highest_v(_highs(series), i, max(1, amplitude)) + ll = lowest_v(_lows(series), i, max(1, amplitude)) + dev = ((atr[i] * channelDeviation) / 2.0) + upb = (ll + dev) + dnb = (hh - dev) + if ((i == 0) or (not math.isfinite(o[(i - 1)]))): + up = upb + dn = dnb + else: + up = (max(up, upb) if (series[(i - 1)][3] > up) else upb) + dn = (min(dn, dnb) if (series[(i - 1)][3] < dn) else dnb) + if (trend_up and (series[i][3] < dn)): + trend_up = False + elif ((not trend_up) and (series[i][3] > up)): + trend_up = True + o[i] = (up if trend_up else dn) + return o + +def ind_high_low_range(series, period=20): + h = list(_highs(series)) + l = list(_lows(series)) + c = list(_closes(series)) + hhv = list(hh(h, period)) + llv = list(ll(l, period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (math.isfinite(hhv[i]) and (c[i] != 0.0)): + o[i] = ((100.0 * (hhv[i] - llv[i])) / c[i]) + return o + +def ind_historical_volatility(series, period=20): + lr = list(logret(_closes(series))) + sd = list(stddev_7bc07ae7(lr, period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if math.isfinite(sd[i]): + o[i] = ((100.0 * sd[i]) * math.sqrt(252.0)) + return o + +def ind_hurst_exponent(series, period=50): + c = list(_closes(series)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (i < int((period - 1))): + continue + mean = 0.0 + for j in range(0, period): + mean += c[(i - int(j))] + mean /= period + mx = (-1e300) + mn = 1e300 + s = 0.0 + dev = 0.0 + for j in range(0, period): + dev += (c[(i - int(j))] - mean) + mx = max(mx, dev) + mn = min(mn, dev) + d = (c[(i - int(j))] - mean) + s += (d * d) + sd = math.sqrt((s / period)) + rs = (((mx - mn) / sd) if (sd > 0) else 0.0) + if (rs > 0): + o[i] = (math.log(rs) / math.log((period / 2.0))) + return o + +def ind_inertia(closes, period=20): + rsi = list(rsi_series(closes, period)) + return sma_30e386ad(rsi, period) + +def ind_intraday_intensity_index(series, period=21): + ii = [0.0] * (len(series)) + for i in range(0, len(series)): + range_ = (series[i][1] - series[i][2]) + if (range_ != 0.0): + ii[i] = (((((2.0 * series[i][3]) - series[i][1]) - series[i][2]) / range_) * series[i][4]) + o = [float("nan")] * (len(series)) + s = 0.0 + for i in range(0, len(series)): + s += ii[i] + if (i >= int(period)): + s -= ii[(i - int(period))] + if (i >= int((period - 1))): + o[i] = s + return o + +def ind_intraday_momentum_index(s, period=14): + n = len(s) + out = [float("nan")] * (n) + for i in range(int((period - 1)), n): + up = 0.0 + dn = 0.0 + for k in range(0, period): + d = (s[(i - int(k))][3] - s[(i - int(k))][0]) + if (d > 0): + up += d + else: + dn -= d + out[i] = (50.0 if ((up + dn) == 0.0) else ((100.0 * up) / (up + dn))) + return out + +def ind_inverse_fisher_transform(closes, period=14): + rsi = list(rsi_series(closes, period)) + out = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if (not math.isfinite(rsi[i])): + continue + x = ((rsi[i] / 50.0) - 1.0) + if (x > 0.999): + x = 0.999 + if (x < (-0.999)): + x = (-0.999) + e = math.exp((2.0 * x)) + out[i] = (50.0 * (((e - 1.0) / (e + 1.0)) + 1.0)) + return out + +def ind_jurik_moving_average(closes, period=20): + return ema_51fe74d0(ema_51fe74d0(ema_51fe74d0(closes, period), period), period) + +def ind_jurik_velocity(closes, period=14): + roc = [float("nan")] * (len(closes)) + for i in range(1, len(closes)): + if (closes[(i - 1)] != 0.0): + roc[i] = ((100.0 * (closes[i] - closes[(i - 1)])) / closes[(i - 1)]) + return ema_51fe74d0(ema_51fe74d0(ema_51fe74d0(roc, period), period), period) + +def ind_kama(closes, period, fast, slow): + o = [float("nan")] * (len(closes)) + if (period < 1): + period = 1 + fastsc = (2.0 / (fast + 1.0)) + slowsc = (2.0 / (slow + 1.0)) + prev = float("nan") + for i in range(0, len(closes)): + if ((i + 1) < int(period)): + continue + if (not math.isfinite(prev)): + prev = closes[i] + o[i] = prev + continue + dir = abs((closes[i] - closes[((i + 1) - int(period))])) + vol = 0.0 + for j in range((((i + 1) - int(period)) + 1), (i + 1)): + vol += abs((closes[j] - closes[(j - 1)])) + er = ((dir / vol) if (vol > 0.0) else 0.0) + sc = ((er * (fastsc - slowsc)) + slowsc) + sc = (sc * sc) + prev = (prev + (sc * (closes[i] - prev))) + o[i] = prev + return o + +def ind_kdj(s, period=9, smooth=3): + h = list(_highs(s)) + l = list(_lows(s)) + c = list(_closes(s)) + n = len(c) + r = SimpleNamespace(k=[], d=[], j=[]) + r.k = [float("nan")] * (n) + r.d = [float("nan")] * (n) + r.j = [float("nan")] * (n) + k = 50.0 + d = 50.0 + for i in range(0, n): + if (i < int((period - 1))): + continue + hi = h[i] + lo = l[i] + for kk in range(1, period): + hi = max(hi, h[(i - int(kk))]) + lo = min(lo, l[(i - int(kk))]) + rsv = (50.0 if (hi == lo) else ((100.0 * (c[i] - lo)) / (hi - lo))) + k = (((2.0 / 3.0) * k) + ((1.0 / 3.0) * rsv)) + d = (((2.0 / 3.0) * d) + ((1.0 / 3.0) * k)) + r.k[i] = k + r.d[i] = d + r.j[i] = ((3.0 * k) - (2.0 * d)) + return r + +def ind_kst(closes, dummy=0): + def roc(p): + o = [float("nan")] * (len(closes)) + for i in range(int(p), len(closes)): + if (closes[(i - int(p))] != 0.0): + o[i] = ((100.0 * (closes[i] - closes[(i - int(p))])) / closes[(i - int(p))]) + return o + a = list(sma_30e386ad(roc(10), 10)) + b = list(sma_30e386ad(roc(15), 10)) + c = list(sma_30e386ad(roc(20), 10)) + d = list(sma_30e386ad(roc(30), 9)) + out = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if (((math.isfinite(a[i]) and math.isfinite(b[i])) and math.isfinite(c[i])) and math.isfinite(d[i])): + out[i] = (((a[i] + (2.0 * b[i])) + (3.0 * c[i])) + (4.0 * d[i])) + return out + +def ind_kairi(closes, period=25): + m = list(sma_30e386ad(closes, period)) + out = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if (math.isfinite(m[i]) and (m[i] != 0.0)): + out[i] = ((100.0 * (closes[i] - m[i])) / m[i]) + return out + +def ind_keltner_bandwidth(series, period=20, mult=2.0): + tp = list(_typical(series)) + m = list(ema_239a7b94(tp, period)) + a = list(atr(series, period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if ((math.isfinite(m[i]) and math.isfinite(a[i])) and (m[i] != 0.0)): + o[i] = (((4.0 * mult) * a[i]) / m[i]) + return o + +def ind_keltner_channels(series, period=20, mult=2.0): + tp = list(_typical(series)) + m = list(ema_239a7b94(tp, period)) + a = list(atr(series, period)) + r = SimpleNamespace(upper=[], middle=[], lower=[]) + r.upper = [float("nan")] * (len(series)) + r.middle = list(m) + r.lower = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (math.isfinite(m[i]) and math.isfinite(a[i])): + r.upper[i] = (m[i] + (mult * a[i])) + r.lower[i] = (m[i] - (mult * a[i])) + return r + +def ind_kijun_sen(series, period): + return mid_v(_highs(series), _lows(series), period) + +def ind_klinger_volume_oscillator(series, period=13): + vf = [0.0] * (len(series)) + for i in range(0, len(series)): + trend = 0.0 + if (i > 0): + trend = (1.0 if (((series[i][1] + series[i][2]) + series[i][3]) > ((series[(i - 1)][1] + series[(i - 1)][2]) + series[(i - 1)][3])) else (-1.0)) + dm = (((series[i][1] - series[i][2]) - (series[(i - 1)][1] - series[(i - 1)][2])) if (i > 0) else 0.0) + cm = ((((abs((series[i][1] - series[(i - 1)][2])) + abs((series[i][2] - series[(i - 1)][1]))) + abs((series[i][1] - series[(i - 1)][3]))) + abs((series[i][2] - series[(i - 1)][3]))) if (i > 0) else 1.0) + vf_raw = (((trend * series[i][4]) * abs((((2.0 * dm) / cm) - 1.0))) if (cm != 0.0) else 0.0) + vf[i] = vf_raw + r = SimpleNamespace(kvo=[], signal=[]) + r.kvo = [float("nan")] * (len(series)) + r.signal = [float("nan")] * (len(series)) + fast = list(ema_239a7b94(vf, 34)) + slow = list(ema_239a7b94(vf, 55)) + for i in range(0, len(series)): + if (math.isfinite(fast[i]) and math.isfinite(slow[i])): + r.kvo[i] = (fast[i] - slow[i]) + kv = list(r.kvo) + for i in range(0, len(kv)): + if (not math.isfinite(kv[i])): + kv[i] = 0.0 + r.signal = list(ema_239a7b94(kv, period)) + for i in range(0, len(series)): + if (not math.isfinite(r.kvo[i])): + r.signal[i] = float("nan") + return r + +def ind_kurtosis(series, period=20): + c = list(_closes(series)) + m = list(sma_58520e20(c, period)) + sd = list(stddev_7bc07ae7(c, period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if ((not math.isfinite(m[i])) or (sd[i] == 0.0)): + continue + s = 0.0 + for j in range(0, period): + z = ((c[(i - int(j))] - m[i]) / sd[i]) + s += (((z * z) * z) * z) + o[i] = ((s / period) - 3.0) + return o + +def ind_lsma(closes, period): + o = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if ((i + 1) < int(period)): + continue + sl = 0.0 + ic = 0.0 + v = 0.0 + r = 0.0 + sl, ic, v, r = linreg_parts(closes, i, period) + o[i] = v + return o + +def ind_laguerre_filter(closes, gamma=0.8): + n = len(closes) + out = [float("nan")] * (n) + g = gamma + L0 = [0.0] * (n) + L1 = [0.0] * (n) + L2 = [0.0] * (n) + L3 = [0.0] * (n) + for i in range(0, n): + p = closes[i] + pL0 = (L0[(i - 1)] if i else p) + pL1 = (L1[(i - 1)] if i else 0.0) + pL2 = (L2[(i - 1)] if i else 0.0) + pL3 = (L3[(i - 1)] if i else 0.0) + L0[i] = (((1.0 - g) * p) + (g * pL0)) + L1[i] = ((((-g) * L0[i]) + pL0) + (g * pL1)) + L2[i] = ((((-g) * L1[i]) + pL1) + (g * pL2)) + L3[i] = ((((-g) * L2[i]) + pL2) + (g * pL3)) + out[i] = L0[i] + return out + +def ind_laguerre_rsi(closes, gamma=0.8): + n = len(closes) + out = [float("nan")] * (n) + g = gamma + L0 = [0.0] * (n) + L1 = [0.0] * (n) + L2 = [0.0] * (n) + L3 = [0.0] * (n) + for i in range(0, n): + p = closes[i] + pL0 = (L0[(i - 1)] if i else p) + pL1 = (L1[(i - 1)] if i else 0.0) + pL2 = (L2[(i - 1)] if i else 0.0) + pL3 = (L3[(i - 1)] if i else 0.0) + L0[i] = (((1.0 - g) * p) + (g * pL0)) + L1[i] = ((((-g) * L0[i]) + pL0) + (g * pL1)) + L2[i] = ((((-g) * L1[i]) + pL1) + (g * pL2)) + L3[i] = ((((-g) * L2[i]) + pL2) + (g * pL3)) + if (i == 0): + continue + cu = 0.0 + cd = 0.0 + cu += ((L0[i] - L1[i]) if (L0[i] > L1[i]) else 0.0) + cd += ((L1[i] - L0[i]) if (L0[i] < L1[i]) else 0.0) + cu += ((L1[i] - L2[i]) if (L1[i] > L2[i]) else 0.0) + cd += ((L2[i] - L1[i]) if (L1[i] < L2[i]) else 0.0) + cu += ((L2[i] - L3[i]) if (L2[i] > L3[i]) else 0.0) + cd += ((L3[i] - L2[i]) if (L2[i] < L3[i]) else 0.0) + out[i] = (50.0 if ((cu + cd) == 0.0) else ((100.0 * cu) / (cu + cd))) + return out + +def ind_linreg(closes, period): + o = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if ((i + 1) < int(period)): + continue + sl = 0.0 + ic = 0.0 + v = 0.0 + r = 0.0 + sl, ic, v, r = linreg_parts(closes, i, period) + o[i] = v + return o + +def ind_linreg_angle(closes, period): + o = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if ((i + 1) < int(period)): + continue + sl = 0.0 + ic = 0.0 + v = 0.0 + r = 0.0 + sl, ic, v, r = linreg_parts(closes, i, period) + o[i] = ((math.atan(sl) * 180.0) / 3.141592653589793) + return o + +def ind_linreg_intercept(closes, period): + o = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if ((i + 1) < int(period)): + continue + sl = 0.0 + ic = 0.0 + v = 0.0 + r = 0.0 + sl, ic, v, r = linreg_parts(closes, i, period) + o[i] = ic + return o + +def ind_linreg_slope(closes, period): + o = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if ((i + 1) < int(period)): + continue + sl = 0.0 + ic = 0.0 + v = 0.0 + r = 0.0 + sl, ic, v, r = linreg_parts(closes, i, period) + o[i] = sl + return o + +def ind_linear_regression_forecast(series, period=14): + c = list(_closes(series)) + o = [float("nan")] * (len(series)) + sx = ((period * (period - 1)) / 2.0) + sxx = 0.0 + for j in range(0, period): + sxx += (float(j) * j) + den = ((period * sxx) - (sx * sx)) + for i in range(0, len(series)): + if (i < int((period - 1))): + continue + sy = 0.0 + sxy = 0.0 + for j in range(0, period): + y = c[((i - int((period - 1))) + int(j))] + sy += y + sxy += (j * y) + if (den == 0.0): + continue + slope = (((period * sxy) - (sx * sy)) / den) + inter = ((sy - (slope * sx)) / period) + o[i] = (inter + (slope * (period - 1))) + return o + +def ind_linear_regression_intercept(series, period=14): + c = list(_closes(series)) + o = [float("nan")] * (len(series)) + sx = ((period * (period - 1)) / 2.0) + sxx = 0.0 + for j in range(0, period): + sxx += (float(j) * j) + den = ((period * sxx) - (sx * sx)) + for i in range(0, len(series)): + if (i < int((period - 1))): + continue + sy = 0.0 + sxy = 0.0 + for j in range(0, period): + y = c[((i - int((period - 1))) + int(j))] + sy += y + sxy += (j * y) + if (den != 0.0): + slope = (((period * sxy) - (sx * sy)) / den) + o[i] = ((sy - (slope * sx)) / period) + return o + +def ind_linear_regression_oscillator(closes, period=14): + out = [float("nan")] * (len(closes)) + for i in range(int((period - 1)), len(closes)): + out[i] = (closes[i] - linreg_value_at(closes, i, period)) + return out + +def ind_linear_regression_slope(series, period=14): + c = list(_closes(series)) + o = [float("nan")] * (len(series)) + sx = ((period * (period - 1)) / 2.0) + sxx = 0.0 + for j in range(0, period): + sxx += (float(j) * j) + den = ((period * sxx) - (sx * sx)) + for i in range(0, len(series)): + if (i < int((period - 1))): + continue + sy = 0.0 + sxy = 0.0 + for j in range(0, period): + y = c[((i - int((period - 1))) + int(j))] + sy += y + sxy += (j * y) + if (den != 0.0): + o[i] = (((period * sxy) - (sx * sy)) / den) + return o + +def ind_macd(closes, fast=12, slow=26, signal=9): + ef = list(ema_51fe74d0(closes, fast)) + es = list(ema_51fe74d0(closes, slow)) + r = SimpleNamespace(macd=[], signal=[], histogram=[]) + r.macd = [float("nan")] * (len(closes)) + r.signal = [float("nan")] * (len(closes)) + r.histogram = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if (math.isfinite(ef[i]) and math.isfinite(es[i])): + r.macd[i] = (ef[i] - es[i]) + sig = list(ema_51fe74d0(r.macd, signal)) + r.signal = list(sig) + for i in range(0, len(closes)): + if (math.isfinite(r.macd[i]) and math.isfinite(sig[i])): + r.histogram[i] = (r.macd[i] - sig[i]) + return r + +def ind_macd_histogram(closes, fast=12, slow=26, signal=9): + ef = list(ema_51fe74d0(closes, fast)) + es = list(ema_51fe74d0(closes, slow)) + macd = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if (math.isfinite(ef[i]) and math.isfinite(es[i])): + macd[i] = (ef[i] - es[i]) + sig = list(ema_51fe74d0(macd, signal)) + out = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if (math.isfinite(macd[i]) and math.isfinite(sig[i])): + out[i] = (macd[i] - sig[i]) + return out + +def ind_macd_of_rsi(closes, rsi_period=14, fast=12, slow=26): + rsi = list(rsi_series(closes, rsi_period)) + ef = list(ema_51fe74d0(rsi, fast)) + es = list(ema_51fe74d0(rsi, slow)) + out = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if (math.isfinite(ef[i]) and math.isfinite(es[i])): + out[i] = (ef[i] - es[i]) + return out + +def ind_ma_envelope_lower(closes, period, pct): + sma = list(sma_v(closes, period)) + o = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if math.isfinite(sma[i]): + o[i] = (sma[i] * (1.0 - (pct / 100.0))) + return o + +def ind_ma_envelope_upper(closes, period, pct): + sma = list(sma_v(closes, period)) + o = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if math.isfinite(sma[i]): + o[i] = (sma[i] * (1.0 + (pct / 100.0))) + return o + +def ind_mama(closes, fastlimit, slowlimit): + o = [float("nan")] * (len(closes)) + det = [0.0] * (len(closes)) + def cp(i, lag): + return (closes[(i - lag)] if (i >= lag) else closes[0]) + def dp(i, lag): + return (det[(i - lag)] if (i >= lag) else 0.0) + for i in range(0, len(closes)): + det[i] = (((((0.0962 * cp(i, 0)) + (0.5769 * cp(i, 2))) - (0.5769 * cp(i, 4))) - (0.0962 * cp(i, 6))) * 0.54) + alpha = [slowlimit] * (len(closes)) + for i in range(0, len(closes)): + q1 = ((((0.0962 * det[i]) + (0.5769 * dp(i, 2))) - (0.5769 * dp(i, 4))) - (0.0962 * dp(i, 6))) + i1 = dp(i, 3) + phase = math.atan2(q1, i1) + a = (slowlimit + ((fastlimit - slowlimit) * (abs(phase) / 3.141592653589793))) + if (a < slowlimit): + a = slowlimit + if (a > fastlimit): + a = fastlimit + alpha[i] = a + prev = float("nan") + for i in range(0, len(closes)): + if (not math.isfinite(prev)): + prev = closes[i] + o[i] = prev + else: + prev = ((alpha[i] * closes[i]) + ((1.0 - alpha[i]) * prev)) + o[i] = prev + return o + +def ind_mass_index(series, period=25): + hl = [0.0] * (len(series)) + for i in range(0, len(series)): + hl[i] = (series[i][1] - series[i][2]) + e = list(ema_239a7b94(hl, 9)) + ratio = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (math.isfinite(e[i]) and (e[i] != 0.0)): + ratio[i] = (hl[i] / e[i]) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (i < int((period - 1))): + continue + s = 0.0 + ok = True + for j in range(0, period): + if (not math.isfinite(ratio[(i - int(j))])): + ok = False + break + s += ratio[(i - int(j))] + if ok: + o[i] = s + return o + +def ind_mcginley(closes, period): + o = [float("nan")] * (len(closes)) + if (period < 1): + period = 1 + prev = float("nan") + for i in range(0, len(closes)): + if (not math.isfinite(prev)): + prev = closes[i] + o[i] = prev + continue + r = ((closes[i] / prev) if (prev != 0.0) else 1.0) + denom = ((0.6 * period) * pow(r, 4.0)) + if (denom == 0.0): + denom = 1.0 + prev = (prev + ((closes[i] - prev) / denom)) + o[i] = prev + return o + +def ind_median_ma(closes, period): + o = [float("nan")] * (len(closes)) + if (period < 1): + period = 1 + win = [] + for i in range(0, len(closes)): + if ((i + 1) < int(period)): + continue + win.clear() + for j in range(0, period): + win.append(closes[(i - int(j))]) + win.sort() + o[i] = (win[int((period // 2))] if ((period % 2) == 1) else ((win[int(((period // 2) - 1))] + win[int((period // 2))]) / 2.0)) + return o + +def ind_median_price(series, period=20): + c = list(_closes(series)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (i < int((period - 1))): + continue + w = c[int((i - int((period - 1)))):int((i + 1))] + w.sort() + o[i] = (w[int((period // 2))] if ((period % 2) == 1) else ((w[int(((period // 2) - 1))] + w[int((period // 2))]) / 2.0)) + return o + +def ind_minus_di(series, period): + return di_minus_v(series, period) + +def ind_momentum(closes, period=10): + out = [float("nan")] * (len(closes)) + for i in range(int(period), len(closes)): + out[i] = (closes[i] - closes[(i - int(period))]) + return out + +def ind_money_flow_index(series, period=14): + tp = list(_typical(series)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (i < int(period)): + continue + pos = 0.0 + neg = 0.0 + for j in range(0, period): + idx = (i - int(j)) + mf = (tp[idx] * series[idx][4]) + if ((idx > 0) and (tp[idx] > tp[(idx - 1)])): + pos += mf + elif ((idx > 0) and (tp[idx] < tp[(idx - 1)])): + neg += mf + if (neg == 0.0): + o[i] = 100.0 + else: + mr = (pos / neg) + o[i] = (100.0 - (100.0 / (1.0 + mr))) + return o + +def ind_money_flow_volume(series, period=1): + tp = list(_typical(series)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + o[i] = (tp[i] * series[i][4]) + return o + +def ind_ma_ribbon(closes): + r = SimpleNamespace(lines=[]) + ps = [5, 10, 20, 30, 50, 100] + for k in range(0, 6): + r.lines.append(sma_v(closes, ps[k])) + return r + +def ind_natr(series, period=14): + a = list(atr(series, period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (math.isfinite(a[i]) and (series[i][3] != 0.0)): + o[i] = ((100.0 * a[i]) / series[i][3]) + return o + +def ind_negative_volume_index(series, period=1): + o = [float("nan")] * (len(series)) + acc = 1000.0 + for i in range(0, len(series)): + if (((i > 0) and (series[i][4] < series[(i - 1)][4])) and (series[(i - 1)][3] != 0.0)): + acc *= (series[i][3] / series[(i - 1)][3]) + o[i] = acc + return o + +def ind_normalized_roc(closes, period=12, norm=20): + roc = [float("nan")] * (len(closes)) + for i in range(int(period), len(closes)): + if (closes[(i - int(period))] != 0.0): + roc[i] = ((100.0 * (closes[i] - closes[(i - int(period))])) / closes[(i - int(period))]) + sd = list(stddev_8463129b(roc, norm)) + out = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if ((math.isfinite(roc[i]) and math.isfinite(sd[i])) and (sd[i] != 0.0)): + out[i] = (roc[i] / sd[i]) + return out + +def ind_obv(series, period=1): + o = [float("nan")] * (len(series)) + acc = 0.0 + for i in range(0, len(series)): + if (i > 0): + if (series[i][3] > series[(i - 1)][3]): + acc += series[i][4] + elif (series[i][3] < series[(i - 1)][3]): + acc -= series[i][4] + o[i] = acc + return o + +def ind_ppo(closes, fast=12, slow=26): + ef = list(ema_51fe74d0(closes, fast)) + es = list(ema_51fe74d0(closes, slow)) + out = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if ((math.isfinite(ef[i]) and math.isfinite(es[i])) and (es[i] != 0.0)): + out[i] = ((100.0 * (ef[i] - es[i])) / es[i]) + return out + +def ind_psar(series, step, maxaf): + o = [float("nan")] * (len(series)) + if (len(series) < 2): + return o + up = (series[1][3] > series[0][3]) + sar = (series[0][2] if up else series[0][1]) + ep = (series[0][1] if up else series[0][2]) + af = step + o[0] = sar + for i in range(1, len(series)): + prev_sar = sar + sar = (prev_sar + (af * (ep - prev_sar))) + if up: + sar = min(sar, series[(i - 1)][2]) + if (i >= 2): + sar = min(sar, series[(i - 2)][2]) + if (series[i][2] < sar): + up = False + sar = ep + ep = series[i][2] + af = step + else: + if (series[i][1] > ep): + ep = series[i][1] + af = min((af + step), maxaf) + else: + sar = max(sar, series[(i - 1)][1]) + if (i >= 2): + sar = max(sar, series[(i - 2)][1]) + if (series[i][1] > sar): + up = True + sar = ep + ep = series[i][1] + af = step + else: + if (series[i][2] < ep): + ep = series[i][2] + af = min((af + step), maxaf) + o[i] = sar + return o + +def ind_parkinson_volatility(series, period=20): + o = [float("nan")] * (len(series)) + k = (1.0 / (4.0 * math.log(2.0))) + for i in range(0, len(series)): + if (i < int((period - 1))): + continue + s = 0.0 + ok = True + for j in range(0, period): + b = series[(i - int(j))] + if ((b[1] <= 0) or (b[2] <= 0)): + ok = False + break + lh = math.log((b[1] / b[2])) + s += (lh * lh) + if ok: + o[i] = ((100.0 * math.sqrt(((k * s) / period))) * math.sqrt(252.0)) + return o + +def ind_percent_rank(closes, period=14): + out = [float("nan")] * (len(closes)) + for i in range(int((period - 1)), len(closes)): + cnt = 0 + for k in range(1, period): + if (closes[(i - int(k))] < closes[i]): + cnt += 1 + out[i] = ((100.0 * cnt) / (period - 1)) + return out + +def ind_percentage_volume_oscillator(series, period=14): + v = list(_volumes(series)) + fast = list(ema_239a7b94(v, 12)) + slow = list(ema_239a7b94(v, 26)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if ((math.isfinite(fast[i]) and math.isfinite(slow[i])) and (slow[i] != 0.0)): + o[i] = ((100.0 * (fast[i] - slow[i])) / slow[i]) + return o + +def ind_percentile_rank(series, period=20): + c = list(_closes(series)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (i < int((period - 1))): + continue + below = 0 + for j in range(0, period): + if (c[(i - int(j))] < c[i]): + below += 1 + o[i] = ((100.0 * below) / (period - 1)) + return o + +def ind_pivot_point(series): + o = [float("nan")] * (len(series)) + for i in range(1, len(series)): + o[i] = (((series[(i - 1)][1] + series[(i - 1)][2]) + series[(i - 1)][3]) / 3.0) + return o + +def ind_plus_di(series, period): + return di_plus_v(series, period) + +def ind_positive_volume_index(series, period=1): + o = [float("nan")] * (len(series)) + acc = 1000.0 + for i in range(0, len(series)): + if (((i > 0) and (series[i][4] > series[(i - 1)][4])) and (series[(i - 1)][3] != 0.0)): + acc *= (series[i][3] / series[(i - 1)][3]) + o[i] = acc + return o + +def ind_pretty_good_oscillator(s, period=14): + c = list(_closes(s)) + h = list(_highs(s)) + l = list(_lows(s)) + tr = [float("nan")] * (len(c)) + for i in range(1, len(c)): + tr[i] = max((h[i] - l[i]), max(abs((h[i] - c[(i - 1)])), abs((l[i] - c[(i - 1)])))) + m = list(sma_30e386ad(c, period)) + atr = list(ema_51fe74d0(tr, period)) + out = [float("nan")] * (len(c)) + for i in range(0, len(c)): + if ((math.isfinite(m[i]) and math.isfinite(atr[i])) and (atr[i] != 0.0)): + out[i] = ((c[i] - m[i]) / atr[i]) + return out + +def ind_price_momentum_oscillator(closes, slow=35, fast=20): + roc = [float("nan")] * (len(closes)) + for i in range(1, len(closes)): + if (closes[(i - 1)] != 0.0): + roc[i] = ((100.0 * (closes[i] - closes[(i - 1)])) / closes[(i - 1)]) + s1 = list(ema_51fe74d0(roc, slow)) + s2 = list(ema_51fe74d0(s1, fast)) + out = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if math.isfinite(s2[i]): + out[i] = (10.0 * s2[i]) + return out + +def ind_qstick(series, period): + d = [0.0] * (len(series)) + for i in range(0, len(series)): + d[i] = (series[i][3] - series[i][0]) + return sma_v(d, period) + +def ind_rma(closes, period): + o = [float("nan")] * (len(closes)) + if (period < 1): + period = 1 + if (not closes): + return o + k = (1.0 / period) + s = 0.0 + for i in range(0, len(closes)): + s += closes[i] + if ((i + 1) == int(period)): + o[i] = (s / period) + elif ((i + 1) > int(period)): + o[i] = ((closes[i] * k) + (o[(i - 1)] * (1.0 - k))) + return o + +def ind_roc(closes, period=12): + out = [float("nan")] * (len(closes)) + for i in range(int(period), len(closes)): + if (closes[(i - int(period))] != 0.0): + out[i] = ((100.0 * (closes[i] - closes[(i - int(period))])) / closes[(i - int(period))]) + return out + +def ind_rocr(closes, period=12): + out = [float("nan")] * (len(closes)) + for i in range(int(period), len(closes)): + if (closes[(i - int(period))] != 0.0): + out[i] = (closes[i] / closes[(i - int(period))]) + return out + +def ind_rsi(closes, period=14): + return rsi_series(closes, period) + +def ind_rsx(closes, period=14): + n = len(closes) + out = [float("nan")] * (n) + if (n < int((period + 1))): + return out + g = [0.0] * (n) + l = [0.0] * (n) + for i in range(1, n): + d = (closes[i] - closes[(i - 1)]) + g[i] = (d if (d > 0) else 0.0) + l[i] = ((-d) if (d < 0) else 0.0) + ag = list(ema_51fe74d0(ema_51fe74d0(ema_51fe74d0(g, period), period), period)) + al = list(ema_51fe74d0(ema_51fe74d0(ema_51fe74d0(l, period), period), period)) + for i in range(0, n): + if ((not math.isfinite(ag[i])) or (not math.isfinite(al[i]))): + continue + den = (ag[i] + al[i]) + out[i] = (50.0 if (den == 0.0) else ((100.0 * ag[i]) / den)) + return out + +def ind_r_squared(series, period=14): + c = list(_closes(series)) + o = [float("nan")] * (len(series)) + sx = ((period * (period - 1)) / 2.0) + sxx = 0.0 + for j in range(0, period): + sxx += (float(j) * j) + den = ((period * sxx) - (sx * sx)) + for i in range(0, len(series)): + if (i < int((period - 1))): + continue + sy = 0.0 + sxy = 0.0 + for j in range(0, period): + y = c[((i - int((period - 1))) + int(j))] + sy += y + sxy += (j * y) + if (den == 0.0): + continue + slope = (((period * sxy) - (sx * sy)) / den) + inter = ((sy - (slope * sx)) / period) + mean = (sy / period) + sst = 0.0 + sse = 0.0 + for j in range(0, period): + y = c[((i - int((period - 1))) + int(j))] + fit = (inter + (slope * j)) + sst += ((y - mean) * (y - mean)) + sse += ((y - fit) * (y - fit)) + o[i] = ((1.0 - (sse / sst)) if (sst != 0.0) else 1.0) + return o + +def ind_rwi_high(series, period): + atr = list(atr_v(series, period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (((i + 1) < int(period)) or (not math.isfinite(atr[i]))): + continue + den = (atr[i] * math.sqrt(float(period))) + o[i] = (((series[i][1] - series[((i + 1) - int(period))][2]) / den) if (den > 0.0) else 0.0) + return o + +def ind_rwi_low(series, period): + atr = list(atr_v(series, period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (((i + 1) < int(period)) or (not math.isfinite(atr[i]))): + continue + den = (atr[i] * math.sqrt(float(period))) + o[i] = (((series[((i + 1) - int(period))][1] - series[i][2]) / den) if (den > 0.0) else 0.0) + return o + +def ind_rainbow_oscillator(closes, max_period=10): + out = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if (i < int((max_period - 1))): + continue + sum_ = 0.0 + cnt = 0 + for p in range(2, (max_period + 1)): + s = 0.0 + for k in range(0, p): + s += closes[(i - int(k))] + sum_ += (s / p) + cnt += 1 + rb = (sum_ / cnt) + if (rb != 0.0): + out[i] = ((100.0 * (closes[i] - rb)) / rb) + return out + +def ind_range_expansion_index(s, period=8): + n = len(s) + out = [float("nan")] * (n) + for i in range(int((period + 1)), n): + num = 0.0 + den = 0.0 + for k in range(0, period): + j = (i - int(k)) + if (j < 2): + continue + if ((s[j][1] >= s[(j - 2)][1]) or (s[j][2] <= s[(j - 2)][2])): + d = (s[j][3] - s[(j - 2)][3]) + num += d + den += abs(d) + out[i] = (0.0 if (den == 0.0) else ((100.0 * num) / den)) + return out + +def ind_reflex(s, period=10): + h = list(_highs(s)) + l = list(_lows(s)) + c = list(_closes(s)) + d = [float("nan")] * (len(c)) + for i in range(10, len(c)): + d[i] = (c[i] - c[(i - 10)]) + ss = list(super_smoother(d, period)) + rng = [float("nan")] * (len(c)) + for i in range(0, len(c)): + rng[i] = (h[i] - l[i]) + m = list(sma_30e386ad(rng, period)) + out = [float("nan")] * (len(c)) + for i in range(0, len(c)): + if ((math.isfinite(ss[i]) and math.isfinite(m[i])) and (m[i] != 0.0)): + out[i] = (ss[i] / m[i]) + return out + +def ind_regression_channel(closes, period, mult): + r = SimpleNamespace(upper=[], mid=[], lower=[]) + r.upper = [float("nan")] * (len(closes)) + r.mid = [float("nan")] * (len(closes)) + r.lower = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if ((i + 1) < int(period)): + continue + sl = 0.0 + ic = 0.0 + v = 0.0 + rsq = 0.0 + sl, ic, v, rsq = linreg_parts(closes, i, period) + ss = 0.0 + for j in range(0, period): + fit = (ic + (sl * j)) + d = (closes[((i - int((period - 1))) + int(j))] - fit) + ss += (d * d) + sd = math.sqrt((ss / period)) + r.mid[i] = v + r.upper[i] = (v + (mult * sd)) + r.lower[i] = (v - (mult * sd)) + return r + +def ind_relative_momentum_index(closes, period=20, momentum=5): + n = len(closes) + out = [float("nan")] * (n) + if (n < int((period + momentum))): + return out + g = [0.0] * (n) + l = [0.0] * (n) + for i in range(int(momentum), n): + d = (closes[i] - closes[(i - int(momentum))]) + g[i] = (d if (d > 0) else 0.0) + l[i] = ((-d) if (d < 0) else 0.0) + ag = list(wilder(g, period)) + al = list(wilder(l, period)) + for i in range(0, n): + if ((not math.isfinite(ag[i])) or (not math.isfinite(al[i]))): + continue + den = (ag[i] + al[i]) + out[i] = (50.0 if (den == 0.0) else ((100.0 * ag[i]) / den)) + return out + +def ind_relative_vigor_index(s, period=10): + o = list(_opens(s)) + c = list(_closes(s)) + h = list(_highs(s)) + l = list(_lows(s)) + num = [float("nan")] * (len(c)) + den = [float("nan")] * (len(c)) + for i in range(0, len(c)): + num[i] = (c[i] - o[i]) + den[i] = (h[i] - l[i]) + sn = list(sma_30e386ad(num, period)) + sd = list(sma_30e386ad(den, period)) + out = [float("nan")] * (len(c)) + for i in range(0, len(c)): + if ((math.isfinite(sn[i]) and math.isfinite(sd[i])) and (sd[i] != 0.0)): + out[i] = (sn[i] / sd[i]) + return out + +def ind_relative_volatility_index(series, period=10): + sd = list(stddev_7bc07ae7(_closes(series), period)) + up = [0.0] * (len(series)) + dn = [0.0] * (len(series)) + for i in range(1, len(series)): + if (not math.isfinite(sd[i])): + continue + if (series[i][3] > series[(i - 1)][3]): + up[i] = sd[i] + elif (series[i][3] < series[(i - 1)][3]): + dn[i] = sd[i] + eu = list(ema_wilder(up, period)) + ed = list(ema_wilder(dn, period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if ((math.isfinite(eu[i]) and math.isfinite(ed[i])) and ((eu[i] + ed[i]) != 0.0)): + o[i] = ((100.0 * eu[i]) / (eu[i] + ed[i])) + return o + +def ind_relative_volume(series, period=20): + v = list(_volumes(series)) + mv = list(sma_58520e20(v, period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (math.isfinite(mv[i]) and (mv[i] != 0.0)): + o[i] = (v[i] / mv[i]) + return o + +def ind_rogers_satchell_volatility(series, period=20): + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (i < int((period - 1))): + continue + s = 0.0 + ok = True + for j in range(0, period): + b = series[(i - int(j))] + if ((((b[1] <= 0) or (b[2] <= 0)) or (b[0] <= 0)) or (b[3] <= 0)): + ok = False + break + s += ((math.log((b[1] / b[3])) * math.log((b[1] / b[0]))) + (math.log((b[2] / b[3])) * math.log((b[2] / b[0])))) + if (ok and (s > 0)): + o[i] = ((100.0 * math.sqrt((s / period))) * math.sqrt(252.0)) + elif ok: + o[i] = 0.0 + return o + +def ind_roofing_filter(closes, period=10, hp_period=48): + hp = [float("nan")] * (len(closes)) + m = list(sma_30e386ad(closes, hp_period)) + for i in range(0, len(closes)): + if math.isfinite(m[i]): + hp[i] = (closes[i] - m[i]) + return super_smoother(hp, period) + +def ind_sma(closes, period): + return sma_v(closes, period) + +def ind_smi(s, period=13): + h = list(_highs(s)) + l = list(_lows(s)) + c = list(_closes(s)) + diff = [float("nan")] * (len(c)) + rng = [float("nan")] * (len(c)) + for i in range(0, len(c)): + diff[i] = (c[i] - ((h[i] + l[i]) / 2.0)) + rng[i] = (h[i] - l[i]) + num = list(ema_51fe74d0(ema_51fe74d0(diff, period), period)) + den = list(ema_51fe74d0(ema_51fe74d0(rng, period), period)) + out = [float("nan")] * (len(c)) + for i in range(0, len(c)): + if ((math.isfinite(num[i]) and math.isfinite(den[i])) and (den[i] != 0.0)): + out[i] = ((100.0 * num[i]) / den[i]) + return out + +def ind_smma(closes, period): + return smma_v(closes, period) + +def ind_ssl_channel(series, period): + sh = list(sma_v(_highs(series), period)) + sl = list(sma_v(_lows(series), period)) + cl = list(_closes(series)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (math.isfinite(sh[i]) and math.isfinite(sl[i])): + o[i] = (sl[i] if (cl[i] > sh[i]) else sh[i]) + return o + +def ind_schaff_trend_cycle(closes, fast=23, slow=50, cycle=10): + ef = list(ema_51fe74d0(closes, fast)) + es = list(ema_51fe74d0(closes, slow)) + macd = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if (math.isfinite(ef[i]) and math.isfinite(es[i])): + macd[i] = (ef[i] - es[i]) + st = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if ((i < int((cycle - 1))) or (not math.isfinite(macd[i]))): + continue + hi = highest(macd, i, cycle) + lo = lowest(macd, i, cycle) + st[i] = (50.0 if (hi == lo) else ((100.0 * (macd[i] - lo)) / (hi - lo))) + return ema_51fe74d0(st, cycle) + +def ind_senkou_span_a(series, tenkan, kijun): + t = list(mid_v(_highs(series), _lows(series), tenkan)) + k = list(mid_v(_highs(series), _lows(series), kijun)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (math.isfinite(t[i]) and math.isfinite(k[i])): + o[i] = ((t[i] + k[i]) / 2.0) + return o + +def ind_senkou_span_b(series, period): + return mid_v(_highs(series), _lows(series), period) + +def ind_shannon_entropy(series, period=20): + c = list(_closes(series)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (i < int(period)): + continue + up = 0 + dn = 0 + fl = 0 + for j in range(0, period): + d = (c[(i - int(j))] - c[((i - int(j)) - 1)]) + if (d > 0): + up += 1 + elif (d < 0): + dn += 1 + else: + fl += 1 + e = 0.0 + for k in range(0, 3): + p = ((up if (k == 0) else (dn if (k == 1) else fl)) / float(period)) + if (p > 0): + e -= (p * math.log2(p)) + o[i] = e + return o + +def ind_sine_wma(closes, period): + o = [float("nan")] * (len(closes)) + if (period < 1): + period = 1 + ws = 0.0 + w = [0.0] * (int(period)) + pi = 3.141592653589793 + for i in range(0, period): + w[int(i)] = math.sin(((pi * (i + 1)) / (period + 1))) + ws += w[int(i)] + for i in range(0, len(closes)): + if ((i + 1) < int(period)): + continue + s = 0.0 + for j in range(0, period): + s += (closes[((i - int((period - 1))) + int(j))] * w[int(j)]) + o[i] = (s / ws) + return o + +def ind_sine_wave(closes, dummy=0): + n = len(closes) + r = SimpleNamespace(sine=[], lead_sine=[]) + r.sine = [float("nan")] * (n) + r.lead_sine = [float("nan")] * (n) + a = 0.07 + sm = [0.0] * (n) + cy = [0.0] * (n) + for i in range(0, n): + c0 = closes[i] + c1 = (closes[(i - 1)] if (i >= 1) else c0) + c2 = (closes[(i - 2)] if (i >= 2) else c0) + c3 = (closes[(i - 3)] if (i >= 3) else c0) + sm[i] = ((((c0 + (2.0 * c1)) + (2.0 * c2)) + c3) / 6.0) + s1 = (sm[(i - 1)] if (i >= 1) else sm[i]) + s2 = (sm[(i - 2)] if (i >= 2) else sm[i]) + y1 = (cy[(i - 1)] if (i >= 1) else 0.0) + y2 = (cy[(i - 2)] if (i >= 2) else 0.0) + cy[i] = (((((1.0 - (a / 2.0)) * (1.0 - (a / 2.0))) * ((sm[i] - (2.0 * s1)) + s2)) + ((2.0 * (1.0 - a)) * y1)) - (((1.0 - a) * (1.0 - a)) * y2)) + for i in range(7, n): + q = (cy[i] - cy[(i - 1)]) + mag = math.sqrt(((cy[i] * cy[i]) + (q * q))) + if (mag == 0.0): + continue + r.sine[i] = (cy[i] / mag) + r.lead_sine[i] = (q / mag) + return r + +def ind_skewness(series, period=20): + c = list(_closes(series)) + m = list(sma_58520e20(c, period)) + sd = list(stddev_7bc07ae7(c, period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if ((not math.isfinite(m[i])) or (sd[i] == 0.0)): + continue + s = 0.0 + for j in range(0, period): + z = ((c[(i - int(j))] - m[i]) / sd[i]) + s += ((z * z) * z) + o[i] = (s / period) + return o + +def ind_smoothed_roc(closes, period=12, smooth=25): + roc = [float("nan")] * (len(closes)) + for i in range(int(period), len(closes)): + if (closes[(i - int(period))] != 0.0): + roc[i] = ((100.0 * (closes[i] - closes[(i - int(period))])) / closes[(i - int(period))]) + return ema_51fe74d0(roc, smooth) + +def ind_spearman_rank(closes, period=14): + out = [float("nan")] * (len(closes)) + for i in range(int((period - 1)), len(closes)): + mx = 0.0 + my = 0.0 + rx = [0.0] * (int(period)) + ry = [0.0] * (int(period)) + for k in range(0, period): + v = closes[((i - int((period - 1))) + int(k))] + r = 1 + for j in range(0, period): + if (closes[((i - int((period - 1))) + int(j))] < v): + r += 1 + rx[int(k)] = float(r) + ry[int(k)] = float((k + 1)) + mx += rx[int(k)] + my += ry[int(k)] + mx /= period + my /= period + sxy = 0.0 + sxx = 0.0 + syy = 0.0 + for k in range(0, period): + sxy += ((rx[int(k)] - mx) * (ry[int(k)] - my)) + sxx += ((rx[int(k)] - mx) * (rx[int(k)] - mx)) + syy += ((ry[int(k)] - my) * (ry[int(k)] - my)) + out[i] = (0.0 if ((sxx == 0.0) or (syy == 0.0)) else (sxy / math.sqrt((sxx * syy)))) + return out + +def ind_special_k(closes, dummy=0): + def roc(p): + o = [float("nan")] * (len(closes)) + for i in range(int(p), len(closes)): + if (closes[(i - int(p))] != 0.0): + o[i] = ((100.0 * (closes[i] - closes[(i - int(p))])) / closes[(i - int(p))]) + return o + a = list(sma_30e386ad(roc(10), 10)) + b = list(sma_30e386ad(roc(15), 10)) + c = list(sma_30e386ad(roc(20), 10)) + d = list(sma_30e386ad(roc(30), 15)) + out = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if (((math.isfinite(a[i]) and math.isfinite(b[i])) and math.isfinite(c[i])) and math.isfinite(d[i])): + out[i] = (((a[i] + (2.0 * b[i])) + (3.0 * c[i])) + (4.0 * d[i])) + return out + +def ind_standard_error(series, period=14): + c = list(_closes(series)) + o = [float("nan")] * (len(series)) + sx = ((period * (period - 1)) / 2.0) + sxx = 0.0 + for j in range(0, period): + sxx += (float(j) * j) + den = ((period * sxx) - (sx * sx)) + for i in range(0, len(series)): + if (i < int((period - 1))): + continue + sy = 0.0 + sxy = 0.0 + for j in range(0, period): + y = c[((i - int((period - 1))) + int(j))] + sy += y + sxy += (j * y) + if ((den == 0.0) or (period <= 2)): + continue + slope = (((period * sxy) - (sx * sy)) / den) + inter = ((sy - (slope * sx)) / period) + sse = 0.0 + for j in range(0, period): + y = c[((i - int((period - 1))) + int(j))] + d = (y - (inter + (slope * j))) + sse += (d * d) + o[i] = math.sqrt((sse / (period - 2))) + return o + +def ind_standard_pivot_points(series, period=1): + r = SimpleNamespace(pivot=[], r1=[], s1=[]) + r.pivot = [float("nan")] * (len(series)) + r.r1 = [float("nan")] * (len(series)) + r.s1 = [float("nan")] * (len(series)) + for i in range(1, len(series)): + p = (((series[(i - 1)][1] + series[(i - 1)][2]) + series[(i - 1)][3]) / 3.0) + r.pivot[i] = p + r.r1[i] = ((2.0 * p) - series[(i - 1)][2]) + r.s1[i] = ((2.0 * p) - series[(i - 1)][1]) + return r + +def ind_stddev(series, period=20): + return stddev_7bc07ae7(_closes(series), period) + +def ind_stoch_rsi(closes, period=14): + rsi = list(rsi_series(closes, period)) + out = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if ((i < int((period - 1))) or (not math.isfinite(rsi[i]))): + continue + hi = highest(rsi, i, period) + lo = lowest(rsi, i, period) + out[i] = (50.0 if (hi == lo) else ((100.0 * (rsi[i] - lo)) / (hi - lo))) + return out + +def ind_stochastic_fast(s, period=14, smooth=3): + h = list(_highs(s)) + l = list(_lows(s)) + c = list(_closes(s)) + r = SimpleNamespace(k=[], d=[]) + r.k = list(stoch_k(h, l, c, period)) + r.d = list(sma_30e386ad(r.k, smooth)) + return r + +def ind_stochastic_full(s, period=14, smooth_k=3, smooth_d=3): + h = list(_highs(s)) + l = list(_lows(s)) + c = list(_closes(s)) + fk = list(stoch_k(h, l, c, period)) + r = SimpleNamespace(k=[], d=[]) + r.k = list(sma_30e386ad(fk, smooth_k)) + r.d = list(sma_30e386ad(r.k, smooth_d)) + return r + +def ind_stochastic_pop(s, period=14): + h = list(_highs(s)) + l = list(_lows(s)) + c = list(_closes(s)) + k = list(stoch_k(h, l, c, period)) + out = [float("nan")] * (len(c)) + for i in range(1, len(c)): + if ((not math.isfinite(k[i])) or (not math.isfinite(k[(i - 1)]))): + continue + if ((k[(i - 1)] <= 80.0) and (k[i] > 80.0)): + out[i] = 1.0 + elif ((k[(i - 1)] >= 20.0) and (k[i] < 20.0)): + out[i] = (-1.0) + else: + out[i] = 0.0 + return out + +def ind_stochastic_slow(s, period=14, smooth=3): + h = list(_highs(s)) + l = list(_lows(s)) + c = list(_closes(s)) + fk = list(stoch_k(h, l, c, period)) + r = SimpleNamespace(k=[], d=[]) + r.k = list(sma_30e386ad(fk, smooth)) + r.d = list(sma_30e386ad(r.k, smooth)) + return r + +def ind_super_smoother(closes, period=10): + return super_smoother(closes, period) + +def ind_supertrend(series, period, mult): + atr = list(atr_v(series, period)) + o = [float("nan")] * (len(series)) + if (not series): + return o + fup = 0.0 + fdn = 0.0 + up = True + for i in range(0, len(series)): + if (not math.isfinite(atr[i])): + continue + hl2 = ((series[i][1] + series[i][2]) / 2.0) + upb = (hl2 + (mult * atr[i])) + dnb = (hl2 - (mult * atr[i])) + if ((i == 0) or (not math.isfinite(o[(i - 1)]))): + fup = upb + fdn = dnb + else: + fup = (upb if ((upb < fup) or (series[(i - 1)][3] > fup)) else fup) + fdn = (dnb if ((dnb > fdn) or (series[(i - 1)][3] < fdn)) else fdn) + if ((i > 0) and math.isfinite(o[(i - 1)])): + if (up and (series[i][3] < fdn)): + up = False + elif ((not up) and (series[i][3] > fup)): + up = True + o[i] = (fdn if up else fup) + return o + +def ind_swenlin_trading_oscillator(closes, slow=35, fast=20, signal=10): + roc = [float("nan")] * (len(closes)) + for i in range(1, len(closes)): + if (closes[(i - 1)] != 0.0): + roc[i] = ((100.0 * (closes[i] - closes[(i - 1)])) / closes[(i - 1)]) + s1 = list(ema_51fe74d0(roc, slow)) + s2 = list(ema_51fe74d0(s1, fast)) + pmo = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if math.isfinite(s2[i]): + pmo[i] = (10.0 * s2[i]) + sig = list(ema_51fe74d0(pmo, signal)) + out = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if (math.isfinite(pmo[i]) and math.isfinite(sig[i])): + out[i] = (pmo[i] - sig[i]) + return out + +def ind_swing_index(series, limitMove): + o = [float("nan")] * (len(series)) + if (limitMove <= 0.0): + limitMove = 1.0 + for i in range(1, len(series)): + b = series[i] + p = series[(i - 1)] + rnum = abs((b[1] - p[3])) + rden = abs((b[2] - p[3])) + rr = (b[1] - b[2]) + r = max(rnum, max(rden, rr)) + k = max(rnum, rden) + num = (((b[3] - p[3]) + (0.5 * (b[3] - b[0]))) + (0.25 * (p[3] - p[0]))) + o[i] = ((((50.0 * num) / r) * (k / limitMove)) if (r > 0.0) else 0.0) + return o + +def ind_t3(closes, period, vf): + e1 = list(ema_v(closes, period)) + e2 = list(ema_v(e1, period)) + e3 = list(ema_v(e2, period)) + e4 = list(ema_v(e3, period)) + e5 = list(ema_v(e4, period)) + e6 = list(ema_v(e5, period)) + c1 = (((-vf) * vf) * vf) + c2 = (((3.0 * vf) * vf) + (((3.0 * vf) * vf) * vf)) + c3 = (((((-6.0) * vf) * vf) - (3.0 * vf)) - (((3.0 * vf) * vf) * vf)) + c4 = (((1.0 + (3.0 * vf)) + ((vf * vf) * vf)) + ((3.0 * vf) * vf)) + o = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if (((math.isfinite(e3[i]) and math.isfinite(e4[i])) and math.isfinite(e5[i])) and math.isfinite(e6[i])): + o[i] = ((((c1 * e6[i]) + (c2 * e5[i])) + (c3 * e4[i])) + (c4 * e3[i])) + return o + +def ind_td_sequential(closes, dummy=0): + out = [float("nan")] * (len(closes)) + count = 0 + for i in range(0, len(closes)): + if (i < 4): + out[i] = 0.0 + continue + if (closes[i] < closes[(i - 4)]): + count = ((count + 1) if (count > 0) else 1) + elif (closes[i] > closes[(i - 4)]): + count = ((count - 1) if (count < 0) else (-1)) + else: + count = 0 + if (count > 9): + count = 9 + if (count < (-9)): + count = (-9) + out[i] = float(count) + return out + +def ind_tema(closes, period): + e1 = list(ema_v(closes, period)) + e2 = list(ema_v(e1, period)) + e3 = list(ema_v(e2, period)) + o = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if ((math.isfinite(e1[i]) and math.isfinite(e2[i])) and math.isfinite(e3[i])): + o[i] = (((3.0 * e1[i]) - (3.0 * e2[i])) + e3[i]) + return o + +def ind_trima(closes, period): + return sma_v(sma_v(closes, period), period) + +def ind_trix(closes, period): + e3 = list(ema_v(ema_v(ema_v(closes, period), period), period)) + o = [float("nan")] * (len(closes)) + for i in range(1, len(closes)): + if ((math.isfinite(e3[i]) and math.isfinite(e3[(i - 1)])) and (e3[(i - 1)] != 0.0)): + o[i] = ((100.0 * (e3[i] - e3[(i - 1)])) / e3[(i - 1)]) + return o + +def ind_tsf(closes, period): + o = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if ((i + 1) < int(period)): + continue + sl = 0.0 + ic = 0.0 + v = 0.0 + r = 0.0 + sl, ic, v, r = linreg_parts(closes, i, period) + o[i] = (ic + (sl * period)) + return o + +def ind_tsi(closes, long_period=25, short_period=13): + mom = [float("nan")] * (len(closes)) + absmom = [float("nan")] * (len(closes)) + for i in range(1, len(closes)): + mom[i] = (closes[i] - closes[(i - 1)]) + absmom[i] = abs(mom[i]) + num = list(ema_51fe74d0(ema_51fe74d0(mom, long_period), short_period)) + den = list(ema_51fe74d0(ema_51fe74d0(absmom, long_period), short_period)) + out = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if ((math.isfinite(num[i]) and math.isfinite(den[i])) and (den[i] != 0.0)): + out[i] = ((100.0 * num[i]) / den[i]) + return out + +def ind_tsma(closes, period): + return ema_v(ema_v(ema_v(closes, period), period), period) + +def ind_ttm_squeeze(series, period=20, mult=2.0): + c = list(_closes(series)) + m = list(sma_58520e20(c, period)) + sd = list(stddev_7bc07ae7(c, period)) + a = list(atr(series, period)) + r = SimpleNamespace(squeeze=[], ratio=[]) + r.squeeze = [float("nan")] * (len(series)) + r.ratio = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if ((not math.isfinite(m[i])) or (not math.isfinite(a[i]))): + continue + bbw = ((2.0 * mult) * sd[i]) + kcw = ((2.0 * 1.5) * a[i]) + r.ratio[i] = ((bbw / kcw) if (kcw != 0.0) else float("nan")) + r.squeeze[i] = (1.0 if (bbw < kcw) else 0.0) + return r + +def ind_tenkan_sen(series, period): + return mid_v(_highs(series), _lows(series), period) + +def ind_trend_flex(closes, period=10): + d = [float("nan")] * (len(closes)) + for i in range(10, len(closes)): + d[i] = (closes[i] - closes[(i - 10)]) + return super_smoother(d, period) + +def ind_trend_intensity(closes, period): + sma = list(sma_v(closes, period)) + o = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if ((i + 1) < int(period)): + continue + pos = 0.0 + neg = 0.0 + for j in range(0, period): + d = (closes[(i - int(j))] - sma[i]) + if (d > 0.0): + pos += d + else: + neg -= d + o[i] = (((100.0 * pos) / (pos + neg)) if ((pos + neg) > 0.0) else 50.0) + return o + +def ind_true_range(series, period=1): + return tr(series) + +def ind_twiggs_money_flow(series, period=21): + th = [0.0] * (len(series)) + tl = [0.0] * (len(series)) + for i in range(0, len(series)): + th[i] = series[i][1] + tl[i] = series[i][2] + if (i > 0): + th[i] = max(th[i], series[(i - 1)][3]) + tl[i] = min(tl[i], series[(i - 1)][3]) + adv = [0.0] * (len(series)) + vol = [0.0] * (len(series)) + for i in range(0, len(series)): + range_ = (th[i] - tl[i]) + clv = ((((series[i][3] - tl[i]) - (th[i] - series[i][3])) / range_) if (range_ != 0.0) else 0.0) + adv[i] = (clv * series[i][4]) + vol[i] = series[i][4] + sa = list(ema_239a7b94(adv, period)) + sv = list(ema_239a7b94(vol, period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if ((math.isfinite(sa[i]) and math.isfinite(sv[i])) and (sv[i] != 0.0)): + o[i] = (sa[i] / sv[i]) + return o + +def ind_typical_price(series, period=1): + return _typical(series) + +def ind_ut_bot(series, period, mult): + atr = list(atr_v(series, period)) + o = [float("nan")] * (len(series)) + if (not series): + return o + stop = 0.0 + have = False + for i in range(0, len(series)): + if (not math.isfinite(atr[i])): + continue + c = series[i][3] + if (not have): + stop = (c - (mult * atr[i])) + have = True + else: + prev = stop + if ((c > prev) and ((i < 2) or (series[(i - 1)][3] > prev))): + stop = max(prev, (c - (mult * atr[i]))) + elif ((c < prev) and ((i < 2) or (series[(i - 1)][3] < prev))): + stop = min(prev, (c + (mult * atr[i]))) + else: + stop = prev + o[i] = stop + return o + +def ind_ulcer_index(series, period=14): + c = list(_closes(series)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (i < int((period - 1))): + continue + mx = c[i] + for j in range(1, period): + mx = max(mx, c[(i - int(j))]) + s = 0.0 + for j in range(0, period): + dd = ((100.0 * (c[(i - int(j))] - mx)) / mx) + s += (dd * dd) + o[i] = math.sqrt((s / period)) + return o + +def ind_ultimate_oscillator(s, p1=7, p2=14, p3=28): + n = len(s) + out = [float("nan")] * (n) + bp = [0.0] * (n) + tr = [0.0] * (n) + for i in range(1, n): + lo = min(s[i][2], s[(i - 1)][3]) + hi = max(s[i][1], s[(i - 1)][3]) + bp[i] = (s[i][3] - lo) + tr[i] = (hi - lo) + def avg(p, i): + sb = 0.0 + st = 0.0 + for k in range(0, p): + sb += bp[(i - int(k))] + st += tr[(i - int(k))] + return (0.0 if (st == 0.0) else (sb / st)) + for i in range(int(p3), n): + out[i] = ((100.0 * (((4.0 * avg(p1, i)) + (2.0 * avg(p2, i))) + avg(p3, i))) / 7.0) + return out + +def ind_up_down_ratio(series, period=14): + c = list(_closes(series)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (i < int(period)): + continue + up = 0 + dn = 0 + for j in range(0, period): + if (c[(i - int(j))] > c[((i - int(j)) - 1)]): + up += 1 + elif (c[(i - int(j))] < c[((i - int(j)) - 1)]): + dn += 1 + o[i] = ((float(up) / dn) if (dn != 0) else float(up)) + return o + +def ind_up_down_volume_ratio(series, period=14): + up = [0.0] * (len(series)) + dn = [0.0] * (len(series)) + for i in range(0, len(series)): + if ((i > 0) and (series[i][3] > series[(i - 1)][3])): + up[i] = series[i][4] + elif ((i > 0) and (series[i][3] < series[(i - 1)][3])): + dn[i] = series[i][4] + su = list(sma_58520e20(up, period)) + sd = list(sma_58520e20(dn, period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if ((math.isfinite(su[i]) and math.isfinite(sd[i])) and (sd[i] != 0.0)): + o[i] = (su[i] / sd[i]) + return o + +def ind_vhf(series, period): + cl = list(_closes(series)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if ((i + 1) < int(period)): + continue + range_ = (highest_v(cl, i, period) - lowest_v(cl, i, period)) + sum_ = 0.0 + for j in range(0, period): + k = (i - int(j)) + if (k > 0): + sum_ += abs((cl[k] - cl[(k - 1)])) + o[i] = ((range_ / sum_) if (sum_ > 0.0) else 0.0) + return o + +def ind_vidya(closes, period): + o = [float("nan")] * (len(closes)) + if (period < 1): + period = 1 + prev = float("nan") + for i in range(0, len(closes)): + if ((i + 1) < int(period)): + continue + up = 0.0 + dn = 0.0 + for j in range((((i + 1) - int(period)) + 1), (i + 1)): + d = (closes[j] - closes[(j - 1)]) + if (d > 0.0): + up += d + else: + dn -= d + cmo = (((100.0 * (up - dn)) / (up + dn)) if ((up + dn) > 0.0) else 0.0) + alpha = (((2.0 / (period + 1.0)) * abs(cmo)) / 100.0) + if (not math.isfinite(prev)): + prev = closes[i] + o[i] = prev + continue + prev = (prev + (alpha * (closes[i] - prev))) + o[i] = prev + return o + +def ind_vwap(series, period=1): + tp = list(_typical(series)) + o = [float("nan")] * (len(series)) + pv = 0.0 + vv = 0.0 + for i in range(0, len(series)): + pv += (tp[i] * series[i][4]) + vv += series[i][4] + if (vv != 0.0): + o[i] = (pv / vv) + return o + +def ind_vwap_bands(series, period=1, mult=1.0): + tp = list(_typical(series)) + r = SimpleNamespace(upper=[], vwap=[], lower=[]) + r.upper = [float("nan")] * (len(series)) + r.vwap = [float("nan")] * (len(series)) + r.lower = [float("nan")] * (len(series)) + pv = 0.0 + vv = 0.0 + pv2 = 0.0 + for i in range(0, len(series)): + pv += (tp[i] * series[i][4]) + vv += series[i][4] + pv2 += ((tp[i] * tp[i]) * series[i][4]) + if (vv == 0.0): + continue + mean = (pv / vv) + var = ((pv2 / vv) - (mean * mean)) + sd = math.sqrt((var if (var > 0) else 0.0)) + r.vwap[i] = mean + r.upper[i] = (mean + (mult * sd)) + r.lower[i] = (mean - (mult * sd)) + return r + +def ind_vwema(series, period): + cv = [0.0] * (len(series)) + vol = list(_volumes(series)) + for i in range(0, len(series)): + cv[i] = (series[i][3] * series[i][4]) + num = list(ema_v(cv, period)) + den = list(ema_v(vol, period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if ((math.isfinite(num[i]) and math.isfinite(den[i])) and (den[i] != 0.0)): + o[i] = (num[i] / den[i]) + return o + +def ind_vwma(series, period): + o = [float("nan")] * (len(series)) + if (period < 1): + period = 1 + for i in range(0, len(series)): + if ((i + 1) < int(period)): + continue + num = 0.0 + den = 0.0 + for j in range(0, period): + num += (series[(i - int(j))][3] * series[(i - int(j))][4]) + den += series[(i - int(j))][4] + o[i] = ((num / den) if (den > 0.0) else float("nan")) + return o + +def ind_variance(series, period=20): + sd = list(stddev_7bc07ae7(_closes(series), period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if math.isfinite(sd[i]): + o[i] = (sd[i] * sd[i]) + return o + +def ind_volatility_ratio(series, period=14): + t = list(tr(series)) + mt = list(sma_58520e20(t, period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if ((math.isfinite(t[i]) and math.isfinite(mt[i])) and (mt[i] != 0.0)): + o[i] = (t[i] / mt[i]) + return o + +def ind_volatility_stop(series, period=14, mult=3.0): + a = list(atr(series, period)) + o = [float("nan")] * (len(series)) + stop = float("nan") + is_long = True + for i in range(0, len(series)): + if (not math.isfinite(a[i])): + continue + if (not math.isfinite(stop)): + stop = (series[i][3] - (mult * a[i])) + is_long = True + o[i] = stop + continue + if is_long: + stop = max(stop, (series[i][3] - (mult * a[i]))) + if (series[i][3] < stop): + is_long = False + stop = (series[i][3] + (mult * a[i])) + else: + stop = min(stop, (series[i][3] + (mult * a[i]))) + if (series[i][3] > stop): + is_long = True + stop = (series[i][3] - (mult * a[i])) + o[i] = stop + return o + +def ind_volume_average(series, period=20): + return sma_58520e20(_volumes(series), period) + +def ind_volume_delta(series, period=1): + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + range_ = (series[i][1] - series[i][2]) + clv = ((((series[i][3] - series[i][2]) - (series[i][1] - series[i][3])) / range_) if (range_ != 0.0) else 0.0) + o[i] = (clv * series[i][4]) + return o + +def ind_volume_oscillator(series, period=14): + v = list(_volumes(series)) + fast = list(ema_239a7b94(v, 5)) + slow = list(ema_239a7b94(v, 10)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if ((math.isfinite(fast[i]) and math.isfinite(slow[i])) and (slow[i] != 0.0)): + o[i] = ((100.0 * (fast[i] - slow[i])) / slow[i]) + return o + +def ind_volume_price_trend(series, period=1): + o = [float("nan")] * (len(series)) + acc = 0.0 + for i in range(0, len(series)): + if ((i > 0) and (series[(i - 1)][3] != 0.0)): + acc += ((series[i][4] * (series[i][3] - series[(i - 1)][3])) / series[(i - 1)][3]) + o[i] = acc + return o + +def ind_volume_rate_of_change(series, period=14): + v = list(_volumes(series)) + o = [float("nan")] * (len(series)) + for i in range(int(period), len(series)): + if (v[(i - int(period))] != 0.0): + o[i] = ((100.0 * (v[i] - v[(i - int(period))])) / v[(i - int(period))]) + return o + +def ind_volume_weighted_moving_average(series, period=20): + c = list(_closes(series)) + v = list(_volumes(series)) + cv = [0.0] * (len(series)) + for i in range(0, len(series)): + cv[i] = (c[i] * v[i]) + sc = list(sma_58520e20(cv, period)) + sv = list(sma_58520e20(v, period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (math.isfinite(sc[i]) and (sv[i] != 0.0)): + o[i] = (sc[i] / sv[i]) + return o + +def ind_volume_zone_oscillator(series, period=14): + r = [0.0] * (len(series)) + vp = [0.0] * (len(series)) + vn = [0.0] * (len(series)) + for i in range(0, len(series)): + if ((i > 0) and (series[i][3] > series[(i - 1)][3])): + r[i] = 1.0 + elif ((i > 0) and (series[i][3] < series[(i - 1)][3])): + r[i] = (-1.0) + v = series[i][4] + if (r[i] > 0): + vp[i] = v + elif (r[i] < 0): + vn[i] = v + svp = list(ema_239a7b94(vp, period)) + svn = list(ema_239a7b94(vn, period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + tot = (svp[i] + svn[i]) + if ((math.isfinite(svp[i]) and math.isfinite(svn[i])) and (tot != 0.0)): + o[i] = ((100.0 * (svp[i] - svn[i])) / tot) + return o + +def ind_vortex(series, period): + r = SimpleNamespace(plus=[], minus=[]) + r.plus = [float("nan")] * (len(series)) + r.minus = [float("nan")] * (len(series)) + if (period < 1): + period = 1 + tr = list(tr_v(series)) + for i in range(0, len(series)): + if (i < int(period)): + continue + vmp = 0.0 + vmm = 0.0 + trs = 0.0 + for j in range(0, period): + k = (i - int(j)) + vmp += abs((series[k][1] - series[(k - 1)][2])) + vmm += abs((series[k][2] - series[(k - 1)][1])) + trs += tr[k] + if (trs > 0.0): + r.plus[i] = (vmp / trs) + r.minus[i] = (vmm / trs) + return r + +def ind_wma(closes, period): + return wma_v(closes, period) + +def ind_wave_trend(s, esa=10, d=21): + tp = list(_typical(s)) + esa_v = list(ema_51fe74d0(tp, esa)) + dev = [float("nan")] * (len(tp)) + for i in range(0, len(tp)): + if math.isfinite(esa_v[i]): + dev[i] = abs((tp[i] - esa_v[i])) + dv = list(ema_51fe74d0(dev, esa)) + ci = [float("nan")] * (len(tp)) + for i in range(0, len(tp)): + if ((math.isfinite(esa_v[i]) and math.isfinite(dv[i])) and (dv[i] != 0.0)): + ci[i] = ((tp[i] - esa_v[i]) / (0.015 * dv[i])) + return ema_51fe74d0(ci, d) + +def ind_weighted_close(series, period=1): + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + o[i] = (((series[i][1] + series[i][2]) + (2.0 * series[i][3])) / 4.0) + return o + +def ind_wilder_volatility_system(series, period=14, mult=3.0): + a = list(atr(series, period)) + o = [float("nan")] * (len(series)) + stop = float("nan") + is_long = True + for i in range(0, len(series)): + if (not math.isfinite(a[i])): + continue + if (not math.isfinite(stop)): + stop = (series[i][1] - (mult * a[i])) + is_long = True + o[i] = stop + continue + if is_long: + cand = (series[i][1] - (mult * a[i])) + stop = max(stop, cand) + if (series[i][3] < stop): + is_long = False + stop = (series[i][2] + (mult * a[i])) + else: + cand = (series[i][2] + (mult * a[i])) + stop = min(stop, cand) + if (series[i][3] > stop): + is_long = True + stop = (series[i][1] - (mult * a[i])) + o[i] = stop + return o + +def ind_wilders_ma(closes, period): + return smma_v(closes, period) + +def ind_williams_ad(s, dummy=0): + n = len(s) + out = [float("nan")] * (n) + run = 0.0 + for i in range(0, n): + if (i == 0): + out[i] = 0.0 + continue + C = s[i][3] + C1 = s[(i - 1)][3] + H = s[i][1] + L = s[i][2] + if (C > C1): + run += (C - min(L, C1)) + elif (C < C1): + run -= (max(H, C1) - C) + out[i] = run + return out + +def ind_williams_r(s, period=14): + h = list(_highs(s)) + l = list(_lows(s)) + c = list(_closes(s)) + out = [float("nan")] * (len(c)) + for i in range(0, len(c)): + if (i < int((period - 1))): + continue + hi = highest(h, i, period) + lo = lowest(l, i, period) + out[i] = (0.0 if (hi == lo) else (((-100.0) * (hi - c[i])) / (hi - lo))) + return out + +def ind_woodie_pivot_points(series, period=1): + r = SimpleNamespace(pivot=[], r1=[], s1=[]) + r.pivot = [float("nan")] * (len(series)) + r.r1 = [float("nan")] * (len(series)) + r.s1 = [float("nan")] * (len(series)) + for i in range(1, len(series)): + p = (((series[(i - 1)][1] + series[(i - 1)][2]) + (2.0 * series[(i - 1)][3])) / 4.0) + r.pivot[i] = p + r.r1[i] = ((2.0 * p) - series[(i - 1)][2]) + r.s1[i] = ((2.0 * p) - series[(i - 1)][1]) + return r + +def ind_yang_zhang_volatility(series, period=20): + c = list(_closes(series)) + o = list(_opens(series)) + lr_oc = [float("nan")] * (len(series)) + lr_co = [float("nan")] * (len(series)) + for i in range(1, len(series)): + if ((o[i] > 0) and (c[(i - 1)] > 0)): + lr_oc[i] = math.log((o[i] / c[(i - 1)])) + if ((c[i] > 0) and (o[i] > 0)): + lr_co[i] = math.log((c[i] / o[i])) + out = [float("nan")] * (len(series)) + k = (0.34 / (1.34 + ((period + 1.0) / (period - 1.0)))) + for i in range(0, len(series)): + if (i < int(period)): + continue + so = 0.0 + sc = 0.0 + mo = 0.0 + mc = 0.0 + n = 0 + for j in range(0, period): + idx = (i - int(j)) + if ((not math.isfinite(lr_oc[idx])) or (not math.isfinite(lr_co[idx]))): + continue + mo += lr_oc[idx] + mc += lr_co[idx] + n += 1 + if (n < period): + continue + mo /= n + mc /= n + for j in range(0, period): + idx = (i - int(j)) + so += ((lr_oc[idx] - mo) * (lr_oc[idx] - mo)) + sc += ((lr_co[idx] - mc) * (lr_co[idx] - mc)) + rs = 0.0 + ok = True + for j in range(0, period): + b = series[(i - int(j))] + if ((((b[1] <= 0) or (b[2] <= 0)) or (b[0] <= 0)) or (b[3] <= 0)): + ok = False + break + rs += ((math.log((b[1] / b[3])) * math.log((b[1] / b[0]))) + (math.log((b[2] / b[3])) * math.log((b[2] / b[0])))) + if (not ok): + continue + var = (((so / (period - 1)) + ((k * sc) / (period - 1))) + (((1.0 - k) * rs) / period)) + out[i] = (((100.0 * math.sqrt(var)) * math.sqrt(252.0)) if (var > 0) else 0.0) + return out + +def ind_zlema(closes, period): + lag = ((period - 1) // 2) + z = [0.0] * (len(closes)) + for i in range(0, len(closes)): + prev = (closes[(i - int(lag))] if (i >= int(lag)) else closes[0]) + z[i] = (closes[i] + (closes[i] - prev)) + return ema_v(z, period) + +def ind_z_score(series, period=20): + c = list(_closes(series)) + m = list(sma_58520e20(c, period)) + sd = list(stddev_7bc07ae7(c, period)) + o = [float("nan")] * (len(series)) + for i in range(0, len(series)): + if (math.isfinite(m[i]) and (sd[i] != 0.0)): + o[i] = ((c[i] - m[i]) / sd[i]) + return o + +def ind_zero_lag_macd(closes, fast=12, slow=26, signal=9): + def zlema(v, p): + lag = ((p - 1) // 2) + adj = [float("nan")] * (len(v)) + for i in range(0, len(v)): + if (not math.isfinite(v[i])): + continue + adj[i] = ((v[i] + (v[i] - v[(i - int(lag))])) if ((i >= int(lag)) and math.isfinite(v[(i - int(lag))])) else v[i]) + return ema_51fe74d0(adj, p) + ef = zlema(closes, fast) + es = zlema(closes, slow) + out = [float("nan")] * (len(closes)) + for i in range(0, len(closes)): + if (math.isfinite(ef[i]) and math.isfinite(es[i])): + out[i] = (ef[i] - es[i]) + return out + +def ind_zigzag(series, deviation): + o = [float("nan")] * (len(series)) + if (not series): + return o + last_pivot = series[0][3] + last_idx = 0 + dir = 0 + ext_high = series[0][1] + ext_low = series[0][2] + ext_idx = 0 + for i in range(1, len(series)): + thr = ((last_pivot * deviation) / 100.0) + if ((dir >= 0) and (series[i][1] > ext_high)): + ext_high = series[i][1] + ext_idx = i + if ((dir <= 0) and (series[i][2] < ext_low)): + ext_low = series[i][2] + ext_idx = i + if (dir == 0): + if (series[i][1] >= (last_pivot + thr)): + dir = 1 + ext_high = series[i][1] + ext_idx = i + elif (series[i][2] <= (last_pivot - thr)): + dir = (-1) + ext_low = series[i][2] + ext_idx = i + elif ((dir == 1) and (series[i][2] <= (ext_high - ((ext_high * deviation) / 100.0)))): + o[ext_idx] = ext_high + last_pivot = ext_high + last_idx = ext_idx + dir = (-1) + ext_low = series[i][2] + ext_idx = i + elif ((dir == (-1)) and (series[i][1] >= (ext_low + ((ext_low * deviation) / 100.0)))): + o[ext_idx] = ext_low + last_pivot = ext_low + last_idx = ext_idx + dir = 1 + ext_high = series[i][1] + ext_idx = i + if (dir == 1): + o[ext_idx] = ext_high + elif (dir == (-1)): + o[ext_idx] = ext_low + return o + +# --- registry --- +INDICATOR_INFO = { + 'IndADX': {"func": 'ind_adx', "series": 'bars', "params": [14], "lines": [None]}, + 'IndADXR': {"func": 'ind_adxr', "series": 'bars', "params": [14], "lines": [None]}, + 'IndALMA': {"func": 'ind_alma', "series": 'closes', "params": [9, 0.85, 6.0], "lines": [None]}, + 'IndAPO': {"func": 'ind_apo', "series": 'closes', "params": [12, 26], "lines": [None]}, + 'IndATR': {"func": 'ind_atr', "series": 'bars', "params": [14], "lines": [None]}, + 'IndAcceleratorOscillator': {"func": 'ind_accelerator_oscillator', "series": 'bars', "params": [5, 34, 5], "lines": [None]}, + 'IndAccumulationDistributionLine': {"func": 'ind_accumulation_distribution_line', "series": 'bars', "params": [1], "lines": [None]}, + 'IndAccumulativeSwingIndex': {"func": 'ind_accumulative_swing_index', "series": 'bars', "params": [1.0], "lines": [None]}, + 'IndAdaptiveCyberCycle': {"func": 'ind_adaptive_cyber_cycle', "series": 'closes', "params": [], "lines": [None]}, + 'IndAdaptiveRSI': {"func": 'ind_adaptive_rsi', "series": 'closes', "params": [14], "lines": [None]}, + 'IndAlligatorJaw': {"func": 'ind_alligator_jaw', "series": 'closes', "params": [13, 8], "lines": [None]}, + 'IndAlligatorLips': {"func": 'ind_alligator_lips', "series": 'closes', "params": [5, 3], "lines": [None]}, + 'IndAlligatorTeeth': {"func": 'ind_alligator_teeth', "series": 'closes', "params": [8, 5], "lines": [None]}, + 'IndAnchoredVWAP': {"func": 'ind_anchored_vwap', "series": 'bars', "params": [50], "lines": [None]}, + 'IndAroonDown': {"func": 'ind_aroon_down', "series": 'bars', "params": [14], "lines": [None]}, + 'IndAroonOscillator': {"func": 'ind_aroon_osc', "series": 'bars', "params": [14], "lines": [None]}, + 'IndAroonUp': {"func": 'ind_aroon_up', "series": 'bars', "params": [14], "lines": [None]}, + 'IndAutocorrelation': {"func": 'ind_autocorrelation', "series": 'bars', "params": [20], "lines": [None]}, + 'IndAwesomeOscillator': {"func": 'ind_awesome_oscillator', "series": 'bars', "params": [5, 34], "lines": [None]}, + 'IndBalanceOfPower': {"func": 'ind_balance_of_power', "series": 'bars', "params": [14], "lines": [None]}, + 'IndBearPower': {"func": 'ind_bear_power', "series": 'bars', "params": [13], "lines": [None]}, + 'IndBollingerBands': {"func": 'ind_bollinger_bands', "series": 'bars', "params": [20, 2.0], "lines": [('field', 'upper'), ('field', 'middle'), ('field', 'lower')]}, + 'IndBollingerBandwidth': {"func": 'ind_bollinger_bandwidth', "series": 'bars', "params": [20, 2.0], "lines": [None]}, + 'IndBollingerPercentB': {"func": 'ind_bollinger_percent_b', "series": 'bars', "params": [20, 2.0], "lines": [None]}, + 'IndBullPower': {"func": 'ind_bull_power', "series": 'bars', "params": [13], "lines": [None]}, + 'IndCCI': {"func": 'ind_cci', "series": 'bars', "params": [20], "lines": [None]}, + 'IndCamarillaPivotPoints': {"func": 'ind_camarilla_pivot_points', "series": 'bars', "params": [1], "lines": [('field', 'pivot'), ('field', 'r1'), ('field', 's1')]}, + 'IndCenterOfGravity': {"func": 'ind_center_of_gravity', "series": 'closes', "params": [10], "lines": [None]}, + 'IndChaikinMoneyFlow': {"func": 'ind_chaikin_money_flow', "series": 'bars', "params": [20], "lines": [None]}, + 'IndChaikinOscillator': {"func": 'ind_chaikin_oscillator', "series": 'bars', "params": [14], "lines": [None]}, + 'IndChaikinVolatility': {"func": 'ind_chaikin_volatility', "series": 'bars', "params": [10], "lines": [None]}, + 'IndChandeForecastOscillator': {"func": 'ind_chande_forecast_oscillator', "series": 'closes', "params": [5], "lines": [None]}, + 'IndChandeKrollStop': {"func": 'ind_chande_kroll_stop', "series": 'bars', "params": [10, 1.0], "lines": [None]}, + 'IndChandeMomentumOscillator': {"func": 'ind_chande_momentum_oscillator', "series": 'closes', "params": [20], "lines": [None]}, + 'IndChandelierExit': {"func": 'ind_chandelier_exit', "series": 'bars', "params": [22, 3.0], "lines": [('field', 'long_exit'), ('field', 'short_exit')]}, + 'IndChandelierExitLong': {"func": 'ind_chandelier_long', "series": 'bars', "params": [22, 3.0], "lines": [None]}, + 'IndChandelierExitShort': {"func": 'ind_chandelier_short', "series": 'bars', "params": [22, 3.0], "lines": [None]}, + 'IndChikouSpan': {"func": 'ind_chikou_span', "series": 'closes', "params": [26], "lines": [None]}, + 'IndChoppinessIndex': {"func": 'ind_choppiness_index', "series": 'bars', "params": [14], "lines": [None]}, + 'IndCloseVolatility': {"func": 'ind_close_volatility', "series": 'bars', "params": [20], "lines": [None]}, + 'IndConnorsRSI': {"func": 'ind_connors_rsi', "series": 'bars', "params": [], "lines": [None]}, + 'IndCoppockCurve': {"func": 'ind_coppock_curve', "series": 'closes', "params": [14, 11, 10], "lines": [None]}, + 'IndCorrelation': {"func": 'ind_correlation', "series": 'bars', "params": [20], "lines": [None]}, + 'IndCorrelationCoefficient': {"func": 'ind_correlation_coefficient', "series": 'closes', "params": [14], "lines": [None]}, + 'IndCovariance': {"func": 'ind_covariance', "series": 'bars', "params": [20], "lines": [None]}, + 'IndCumulativeVolumeDelta': {"func": 'ind_cumulative_volume_delta', "series": 'bars', "params": [1], "lines": [None]}, + 'IndCutlerRSI': {"func": 'ind_cutler_rsi', "series": 'closes', "params": [14], "lines": [None]}, + 'IndCyberCycle': {"func": 'ind_cyber_cycle', "series": 'closes', "params": [], "lines": [None]}, + 'IndDEMA': {"func": 'ind_dema', "series": 'closes', "params": [14], "lines": [None]}, + 'IndDPO': {"func": 'ind_dpo', "series": 'closes', "params": [20], "lines": [None]}, + 'IndDSS': {"func": 'ind_dss', "series": 'bars', "params": [10, 3], "lines": [None]}, + 'IndDX': {"func": 'ind_dx', "series": 'bars', "params": [14], "lines": [None]}, + 'IndDeMarker': {"func": 'ind_demarker', "series": 'bars', "params": [14], "lines": [None]}, + 'IndDecycler': {"func": 'ind_decycler', "series": 'closes', "params": [10], "lines": [None]}, + 'IndDemandIndex': {"func": 'ind_demand_index', "series": 'bars', "params": [14], "lines": [None]}, + 'IndDetrendedPriceOscillator': {"func": 'ind_detrended_price_oscillator', "series": 'closes', "params": [20], "lines": [None]}, + 'IndDisparityIndex': {"func": 'ind_disparity_index', "series": 'closes', "params": [20], "lines": [None]}, + 'IndDominantCycle': {"func": 'ind_dominant_cycle', "series": 'closes', "params": [], "lines": [None]}, + 'IndDominantCyclePeriod': {"func": 'ind_dominant_cycle_period', "series": 'bars', "params": [50], "lines": [None]}, + 'IndDonchianChannels': {"func": 'ind_donchian_channels', "series": 'bars', "params": [20], "lines": [('field', 'upper'), ('field', 'middle'), ('field', 'lower')]}, + 'IndDonchianLower': {"func": 'ind_donchian_lower', "series": 'bars', "params": [20], "lines": [None]}, + 'IndDonchianMiddle': {"func": 'ind_donchian_middle', "series": 'bars', "params": [20], "lines": [None]}, + 'IndDonchianUpper': {"func": 'ind_donchian_upper', "series": 'bars', "params": [20], "lines": [None]}, + 'IndDoubleStochastic': {"func": 'ind_double_stochastic', "series": 'bars', "params": [14, 5, 3], "lines": [None]}, + 'IndDynamicMomentumIndex': {"func": 'ind_dynamic_momentum_index', "series": 'closes', "params": [14], "lines": [None]}, + 'IndEMA': {"func": 'ind_ema', "series": 'closes', "params": [14], "lines": [None]}, + 'IndEaseOfMovement': {"func": 'ind_ease_of_movement', "series": 'bars', "params": [14], "lines": [None]}, + 'IndEfficiencyRatio': {"func": 'ind_efficiency_ratio', "series": 'bars', "params": [10], "lines": [None]}, + 'IndEhlersDecycler': {"func": 'ind_ehlers_decycler', "series": 'closes', "params": [10], "lines": [None]}, + 'IndEhlersSmoothedRSI': {"func": 'ind_ehlers_smoothed_rsi', "series": 'closes', "params": [14], "lines": [None]}, + 'IndEhlersSuperSmoother': {"func": 'ind_ehlers_super_smoother', "series": 'closes', "params": [10], "lines": [None]}, + 'IndEhlersTrendline': {"func": 'ind_ehlers_trendline', "series": 'closes', "params": [0.07], "lines": [None]}, + 'IndElderForceIndex': {"func": 'ind_elder_force_index', "series": 'bars', "params": [13], "lines": [None]}, + 'IndElderImpulse': {"func": 'ind_elder_impulse', "series": 'bars', "params": [13, 12, 26], "lines": [None]}, + 'IndElderRayBear': {"func": 'ind_elder_ray_bear', "series": 'bars', "params": [13], "lines": [None]}, + 'IndElderRayBull': {"func": 'ind_elder_ray_bull', "series": 'bars', "params": [13], "lines": [None]}, + 'IndElderSafeZone': {"func": 'ind_elder_safe_zone', "series": 'bars', "params": [10, 2.0], "lines": [None]}, + 'IndErgodicOscillator': {"func": 'ind_ergodic_oscillator', "series": 'closes', "params": [5, 3], "lines": [None]}, + 'IndEvenBetterSineWave': {"func": 'ind_even_better_sinewave', "series": 'closes', "params": [10, 48], "lines": [('field', 'sine'), ('field', 'lead_sine')]}, + 'IndFAMA': {"func": 'ind_fama', "series": 'closes', "params": [0.5, 0.05], "lines": [None]}, + 'IndFRAMA': {"func": 'ind_frama', "series": 'closes', "params": [16], "lines": [None]}, + 'IndFibonacciPivotPoints': {"func": 'ind_fibonacci_pivot_points', "series": 'bars', "params": [1], "lines": [('field', 'pivot'), ('field', 'r1'), ('field', 's1')]}, + 'IndFisherTransform': {"func": 'ind_fisher_transform', "series": 'closes', "params": [10], "lines": [None]}, + 'IndFractalDimension': {"func": 'ind_fractal_dimension', "series": 'bars', "params": [50], "lines": [None]}, + 'IndFractalDimensionIndex': {"func": 'ind_fractal_dimension_index', "series": 'closes', "params": [30], "lines": [None]}, + 'IndFractalDown': {"func": 'ind_fractal_down', "series": 'bars', "params": [], "lines": [None]}, + 'IndFractalUp': {"func": 'ind_fractal_up', "series": 'bars', "params": [], "lines": [None]}, + 'IndGannHiLoActivator': {"func": 'ind_gann_hilo_activator', "series": 'bars', "params": [3], "lines": [None]}, + 'IndGannSwingOscillator': {"func": 'ind_gann_swing_oscillator', "series": 'bars', "params": [], "lines": [None]}, + 'IndGarmanKlassVolatility': {"func": 'ind_garman_klass_volatility', "series": 'bars', "params": [20], "lines": [None]}, + 'IndGatorOscillator': {"func": 'ind_gator', "series": 'closes', "params": [], "lines": [('field', 'upper'), ('field', 'lower')]}, + 'IndGaussianMA': {"func": 'ind_gaussian_ma', "series": 'closes', "params": [14], "lines": [None]}, + 'IndGopalakrishnanRangeIndex': {"func": 'ind_gopalakrishnan_range_index', "series": 'bars', "params": [20], "lines": [None]}, + 'IndGuppyMMA': {"func": 'ind_guppy_mma', "series": 'closes', "params": [], "lines": [('index', 0), ('index', 1), ('index', 2), ('index', 3), ('index', 4), ('index', 5), ('index', 6), ('index', 7), ('index', 8), ('index', 9), ('index', 10), ('index', 11)]}, + 'IndHMA': {"func": 'ind_hma', "series": 'closes', "params": [16], "lines": [None]}, + 'IndHalfTrend': {"func": 'ind_half_trend', "series": 'bars', "params": [2, 2.0], "lines": [None]}, + 'IndHighLowRange': {"func": 'ind_high_low_range', "series": 'bars', "params": [20], "lines": [None]}, + 'IndHistoricalVolatility': {"func": 'ind_historical_volatility', "series": 'bars', "params": [20], "lines": [None]}, + 'IndHurstExponent': {"func": 'ind_hurst_exponent', "series": 'bars', "params": [50], "lines": [None]}, + 'IndInertia': {"func": 'ind_inertia', "series": 'closes', "params": [20], "lines": [None]}, + 'IndIntradayIntensityIndex': {"func": 'ind_intraday_intensity_index', "series": 'bars', "params": [21], "lines": [None]}, + 'IndIntradayMomentumIndex': {"func": 'ind_intraday_momentum_index', "series": 'bars', "params": [14], "lines": [None]}, + 'IndInverseFisherTransform': {"func": 'ind_inverse_fisher_transform', "series": 'closes', "params": [14], "lines": [None]}, + 'IndJurikMovingAverage': {"func": 'ind_jurik_moving_average', "series": 'closes', "params": [20], "lines": [None]}, + 'IndJurikVelocity': {"func": 'ind_jurik_velocity', "series": 'closes', "params": [14], "lines": [None]}, + 'IndKAMA': {"func": 'ind_kama', "series": 'closes', "params": [10, 2, 30], "lines": [None]}, + 'IndKDJ': {"func": 'ind_kdj', "series": 'bars', "params": [9, 3], "lines": [('field', 'k'), ('field', 'd'), ('field', 'j')]}, + 'IndKST': {"func": 'ind_kst', "series": 'closes', "params": [], "lines": [None]}, + 'IndKairi': {"func": 'ind_kairi', "series": 'closes', "params": [25], "lines": [None]}, + 'IndKeltnerBandwidth': {"func": 'ind_keltner_bandwidth', "series": 'bars', "params": [20, 2.0], "lines": [None]}, + 'IndKeltnerChannels': {"func": 'ind_keltner_channels', "series": 'bars', "params": [20, 2.0], "lines": [('field', 'upper'), ('field', 'middle'), ('field', 'lower')]}, + 'IndKijunSen': {"func": 'ind_kijun_sen', "series": 'bars', "params": [26], "lines": [None]}, + 'IndKlingerVolumeOscillator': {"func": 'ind_klinger_volume_oscillator', "series": 'bars', "params": [14], "lines": [('field', 'kvo'), ('field', 'signal')]}, + 'IndKurtosis': {"func": 'ind_kurtosis', "series": 'bars', "params": [20], "lines": [None]}, + 'IndLSMA': {"func": 'ind_lsma', "series": 'closes', "params": [14], "lines": [None]}, + 'IndLaguerreFilter': {"func": 'ind_laguerre_filter', "series": 'closes', "params": [0.8], "lines": [None]}, + 'IndLaguerreRSI': {"func": 'ind_laguerre_rsi', "series": 'closes', "params": [0.8], "lines": [None]}, + 'IndLinReg': {"func": 'ind_linreg', "series": 'closes', "params": [14], "lines": [None]}, + 'IndLinRegAngle': {"func": 'ind_linreg_angle', "series": 'closes', "params": [14], "lines": [None]}, + 'IndLinRegIntercept': {"func": 'ind_linreg_intercept', "series": 'closes', "params": [14], "lines": [None]}, + 'IndLinRegSlope': {"func": 'ind_linreg_slope', "series": 'closes', "params": [14], "lines": [None]}, + 'IndLinearRegressionForecast': {"func": 'ind_linear_regression_forecast', "series": 'bars', "params": [14], "lines": [None]}, + 'IndLinearRegressionIntercept': {"func": 'ind_linear_regression_intercept', "series": 'bars', "params": [14], "lines": [None]}, + 'IndLinearRegressionOscillator': {"func": 'ind_linear_regression_oscillator', "series": 'closes', "params": [14], "lines": [None]}, + 'IndLinearRegressionSlope': {"func": 'ind_linear_regression_slope', "series": 'bars', "params": [14], "lines": [None]}, + 'IndMACD': {"func": 'ind_macd', "series": 'closes', "params": [12, 26, 9], "lines": [('field', 'macd'), ('field', 'signal'), ('field', 'histogram')]}, + 'IndMACDHistogram': {"func": 'ind_macd_histogram', "series": 'closes', "params": [12, 26, 9], "lines": [None]}, + 'IndMACDofRSI': {"func": 'ind_macd_of_rsi', "series": 'closes', "params": [14, 12, 26], "lines": [None]}, + 'IndMAEnvelopeLower': {"func": 'ind_ma_envelope_lower', "series": 'closes', "params": [20, 2.5], "lines": [None]}, + 'IndMAEnvelopeUpper': {"func": 'ind_ma_envelope_upper', "series": 'closes', "params": [20, 2.5], "lines": [None]}, + 'IndMAMA': {"func": 'ind_mama', "series": 'closes', "params": [0.5, 0.05], "lines": [None]}, + 'IndMassIndex': {"func": 'ind_mass_index', "series": 'bars', "params": [25], "lines": [None]}, + 'IndMcGinley': {"func": 'ind_mcginley', "series": 'closes', "params": [14], "lines": [None]}, + 'IndMedianMA': {"func": 'ind_median_ma', "series": 'closes', "params": [14], "lines": [None]}, + 'IndMedianPrice': {"func": 'ind_median_price', "series": 'bars', "params": [20], "lines": [None]}, + 'IndMinusDI': {"func": 'ind_minus_di', "series": 'bars', "params": [14], "lines": [None]}, + 'IndMomentum': {"func": 'ind_momentum', "series": 'closes', "params": [10], "lines": [None]}, + 'IndMoneyFlowIndex': {"func": 'ind_money_flow_index', "series": 'bars', "params": [14], "lines": [None]}, + 'IndMoneyFlowVolume': {"func": 'ind_money_flow_volume', "series": 'bars', "params": [1], "lines": [None]}, + 'IndMovingAverageRibbon': {"func": 'ind_ma_ribbon', "series": 'closes', "params": [], "lines": [('index', 0), ('index', 1), ('index', 2), ('index', 3), ('index', 4), ('index', 5)]}, + 'IndNATR': {"func": 'ind_natr', "series": 'bars', "params": [14], "lines": [None]}, + 'IndNegativeVolumeIndex': {"func": 'ind_negative_volume_index', "series": 'bars', "params": [1], "lines": [None]}, + 'IndNormalizedROC': {"func": 'ind_normalized_roc', "series": 'closes', "params": [12, 20], "lines": [None]}, + 'IndOBV': {"func": 'ind_obv', "series": 'bars', "params": [1], "lines": [None]}, + 'IndPPO': {"func": 'ind_ppo', "series": 'closes', "params": [12, 26], "lines": [None]}, + 'IndPSAR': {"func": 'ind_psar', "series": 'bars', "params": [0.02, 0.2], "lines": [None]}, + 'IndParkinsonVolatility': {"func": 'ind_parkinson_volatility', "series": 'bars', "params": [20], "lines": [None]}, + 'IndPercentRank': {"func": 'ind_percent_rank', "series": 'closes', "params": [14], "lines": [None]}, + 'IndPercentageVolumeOscillator': {"func": 'ind_percentage_volume_oscillator', "series": 'bars', "params": [14], "lines": [None]}, + 'IndPercentileRank': {"func": 'ind_percentile_rank', "series": 'bars', "params": [20], "lines": [None]}, + 'IndPivotPoint': {"func": 'ind_pivot_point', "series": 'bars', "params": [], "lines": [None]}, + 'IndPlusDI': {"func": 'ind_plus_di', "series": 'bars', "params": [14], "lines": [None]}, + 'IndPositiveVolumeIndex': {"func": 'ind_positive_volume_index', "series": 'bars', "params": [1], "lines": [None]}, + 'IndPrettyGoodOscillator': {"func": 'ind_pretty_good_oscillator', "series": 'bars', "params": [14], "lines": [None]}, + 'IndPriceMomentumOscillator': {"func": 'ind_price_momentum_oscillator', "series": 'closes', "params": [35, 20], "lines": [None]}, + 'IndQStick': {"func": 'ind_qstick', "series": 'bars', "params": [14], "lines": [None]}, + 'IndRMA': {"func": 'ind_rma', "series": 'closes', "params": [14], "lines": [None]}, + 'IndROC': {"func": 'ind_roc', "series": 'closes', "params": [12], "lines": [None]}, + 'IndROCR': {"func": 'ind_rocr', "series": 'closes', "params": [12], "lines": [None]}, + 'IndRSI': {"func": 'ind_rsi', "series": 'closes', "params": [14], "lines": [None]}, + 'IndRSX': {"func": 'ind_rsx', "series": 'closes', "params": [14], "lines": [None]}, + 'IndRSquared': {"func": 'ind_r_squared', "series": 'bars', "params": [14], "lines": [None]}, + 'IndRWIHigh': {"func": 'ind_rwi_high', "series": 'bars', "params": [14], "lines": [None]}, + 'IndRWILow': {"func": 'ind_rwi_low', "series": 'bars', "params": [14], "lines": [None]}, + 'IndRainbowOscillator': {"func": 'ind_rainbow_oscillator', "series": 'closes', "params": [10], "lines": [None]}, + 'IndRangeExpansionIndex': {"func": 'ind_range_expansion_index', "series": 'bars', "params": [8], "lines": [None]}, + 'IndReflex': {"func": 'ind_reflex', "series": 'bars', "params": [10], "lines": [None]}, + 'IndRegressionChannel': {"func": 'ind_regression_channel', "series": 'closes', "params": [20, 2.0], "lines": [('field', 'upper'), ('field', 'mid'), ('field', 'lower')]}, + 'IndRelativeMomentumIndex': {"func": 'ind_relative_momentum_index', "series": 'closes', "params": [20, 5], "lines": [None]}, + 'IndRelativeVigorIndex': {"func": 'ind_relative_vigor_index', "series": 'bars', "params": [10], "lines": [None]}, + 'IndRelativeVolatilityIndex': {"func": 'ind_relative_volatility_index', "series": 'bars', "params": [10], "lines": [None]}, + 'IndRelativeVolume': {"func": 'ind_relative_volume', "series": 'bars', "params": [20], "lines": [None]}, + 'IndRogersSatchellVolatility': {"func": 'ind_rogers_satchell_volatility', "series": 'bars', "params": [20], "lines": [None]}, + 'IndRoofingFilter': {"func": 'ind_roofing_filter', "series": 'closes', "params": [10, 48], "lines": [None]}, + 'IndSMA': {"func": 'ind_sma', "series": 'closes', "params": [14], "lines": [None]}, + 'IndSMI': {"func": 'ind_smi', "series": 'bars', "params": [13], "lines": [None]}, + 'IndSMMA': {"func": 'ind_smma', "series": 'closes', "params": [14], "lines": [None]}, + 'IndSSLChannel': {"func": 'ind_ssl_channel', "series": 'bars', "params": [10], "lines": [None]}, + 'IndSchaffTrendCycle': {"func": 'ind_schaff_trend_cycle', "series": 'closes', "params": [23, 50, 10], "lines": [None]}, + 'IndSenkouSpanA': {"func": 'ind_senkou_span_a', "series": 'bars', "params": [9, 26], "lines": [None]}, + 'IndSenkouSpanB': {"func": 'ind_senkou_span_b', "series": 'bars', "params": [52], "lines": [None]}, + 'IndShannonEntropy': {"func": 'ind_shannon_entropy', "series": 'bars', "params": [20], "lines": [None]}, + 'IndSineWMA': {"func": 'ind_sine_wma', "series": 'closes', "params": [14], "lines": [None]}, + 'IndSineWave': {"func": 'ind_sine_wave', "series": 'closes', "params": [], "lines": [('field', 'sine'), ('field', 'lead_sine')]}, + 'IndSkewness': {"func": 'ind_skewness', "series": 'bars', "params": [20], "lines": [None]}, + 'IndSmoothedROC': {"func": 'ind_smoothed_roc', "series": 'closes', "params": [12, 25], "lines": [None]}, + 'IndSpearmanRank': {"func": 'ind_spearman_rank', "series": 'closes', "params": [14], "lines": [None]}, + 'IndSpecialK': {"func": 'ind_special_k', "series": 'closes', "params": [], "lines": [None]}, + 'IndStandardError': {"func": 'ind_standard_error', "series": 'bars', "params": [14], "lines": [None]}, + 'IndStandardPivotPoints': {"func": 'ind_standard_pivot_points', "series": 'bars', "params": [1], "lines": [('field', 'pivot'), ('field', 'r1'), ('field', 's1')]}, + 'IndStdDev': {"func": 'ind_stddev', "series": 'bars', "params": [20], "lines": [None]}, + 'IndStochRSI': {"func": 'ind_stoch_rsi', "series": 'closes', "params": [14], "lines": [None]}, + 'IndStochasticFast': {"func": 'ind_stochastic_fast', "series": 'bars', "params": [14, 3], "lines": [('field', 'k'), ('field', 'd')]}, + 'IndStochasticFull': {"func": 'ind_stochastic_full', "series": 'bars', "params": [14, 3, 3], "lines": [('field', 'k'), ('field', 'd')]}, + 'IndStochasticPop': {"func": 'ind_stochastic_pop', "series": 'bars', "params": [14], "lines": [None]}, + 'IndStochasticSlow': {"func": 'ind_stochastic_slow', "series": 'bars', "params": [14, 3], "lines": [('field', 'k'), ('field', 'd')]}, + 'IndSuperSmoother': {"func": 'ind_super_smoother', "series": 'closes', "params": [10], "lines": [None]}, + 'IndSupertrend': {"func": 'ind_supertrend', "series": 'bars', "params": [10, 3.0], "lines": [None]}, + 'IndSwenlinTradingOscillator': {"func": 'ind_swenlin_trading_oscillator', "series": 'closes', "params": [35, 20, 10], "lines": [None]}, + 'IndSwingIndex': {"func": 'ind_swing_index', "series": 'bars', "params": [1.0], "lines": [None]}, + 'IndT3': {"func": 'ind_t3', "series": 'closes', "params": [5, 0.7], "lines": [None]}, + 'IndTDSequential': {"func": 'ind_td_sequential', "series": 'closes', "params": [], "lines": [None]}, + 'IndTEMA': {"func": 'ind_tema', "series": 'closes', "params": [14], "lines": [None]}, + 'IndTRIMA': {"func": 'ind_trima', "series": 'closes', "params": [14], "lines": [None]}, + 'IndTRIX': {"func": 'ind_trix', "series": 'closes', "params": [14], "lines": [None]}, + 'IndTSF': {"func": 'ind_tsf', "series": 'closes', "params": [14], "lines": [None]}, + 'IndTSI': {"func": 'ind_tsi', "series": 'closes', "params": [25, 13], "lines": [None]}, + 'IndTSMA': {"func": 'ind_tsma', "series": 'closes', "params": [14], "lines": [None]}, + 'IndTTMSqueeze': {"func": 'ind_ttm_squeeze', "series": 'bars', "params": [20, 2.0], "lines": [('field', 'squeeze'), ('field', 'ratio')]}, + 'IndTenkanSen': {"func": 'ind_tenkan_sen', "series": 'bars', "params": [9], "lines": [None]}, + 'IndTrendFlex': {"func": 'ind_trend_flex', "series": 'closes', "params": [10], "lines": [None]}, + 'IndTrendIntensityIndex': {"func": 'ind_trend_intensity', "series": 'closes', "params": [30], "lines": [None]}, + 'IndTrueRange': {"func": 'ind_true_range', "series": 'bars', "params": [1], "lines": [None]}, + 'IndTwiggsMoneyFlow': {"func": 'ind_twiggs_money_flow', "series": 'bars', "params": [21], "lines": [None]}, + 'IndTypicalPrice': {"func": 'ind_typical_price', "series": 'bars', "params": [1], "lines": [None]}, + 'IndUTBot': {"func": 'ind_ut_bot', "series": 'bars', "params": [10, 1.0], "lines": [None]}, + 'IndUlcerIndex': {"func": 'ind_ulcer_index', "series": 'bars', "params": [14], "lines": [None]}, + 'IndUltimateOscillator': {"func": 'ind_ultimate_oscillator', "series": 'bars', "params": [7, 14, 28], "lines": [None]}, + 'IndUpDownRatio': {"func": 'ind_up_down_ratio', "series": 'bars', "params": [14], "lines": [None]}, + 'IndUpDownVolumeRatio': {"func": 'ind_up_down_volume_ratio', "series": 'bars', "params": [14], "lines": [None]}, + 'IndVHF': {"func": 'ind_vhf', "series": 'bars', "params": [28], "lines": [None]}, + 'IndVIDYA': {"func": 'ind_vidya', "series": 'closes', "params": [14], "lines": [None]}, + 'IndVWAP': {"func": 'ind_vwap', "series": 'bars', "params": [1], "lines": [None]}, + 'IndVWAPBands': {"func": 'ind_vwap_bands', "series": 'bars', "params": [1, 1.0], "lines": [('field', 'upper'), ('field', 'vwap'), ('field', 'lower')]}, + 'IndVWEMA': {"func": 'ind_vwema', "series": 'bars', "params": [14], "lines": [None]}, + 'IndVWMA': {"func": 'ind_vwma', "series": 'bars', "params": [20], "lines": [None]}, + 'IndVariance': {"func": 'ind_variance', "series": 'bars', "params": [20], "lines": [None]}, + 'IndVolatilityRatio': {"func": 'ind_volatility_ratio', "series": 'bars', "params": [14], "lines": [None]}, + 'IndVolatilityStop': {"func": 'ind_volatility_stop', "series": 'bars', "params": [14, 3.0], "lines": [None]}, + 'IndVolumeAverage': {"func": 'ind_volume_average', "series": 'bars', "params": [20], "lines": [None]}, + 'IndVolumeDelta': {"func": 'ind_volume_delta', "series": 'bars', "params": [1], "lines": [None]}, + 'IndVolumeOscillator': {"func": 'ind_volume_oscillator', "series": 'bars', "params": [14], "lines": [None]}, + 'IndVolumePriceTrend': {"func": 'ind_volume_price_trend', "series": 'bars', "params": [1], "lines": [None]}, + 'IndVolumeRateOfChange': {"func": 'ind_volume_rate_of_change', "series": 'bars', "params": [14], "lines": [None]}, + 'IndVolumeWeightedMovingAverage': {"func": 'ind_volume_weighted_moving_average', "series": 'bars', "params": [20], "lines": [None]}, + 'IndVolumeZoneOscillator': {"func": 'ind_volume_zone_oscillator', "series": 'bars', "params": [14], "lines": [None]}, + 'IndVortex': {"func": 'ind_vortex', "series": 'bars', "params": [14], "lines": [('field', 'plus'), ('field', 'minus')]}, + 'IndWMA': {"func": 'ind_wma', "series": 'closes', "params": [14], "lines": [None]}, + 'IndWaveTrend': {"func": 'ind_wave_trend', "series": 'bars', "params": [10, 21], "lines": [None]}, + 'IndWeightedClose': {"func": 'ind_weighted_close', "series": 'bars', "params": [1], "lines": [None]}, + 'IndWilderVolatilitySystem': {"func": 'ind_wilder_volatility_system', "series": 'bars', "params": [14, 3.0], "lines": [None]}, + 'IndWildersMA': {"func": 'ind_wilders_ma', "series": 'closes', "params": [14], "lines": [None]}, + 'IndWilliamsAccumulationDistribution': {"func": 'ind_williams_ad', "series": 'bars', "params": [], "lines": [None]}, + 'IndWilliamsR': {"func": 'ind_williams_r', "series": 'bars', "params": [14], "lines": [None]}, + 'IndWoodiePivotPoints': {"func": 'ind_woodie_pivot_points', "series": 'bars', "params": [1], "lines": [('field', 'pivot'), ('field', 'r1'), ('field', 's1')]}, + 'IndYangZhangVolatility': {"func": 'ind_yang_zhang_volatility', "series": 'bars', "params": [20], "lines": [None]}, + 'IndZLEMA': {"func": 'ind_zlema', "series": 'closes', "params": [14], "lines": [None]}, + 'IndZScore': {"func": 'ind_z_score', "series": 'bars', "params": [20], "lines": [None]}, + 'IndZeroLagMACD': {"func": 'ind_zero_lag_macd', "series": 'closes', "params": [12, 26, 9], "lines": [None]}, + 'IndZigZag': {"func": 'ind_zigzag', "series": 'bars', "params": [5.0], "lines": [None]}, +} + + +def compute_lines(kind, bars, params=None): + """Plotted lines for *kind* from OHLCV *bars*. + + *bars* is a list of (open, high, low, close, volume) + tuples. Returns a list of series (one float per bar, + NaN where the indicator has no value yet), in the + order the widget plots them. *params* overrides the + kind's default parameters positionally. + """ + entry = INDICATOR_INFO[kind] + func = globals()[entry["func"]] + use = list(entry["params"] if params is None else params) + if entry["series"] == "bars": + result = func(bars, *use) + else: + result = func(_closes(bars), *use) + lines = [] + for sel in entry["lines"]: + if sel is None: + lines.append(result) + elif sel[0] == "field": + lines.append(getattr(result, sel[1])) + else: + lines.append(result.lines[sel[1]]) + return lines + + +def _bars(widget): + """Bars a widget plots: its own series when set, else + the built-in demo series (same fallback as StockWidget). + A cleared widget (own series == []) plots nothing. + """ + own = widget._series + if own is not None: + return own + return demo_series() + + +def indicator_names(): + """All 250 indicator palette kinds, in palette order.""" + return list(INDICATOR_INFO) \ No newline at end of file diff --git a/tests/test_indicators_csv.py b/tests/test_indicators_csv.py new file mode 100644 index 0000000..612aeb3 --- /dev/null +++ b/tests/test_indicators_csv.py @@ -0,0 +1,256 @@ +"""Ind* indicator data ingestion: CSV loading + set_series/clear/populate. + +- ``IndicatorWidget.load_csv`` / ``set_series`` / ``get_series`` / + ``add_point`` / ``clear`` / ``populate`` / ``item_count``: the same + series API (and the same ``date,open,high,low,close,volume`` CSV + spec) the StockWidget chart widgets got, but for the 250 Ind* + indicators. +- ``compute_lines``: every one of the 250 kinds recomputes its lines + from loaded OHLCV data without crashing (demo series and the 30-bar + CSV fixture), each line is one value per bar, and the loaded-data + lines differ from the demo lines. Spot values are golden-checked + against the C++ component reference (``ind_*`` functions on the + seeded demo series, seed 42); the full 250-kind cross-check lives + in tools/transpile_indicators.py's verification pass. +- Rendering: every kind draws CSV data headless without raising, the + CSV render differs from the demo render, a one-bar series draws, + and a cleared series draws the no-data placeholder. +""" +import io +import math +import os +import unittest + +import cairo + +from lightgui.xframe import core +from lightgui.xframe import indicators as ind_mod +from lightgui.xframe import stock as stock_mod + +REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +CSV_PATH = os.path.join(REPO, "tests", "data", "ohlcv_30.csv") + +KINDS = ind_mod.indicator_names() + +# Golden spot values from the C++ component reference (ind_* on the +# seeded demo series, seed 42): (kind, line, bar, value). +GOLDEN = ( + ("IndRSI", 0, 25, 46.880370427479114), + ("IndMACD", 0, 40, -0.7883630259220524), + ("IndMACD", 1, 40, -0.7673869019079353), + ("IndMACD", 2, 40, -0.02097612401411708), + ("IndBollingerBands", 0, 40, 100.71938861058676), + ("IndBollingerBands", 1, 40, 97.25597274343893), + ("IndBollingerBands", 2, 40, 93.7925568762911), + ("IndSMA", 0, 30, 98.70914778880885), + ("IndEMA", 0, 30, 98.15064907635568), + ("IndATR", 0, 30, 1.4632890946762565), +) + + +def _make(name, width=400, height=300): + widget = core.create(name, name + "_001", 0, 0, width, height) + assert widget is not None, name + return widget + + +def _draw(widget): + surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, + widget.width + 4, widget.height + 4) + cr = cairo.Context(surface) + cr.set_source_rgb(1, 1, 1) + cr.paint() + widget.draw(cr) + return surface + + +def _png_bytes(surface): + buf = io.BytesIO() + surface.write_to_png(buf) + return buf.getvalue() + + +def _finite(values): + return [v for v in values if v is not None and v == v] + + +class TestIndicatorSeriesApi(unittest.TestCase): + def test_kinds(self): + self.assertEqual(len(KINDS), 250) + self.assertEqual(len(set(KINDS)), 250) + + def test_demo_fallback(self): + w = _make("IndRSI") + self.assertEqual(w.item_count(), 250) + self.assertEqual(len(w.get_series()), 250) + lines = w.get_lines() + self.assertEqual(len(lines), 1) + self.assertEqual(len(lines[0]), 250) + self.assertTrue(_finite(lines[0])) + + def test_set_series_round_trip(self): + w = _make("IndRSI") + bars = stock_mod.load_csv(CSV_PATH) + w.set_series(bars) + self.assertEqual(w.item_count(), 30) + self.assertEqual(w.get_series(), bars) + # get_series returns a copy: mutating it must not move the plot + got = w.get_series() + got.append(got[-1]) + self.assertEqual(w.item_count(), 30) + + def test_set_series_none_restores_demo(self): + w = _make("IndRSI") + w.set_series(stock_mod.load_csv(CSV_PATH)) + self.assertEqual(w.item_count(), 30) + w.set_series(None) + self.assertEqual(w.item_count(), 250) + + def test_add_point(self): + w = _make("IndSMA") + w.set_series(stock_mod.load_csv(CSV_PATH)) + self.assertEqual(w.add_point((100.0, 101.0, 99.0, 100.5, 1000.0)), + 31) + self.assertEqual(w.item_count(), 31) + # No own series yet: starts fresh, does not extend the demo. + w2 = _make("IndSMA") + self.assertEqual(w2.add_point((100.0, 101.0, 99.0, 100.5, 1000.0)), + 1) + self.assertEqual(w2.item_count(), 1) + + def test_clear_populate(self): + w = _make("IndEMA") + w.set_series(stock_mod.load_csv(CSV_PATH)) + w.clear() + self.assertEqual(w.item_count(), 0) + self.assertEqual(w.get_lines(), []) + w.populate(stock_mod.load_csv(CSV_PATH)) + self.assertEqual(w.item_count(), 30) + self.assertTrue(_finite(w.get_lines()[0])) + + def test_load_csv(self): + w = _make("IndMACD") + self.assertEqual(w.load_csv(CSV_PATH), 30) + self.assertEqual(w.item_count(), 30) + self.assertEqual(len(w.get_lines()), 3) + + def test_load_csv_bad_data_leaves_series(self): + w = _make("IndRSI") + before = w.get_series() + with self.assertRaises(ValueError): + w.load_csv(io.StringIO("date,open,high,low,close,volume\n" + "2026-01-01,1,2,3,xx,5\n")) + self.assertEqual(w.get_series(), before) + + def test_set_series_rejects_bad_bars(self): + w = _make("IndRSI") + with self.assertRaises(ValueError): + w.set_series([(1.0, 2.0, 3.0)]) # not a 5-tuple bar + + def test_golden_values(self): + bars = stock_mod.demo_series() + for kind, line, bar, value in GOLDEN: + got = ind_mod.compute_lines(kind, bars)[line][bar] + self.assertAlmostEqual(got, value, places=9, + msg="%s line %d bar %d" % (kind, line, bar)) + + def test_params_override(self): + bars = stock_mod.demo_series() + default = ind_mod.compute_lines("IndRSI", bars)[0] + other = ind_mod.compute_lines("IndRSI", bars, [7])[0] + self.assertNotEqual(default, other) + + +class TestAllKindsRecompute(unittest.TestCase): + def test_all_kinds_load_and_recompute(self): + demo = stock_mod.demo_series() + csv_bars = stock_mod.load_csv(CSV_PATH) + no_finite_csv = [] + for kind in KINDS: + demo_lines = ind_mod.compute_lines(kind, demo) + self.assertTrue(demo_lines, kind) + for values in demo_lines: + self.assertEqual(len(values), 250, kind) + csv_lines = ind_mod.compute_lines(kind, csv_bars) + self.assertEqual(len(csv_lines), len(demo_lines), kind) + for values in csv_lines: + self.assertEqual(len(values), 30, kind) + # Loaded data must change the output (where the kind has + # any finite value on the short CSV at all). + if any(_finite(v) for v in csv_lines): + self.assertNotEqual( + [v for line in csv_lines for v in line], + [v for line in demo_lines[:len(csv_lines)] + for v in line[:30]], kind) + else: + no_finite_csv.append(kind) + # The kinds with no finite value on the 30-bar CSV are the + # long-warm-up family (multi-stage smoothing, 52-bar Senkou + # Span B, Klinger slow EMA 55, Guppy long leg 60, ...). Each + # of them must still produce finite values on the 250-bar + # demo series -- otherwise it would be a broken kind, not a + # warm-up. + self.assertLessEqual(len(no_finite_csv), 40, + sorted(no_finite_csv)) + for kind in no_finite_csv: + demo_lines = ind_mod.compute_lines(kind, demo) + self.assertTrue(any(v == v for line in demo_lines + for v in line), kind) + + def test_all_kinds_widget_api(self): + csv_bars = stock_mod.load_csv(CSV_PATH) + for kind in KINDS: + w = _make(kind) + self.assertEqual(w.item_count(), 250, kind) + w.load_csv(CSV_PATH) + self.assertEqual(w.item_count(), 30, kind) + lines = w.get_lines() + self.assertTrue(lines, kind) + for values in lines: + self.assertEqual(len(values), 30, kind) + w.clear() + self.assertEqual(w.item_count(), 0, kind) + self.assertEqual(w.get_lines(), [], kind) + w.set_series(csv_bars) + self.assertEqual(w.item_count(), 30, kind) + + +class TestIndicatorRendering(unittest.TestCase): + def test_all_kinds_draw_demo_and_csv(self): + for kind in KINDS: + w = _make(kind) + _draw(w) # demo series, must not raise + w.load_csv(CSV_PATH) + _draw(w) # loaded CSV data, must not raise + + def test_csv_render_differs_from_demo(self): + same = [] + for kind in KINDS: + w = _make(kind) + demo_png = _png_bytes(_draw(w)) + w.load_csv(CSV_PATH) + csv_png = _png_bytes(_draw(w)) + if demo_png == csv_png: + same.append(kind) + # A kind whose CSV lines are all NaN (long warm-up on 30 bars) + # draws the same empty plot as... no: the demo plot has lines, + # so every kind must differ. Report the stragglers if any. + self.assertEqual(same, [], same) + + def test_one_bar_draws(self): + w = _make("IndRSI") + w.set_series([(100.0, 101.0, 99.0, 100.5, 1000.0)]) + _draw(w) + + def test_cleared_draws_placeholder(self): + w = _make("IndRSI") + demo_png = _png_bytes(_draw(w)) + w.clear() + cleared_png = _png_bytes(_draw(w)) + self.assertNotEqual(demo_png, cleared_png) + w.populate(stock_mod.load_csv(CSV_PATH)) + self.assertNotEqual(cleared_png, _png_bytes(_draw(w))) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/ind_csv_shots.py b/tools/ind_csv_shots.py new file mode 100644 index 0000000..4727c1c --- /dev/null +++ b/tools/ind_csv_shots.py @@ -0,0 +1,205 @@ +#!/usr/bin/env python3 +"""Screenshot every Ind* indicator widget with CSV data loaded. + +Takes each committed example in examples/.py, injects a +``widget.load_csv(...)`` call into its _build_widgets(), runs it under +Xvfb, and screenshots the root window cropped to the example window +size -- the same render path as the pythondoc sweep (drive.py run_one) +and the visreg harness, so the shots are directly comparable to the +template-data goldens in tools/visreg/goldens/. + +Usage (on hot_newyork, from the repo root): + python3 tools/ind_csv_shots.py [--out-dir DIR] [--workers N] + [--csv PATH] [Kind ...] + +Writes .png per widget into the out dir (default +/opt/lightgui-docs/pythondoc/work/ind-csv-shots), plus report.json +with the ImageMagick RMSE of each CSV shot against its template golden +(large = the CSV data really is what is plotted). +""" +import argparse +import json +import os +import re +import signal +import subprocess +import sys +import time + +REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, REPO) + +from lightgui.xframe import indicators as ind_mod # noqa: E402 + +KINDS = ind_mod.indicator_names() +DEFAULT_OUT = "/opt/lightgui-docs/pythondoc/work/ind-csv-shots" +DEFAULT_CSV = os.path.join(REPO, "tests", "data", "ohlcv_30.csv") + + +def win_size(kind): + from lightgui.xframe.palette import PALETTE + entry = next(e for e in PALETTE if e.name == kind) + return (max(entry.default_w + 32, 220), + max(entry.default_h + 32, 120)) + + +def patched_example(kind, csv_path, tmpdir): + """Copy the committed example, inject load_csv, return path.""" + slug = kind.lower() + src = os.path.join(REPO, "examples", slug + ".py") + with open(src, encoding="utf-8") as f: + code = f.read() + lines = [" widget.load_csv(%r)" % csv_path] + anchor = " widget = create('%s', " % kind + out_lines = [] + injected = False + for line in code.split("\n"): + out_lines.append(line) + if not injected and line.startswith(anchor): + out_lines.extend(lines) + injected = True + if not injected: + raise RuntimeError("create() line not found in %s" % src) + path = os.path.join(tmpdir, slug + "_csv.py") + with open(path, "w", encoding="utf-8") as f: + f.write("\n".join(out_lines)) + return path + + +def wait_for_x(display, timeout=15): + sock = "/tmp/.X11-unix/X%d" % display + t0 = time.time() + while time.time() - t0 < timeout: + if os.path.exists(sock): + return True + time.sleep(0.2) + return False + + +def crop_to_window(path, kind): + from PIL import Image + w, h = win_size(kind) + im = Image.open(path) + im.crop((0, 0, min(w, im.width), min(h, im.height))).save(path) + + +def rmse_pct(golden, shot): + """Normalised RMSE % between two PNGs (ImageMagick compare).""" + proc = subprocess.run( + ["compare", "-metric", "RMSE", golden, shot, "null:"], + capture_output=True, text=True, timeout=60) + text = (proc.stderr or proc.stdout).strip() + m = re.search(r"\(([\d.]+)\)", text) + if not m: + return None + return round(float(m.group(1)) * 100, 2) + + +def run_one(kind, display, csv_path, outdir, tmpdir): + slug = kind.lower() + result = {"kind": kind, "name": kind, "slug": slug, "ok": False, + "reason": "", "shot": os.path.join(outdir, slug + ".png"), + "rmse_vs_template_pct": None} + try: + ex = patched_example(kind, csv_path, tmpdir) + except Exception as exc: # noqa: BLE001 + result["reason"] = "patch failed: %r" % (exc,) + return result + chk = subprocess.run([sys.executable, "-m", "py_compile", ex], + capture_output=True, text=True, timeout=60) + if chk.returncode != 0: + result["reason"] = "py_compile failed: " + chk.stderr.strip()[:300] + return result + env = dict(os.environ) + env["DISPLAY"] = ":%d" % display + env["PYTHONPATH"] = REPO + os.pathsep + env.get("PYTHONPATH", "") + logp = os.path.join(tmpdir, slug + ".log") + png = result["shot"] + with open(logp, "w", encoding="utf-8") as logf: + proc = subprocess.Popen( + [sys.executable, ex], env=env, + stdout=logf, stderr=subprocess.STDOUT, + start_new_session=True) + try: + time.sleep(2.5) + if proc.poll() is not None: + result["reason"] = "exited early rc=%s; log: %s" % ( + proc.returncode, + open(logp, encoding="utf-8", + errors="replace").read()[-400:]) + return result + shot = subprocess.run( + ["import", "-window", "root", png], env=env, + capture_output=True, text=True, timeout=30) + if shot.returncode != 0 or not os.path.exists(png): + result["reason"] = "screenshot failed: " + shot.stderr[:300] + return result + crop_to_window(png, kind) + finally: + try: + os.killpg(proc.pid, signal.SIGTERM) + except ProcessLookupError: + pass + golden = os.path.join(REPO, "tools", "visreg", "goldens", + slug + ".png") + if os.path.exists(golden): + result["rmse_vs_template_pct"] = rmse_pct(golden, png) + result["ok"] = True + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--out-dir", default=DEFAULT_OUT) + parser.add_argument("--workers", type=int, default=6) + parser.add_argument("--csv", default=DEFAULT_CSV) + parser.add_argument("kinds", nargs="*", default=KINDS) + args = parser.parse_args() + kinds = [k for k in args.kinds if k in KINDS] + if not kinds: + print("no in-scope kinds requested") + return 1 + os.makedirs(args.out_dir, exist_ok=True) + tmpdir = os.path.join(args.out_dir, ".tmp") + os.makedirs(tmpdir, exist_ok=True) + displays = [141 + i for i in range(args.workers)] + procs = [] + for d in displays: + procs.append(subprocess.Popen( + ["Xvfb", ":%d" % d, "-screen", "0", "1280x900x24"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)) + try: + for d in displays: + if not wait_for_x(d): + print("Xvfb :%d did not come up" % d) + return 1 + # Round-robin the kinds over the displays, sequentially per + # display (each run needs its own display; 2.5 s settle each). + results = [] + for i, kind in enumerate(kinds): + display = displays[i % len(displays)] + print("[%d/%d] %s on :%d" % (i + 1, len(kinds), kind, display), + flush=True) + results.append(run_one(kind, display, args.csv, + args.out_dir, tmpdir)) + finally: + for p in procs: + p.terminate() + ok = [r for r in results if r["ok"]] + print("shots: ok=%d fail=%d" % (len(ok), len(results) - len(ok))) + for r in results: + if r["ok"]: + print(" OK %-28s RMSE vs template: %s%%" % ( + r["kind"], + r["rmse_vs_template_pct"] if r["rmse_vs_template_pct"] + is not None else "?")) + else: + print(" FAIL %-28s %s" % (r["kind"], r["reason"])) + with open(os.path.join(args.out_dir, "report.json"), "w", + encoding="utf-8") as f: + json.dump(results, f, indent=1) + return 0 if len(ok) == len(results) else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/transpile_indicators.py b/tools/transpile_indicators.py new file mode 100644 index 0000000..af8132b --- /dev/null +++ b/tools/transpile_indicators.py @@ -0,0 +1,1890 @@ +#!/usr/bin/env python3 +"""Transpile the C++ Ind* indicator compute functions to Python. + +Reads the LightGUI C repo (widgets/components/Ind*/Ind*.h) and emits +``lightgui/xframe/indicators.py``: the 250 per-kind ``ind_*`` compute +functions plus the shared math helpers they use, with the C++ NaN +warm-up semantics preserved. + +Why transpile instead of hand-port: each of the 250 headers carries its +own copy of the shared helpers (sma_v/ema_v/...) and its own ``ind_*`` +formula -- 2,263 lines of formula code. The helpers are near-identical +across headers (37 names, 40 distinct bodies); the transpiler dedupes +them by body hash and resolves each kind's calls to the variant its own +header defines, so the Python values match the C++ widgets exactly. + +Regenerate: ``python3 tools/transpile_indicators.py`` (run from the repo +root; the C repo is read from /opt/lightgui by default, override with +--crepo). The output file carries a DO NOT EDIT header. + +Verification: ``tests/test_indicators.py`` cross-checks every kind +against the C++ reference dump (tools/ind_ref_dump, built from the same +headers) on the seeded demo series. +""" +import argparse +import hashlib +import json +import os +import re +import sys +from collections import OrderedDict + +# -------------------------------------------------------------------------- +# Tokenizer (C++ subset) +# -------------------------------------------------------------------------- + +TOKEN_RE = re.compile(r""" + (?P\s+) + | (?P//[^\n]*|/\*.*?\*/) + | (?P"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*') + | (?P(?:\d+\.\d*|\.\d+|\d+)(?:[eE][+-]?\d+)?[fFuUlL]*|0[xX][0-9a-fA-F]+[uUlL]*) + | (?P[A-Za-z_][A-Za-z0-9_]*) + | (?P<<=|>>=|==|!=|<=|>=|&&|\|\||\+\+|--|\+=|-=|\*=|/=|%=|->|::|<<|>>) + | (?P.) +""", re.X | re.S) + + +class Tok: + __slots__ = ('kind', 'text') + + def __init__(self, kind, text): + self.kind = kind + self.text = text + + def __repr__(self): + return 'Tok(%s, %r)' % (self.kind, self.text) + + +def tokenize(src): + toks = [] + for m in TOKEN_RE.finditer(src): + kind = m.lastgroup + if kind in ('ws', 'comment'): + continue + toks.append(Tok(kind, m.group())) + toks.append(Tok('eof', '')) + return toks + + +class TranspileError(Exception): + pass + + +# -------------------------------------------------------------------------- +# Types: 'int' | 'double' | 'bool' | 'vec' | 'vecvec' | 'series' | 'bar' +# | 'struct:Name' | 'str' | 'void' | 'unknown' +# -------------------------------------------------------------------------- + +INT_TYPES = {'int', 'size_t', 'std::size_t', 'long', 'unsigned', 'char'} +BAR_FIELDS = {'open': 0, 'high': 1, 'low': 2, 'close': 3, 'volume': 4, + 'time': 5} + + +def cpp_type_to_py(t): + """Map a C++ type spelling to our type tag.""" + t = t.replace('const', '').replace('&', '').replace('*', '').strip() + t = re.sub(r'\s*::\s*', '::', t) + t = re.sub(r'\s*<\s*', '<', t) + t = re.sub(r'\s*>\s*', '>', t) + t = re.sub(r'\s+', ' ', t).strip() + if t == 'auto': + return 'auto' + if t in INT_TYPES: + return 'int' + if t in ('double', 'float'): + return 'double' + if t == 'bool': + return 'bool' + if t == 'std::string': + return 'str' + if t == 'std::vector': + return 'vec' + if t == 'std::vector>': + return 'vecvec' + if t in ('OHLCVSeries', 'xframe::OHLCVSeries'): + return 'series' + if t == 'OHLCV': + return 'bar' + if t == 'void': + return 'void' + return 'struct:' + t + + +def is_int_type(t): + return t == 'int' + + +def is_float_type(t): + return t == 'double' + + +def result_type(op, lt, rt): + """Result type of a binary op on lt/rt.""" + if op in ('==', '!=', '<', '<=', '>', '>=', '&&', '||'): + return 'bool' + if lt == 'double' or rt == 'double': + return 'double' + if lt == 'int' and rt == 'int': + return 'int' + if lt == 'vec' or rt == 'vec': + return 'vec' + if lt == 'unknown' or rt == 'unknown': + return 'unknown' + return lt + +# -------------------------------------------------------------------------- +# Parser: C++ subset -> Python source (one function at a time) +# -------------------------------------------------------------------------- + +BIN_PREC = { + '||': 1, '&&': 2, + '==': 3, '!=': 3, + '<': 4, '<=': 4, '>': 4, '>=': 4, + '+': 5, '-': 5, + '*': 6, '/': 6, '%': 6, +} +ASSIGN_OPS = {'=', '+=', '-=', '*=', '/=', '%='} +PY_BIN = {'&&': 'and', '||': 'or'} +TYPE_WORDS = {'double', 'int', 'bool', 'size_t', 'float', 'long', + 'unsigned', 'char', 'void', 'auto'} +STD_FUNCS = { + 'fabs': ('abs', 'double'), 'abs': ('abs', None), + 'sqrt': ('math.sqrt', 'double'), 'exp': ('math.exp', 'double'), + 'log': ('math.log', 'double'), 'log10': ('math.log10', 'double'), + 'log2': ('math.log2', 'double'), + 'sin': ('math.sin', 'double'), 'cos': ('math.cos', 'double'), + 'tan': ('math.tan', 'double'), 'asin': ('math.asin', 'double'), + 'acos': ('math.acos', 'double'), 'atan': ('math.atan', 'double'), + 'atan2': ('math.atan2', 'double'), + 'floor': ('math.floor', 'double'), 'ceil': ('math.ceil', 'double'), + 'round': ('round', 'double'), + 'isfinite': ('math.isfinite', 'bool'), 'isnan': ('math.isnan', 'bool'), +} +SERIES_FUNCS = { + 'series_closes': '_closes', 'series_opens': '_opens', + 'series_highs': '_highs', 'series_lows': '_lows', + 'series_volumes': '_volumes', 'series_typical': '_typical', +} + + +class Parser: + """Parses one C++ function body; emits indented Python lines.""" + + def __init__(self, toks, ctx): + self.toks = toks + self.i = 0 + self.ctx = ctx # {env, resolve, ret_types, struct_fields} + self.lines = [] # (indent, text) + self.indent = 0 + + # -- token helpers ------------------------------------------------------ + def peek(self, off=0): + return self.toks[min(self.i + off, len(self.toks) - 1)] + + def next(self): + t = self.toks[self.i] + self.i += 1 + return t + + def at(self, text): + return self.peek().text == text + + def at_eof(self): + return self.peek().kind == 'eof' + + def expect(self, text): + t = self.next() + if t.text != text: + raise TranspileError('expected %r, got %r' % (text, t.text)) + return t + + def emit(self, text): + self.lines.append((self.indent, text)) + + # -- entry -------------------------------------------------------------- + def parse_body(self): + """Tokens positioned just after '{'; parse until matching '}'.""" + self.parse_stmts(end_brace=True) + return self.lines + + def parse_stmts(self, end_brace=False): + while not self.at_eof(): + if end_brace and self.at('}'): + self.next() + return + if self.at(';'): + self.next() + continue + self.parse_stmt() + + # -- statements --------------------------------------------------------- + def parse_stmt(self): + t = self.peek() + if t.text == '{': + self.next() + self.indent += 1 + self.parse_stmts(end_brace=True) + self.indent -= 1 + return + if t.text == 'if': + self.parse_if() + return + if t.text == 'for': + self.parse_for() + return + if t.text == 'while': + self.next() + self.expect('(') + cond, _ = self.parse_expr() + self.expect(')') + self.emit('while %s:' % cond) + self.indent += 1 + self.parse_stmt_or_block() + self.indent -= 1 + return + if t.text == 'return': + self.next() + if self.at(';'): + self.next() + outs = self.ctx.get('func_out_params') + if outs: + self.emit('return (%s)' % ', '.join(outs)) + else: + self.emit('return') + else: + code, _ = self.parse_expr() + self.expect(';') + self.emit('return %s' % code) + return + if t.text == 'break': + self.next() + self.expect(';') + self.emit('break') + return + if t.text == 'continue': + self.next() + self.expect(';') + self.emit('continue') + return + # lambda statement: auto name = [&](...) { ... }; + if self.is_lambda_stmt(): + self.parse_lambda_stmt() + return + # using namespace X; -- no-op (helper names resolve via kind map) + if t.text == 'using': + while not self.at(';') and not self.at_eof(): + self.next() + self.expect(';') + return + # (void)expr; -- no-op + if (t.text == '(' and self.peek(1).text == 'void' + and self.peek(2).text == ')'): + while not self.at(';') and not self.at_eof(): + self.next() + self.expect(';') + return + # declaration? + decl = self.try_parse_declaration() + if decl is not None: + for line in decl: + self.emit(line) + return + # ++x; / x++; / --x; / x--; + if (self.peek().kind == 'ident' + and self.peek(1).text in ('++', '--') + and self.peek(2).text == ';'): + name = self.next().text + op = self.next().text + self.next() + self.emit('%s += 1' % name if op == '++' else '%s -= 1' % name) + return + if (self.peek().text in ('++', '--') + and self.peek(1).kind == 'ident' + and self.peek(2).text == ';'): + op = self.next().text + name = self.next().text + self.next() + self.emit('%s += 1' % name if op == '++' else '%s -= 1' % name) + return + # expression statement + code, typ = self.parse_expr() + self.expect(';') + if typ.startswith('outtuple:'): + # void helper with out-params: assign the returned tuple + outs = typ[len('outtuple:'):].split(',') + self.emit('%s = %s' % (', '.join(outs), code)) + else: + self.emit(code) + + def parse_stmt_or_block(self): + if self.at('{'): + self.parse_stmt() + else: + self.parse_stmt() + + def parse_if(self): + self.expect('if') + self.expect('(') + cond, _ = self.parse_expr() + self.expect(')') + self.emit('if %s:' % cond) + self.indent += 1 + self.parse_stmt_or_block() + self.indent -= 1 + while self.at('else'): + self.next() + if self.at('if'): + self.expect('if') + self.expect('(') + cond, _ = self.parse_expr() + self.expect(')') + self.emit('elif %s:' % cond) + self.indent += 1 + self.parse_stmt_or_block() + self.indent -= 1 + else: + self.emit('else:') + self.indent += 1 + self.parse_stmt_or_block() + self.indent -= 1 + + def parse_for(self): + self.expect('for') + self.expect('(') + # init: declaration | expr | empty + init_var = None + init_val = None + if not self.at(';'): + saved = self.i + decl = self.try_parse_declaration(no_semi=True) + if decl is not None: + # decl lines look like "var = value" (single declarator) + if len(decl) != 1 or '=' not in decl[0]: + raise TranspileError( + 'unsupported for-init declaration: %r' % (decl,)) + init_var, init_val = decl[0].split(' = ', 1) + else: + self.i = saved + code, _ = self.parse_expr() + # expr init (rare): emit as a plain statement before loop + self._for_pre = [code] + self.expect(';') + cond_toks = self.collect_until(';') + self.expect(';') + incr_toks = self.collect_until(')') + self.expect(')') + # analyse the range form + rng = self.analyse_for_range(init_var, cond_toks, incr_toks) + if rng is None: + raise TranspileError( + 'non-range for loop: init=%r cond=%r incr=%r' % ( + init_var, cond_toks, incr_toks)) + start, stop, step = rng + pre = getattr(self, '_for_pre', None) + if pre: + for line in pre: + self.emit(line) + self._for_pre = None + if step == 1: + self.emit('for %s in range(%s, %s):' % (init_var, start, stop)) + else: + self.emit('for %s in range(%s, %s, %s):' % ( + init_var, start, stop, step)) + self.indent += 1 + self.parse_stmt_or_block() + self.indent -= 1 + + def collect_arg_tokens(self): + """Collect tokens of one call argument until a top-level ',' or + ')', returning (token_texts, terminator).""" + depth = 0 + out = [] + while not self.at_eof(): + t = self.peek() + if depth == 0 and t.text in (',', ')'): + return out, t.text + if t.text in ('(', '[', '{'): + depth += 1 + elif t.text in (')', ']', '}'): + depth -= 1 + out.append(self.next().text) + raise TranspileError('unterminated argument list') + + def _range_ctor(self, raw_args): + """Vector range ctor: vector(X.begin() + a, X.begin() + b) -> + X[a:b]. raw_args are token-text lists. Returns the slice expr + or None.""" + if len(raw_args) != 2: + return None + parts = [] + base = None + for toks in raw_args: + if len(toks) >= 6 and toks[1] == '.' and toks[2] == 'begin' \ + and toks[3] == '(' and toks[4] == ')' \ + and toks[5] == '+': + if base is None: + base = toks[0] + elif base != toks[0]: + return None + off = self._tokens_to_expr(toks[6:]) + if off is None: + return None + parts.append(off) + else: + return None + return '%s[%s:%s]' % (base, parts[0], parts[1]) + + def collect_until(self, closer): + """Collect token texts until the matching closer at depth 0.""" + depth = 0 + out = [] + while not self.at_eof(): + t = self.peek() + if depth == 0 and t.text == closer: + return out + if t.text in ('(', '[', '{'): + depth += 1 + elif t.text in (')', ']', '}'): + depth -= 1 + out.append(self.next().text) + raise TranspileError('unterminated; expected %r' % closer) + + def analyse_for_range(self, var, cond, incr): + """Return (start, stop, step) Python exprs, or None. + + cond must be a comparison (or &&-conjunction of comparisons) + bounding the loop var: `var [+/- C] bound` (or the mirrored + form with var on the right). incr must be ++var / var++ / --var / + var-- / var += K / var -= K. + """ + if var is None: + return None + # incr -> step + step = None + if incr == ['++', var] or incr == [var, '++']: + step = 1 + elif incr == ['--', var] or incr == [var, '--']: + step = -1 + elif len(incr) == 3 and incr[0] == var and incr[1] == '+=': + step = ('+', incr[2]) + elif len(incr) == 3 and incr[0] == var and incr[1] == '-=': + step = ('-', incr[2]) + if step is None: + return None + # split cond on top-level && + parts, depth, cur = [], 0, [] + for tok in cond: + if tok in ('(', '[', '{'): + depth += 1 + elif tok in (')', ']', '}'): + depth -= 1 + if tok == '&&' and depth == 0: + parts.append(cur) + cur = [] + else: + cur.append(tok) + parts.append(cur) + stops = [] + for part in parts: + stop = self._range_bound(var, part, step) + if stop is None: + return None + stops.append(stop) + if len(stops) == 1: + stop = stops[0] + elif step == 1 or (isinstance(step, tuple) and step[0] == '+'): + stop = 'min(%s)' % ', '.join(stops) + else: + stop = 'max(%s)' % ', '.join(stops) + if isinstance(step, tuple): + sgn, kval = step + step = '%s%s' % (sgn, kval) + start = self._for_start + return (start, stop, step) + + def _range_bound(self, var, cond, step): + """Stop expr for one comparison conjunct, or None.""" + ops = ['<', '<=', '>', '>='] + oi = None + for k, tok in enumerate(cond): + if tok in ops: + oi = k + break + if oi is None: + return None + lhs, op, rhs = cond[:oi], cond[oi], cond[oi + 1:] + # find which side holds the loop var (with optional +/- const) + def strip_casts(side): + # remove leading (type) casts, e.g. (std::size_t)k + while len(side) >= 4 and side[0] == '(': + depth = 0 + j = 0 + for j, tok in enumerate(side): + if tok == '(': + depth += 1 + elif tok == ')': + depth -= 1 + if depth == 0: + break + inner = side[1:j] + if len(inner) == 1 and inner[0] in TYPE_WORDS: + side = side[j + 1:] + elif len(inner) == 3 and inner[0] == 'std' \ + and inner[1] == '::': + side = side[j + 1:] + else: + break + return side + + def var_side(side): + if side == [var]: + return 0 + if len(side) == 3 and side[0] == var and side[1] in ('+', '-'): + try: + c = int(side[2]) + except ValueError: + return None + return c if side[1] == '+' else -c + return None + loff = var_side(strip_casts(lhs)) + roff = var_side(strip_casts(rhs)) + if loff is not None and roff is None: + bound = self._tokens_to_expr(rhs) + off = loff + flip = False + elif roff is not None and loff is None: + bound = self._tokens_to_expr(lhs) + off = roff + flip = True + else: + return None + if bound is None: + return None + # effective comparison: var bound (flip swaps the op) + if flip: + op = {'<': '>', '<=': '>=', '>': '<', '>=': '<='}[op] + up = step == 1 or (isinstance(step, tuple) and step[0] == '+') + if up: + if op == '<': + return self._shift_bound(bound, -off) + if op == '<=': + return self._shift_bound(bound, -off + 1) + return None + else: + if op == '>': + return self._shift_bound(bound, -off) + if op == '>=': + return self._shift_bound(bound, -off - 1) + return None + + def _shift_bound(self, bound, delta): + if delta == 0: + return bound + if delta > 0: + return '(%s + %d)' % (bound, delta) + return '(%s - %d)' % (bound, -delta) + + def _tokens_to_expr(self, toks): + """Translate a small token list (no statements) to Python expr.""" + code, _t = self._tokens_to_expr_typed(toks) + return code + + def _tokens_to_expr_typed(self, toks): + """Translate a small token list to (Python expr, type tag).""" + sub = Parser(tokenize(' '.join(toks)), self.ctx) + try: + code, typ = sub.parse_expr() + except TranspileError: + return None, None + if not sub.at_eof(): + return None, None + return code, typ + + # -- lambdas ------------------------------------------------------------ + def is_lambda_stmt(self): + # auto name = [&](...) ... ; + if self.peek().text != 'auto': + return False + i = self.i + 1 + if self.toks[i].kind != 'ident': + return False + i += 1 + if self.toks[i].text != '=': + return False + return self.toks[i + 1].text == '[' + + def parse_lambda_stmt(self): + self.expect('auto') + name = self.next().text + if name in PY_BUILTINS: + self.ctx.setdefault('rename', {})[name] = name + '_' + name = name + '_' + self.expect('=') + self.expect('[') + # capture list: & or = or empty, up to ] + while not self.at(']'): + self.next() + self.expect(']') + self.expect('(') + params, ptypes = self.parse_param_list() + self.expect(')') + if self.at('->'): + self.next() + self.skip_type() + self.expect('{') + # nested def: parse body with a fresh env seeded from params + outer_env = dict(self.ctx['env']) + py_params = [] + for pname, ptype in zip(params, ptypes): + if pname in PY_BUILTINS: + self.ctx.setdefault('rename', {})[pname] = pname + '_' + pname = pname + '_' + py_params.append(pname) + self.ctx['env'][pname] = ptype + saved_indent = self.indent + self.indent += 1 + body_lines = [] + start = len(self.lines) + self.parse_stmts(end_brace=True) + body_lines = self.lines[start:] + del self.lines[start:] + # nonlocal for names the lambda assigns that live outside it + assigned = set() + for _ind, text in body_lines: + m = re.match(r'([A-Za-z_]\w*)\s*(?:\+=|-=|\*=|/=|%=|=)', text) + if m: + assigned.add(m.group(1)) + nonlocals = sorted(n for n in assigned + if n in outer_env and n not in py_params) + self.ctx['env'] = outer_env + self.indent = saved_indent + self.emit('def %s(%s):' % (name, ', '.join(py_params))) + self.indent += 1 + for n in nonlocals: + self.emit('nonlocal %s' % n) + if not body_lines: + self.emit('pass') + else: + for ind, text in body_lines: + self.lines.append((ind, text)) + self.indent -= 1 + self.expect(';') + self.ctx['env'][name] = 'func' + + # -- declarations ------------------------------------------------------- + def parse_param_list(self): + """Parse C++ params inside parens; return (names, types).""" + names, types = [], [] + if self.at(')'): + return names, types + while True: + ptype, pname = self.parse_param() + names.append(pname) + types.append(ptype) + if self.at(','): + self.next() + continue + break + return names, types + + def parse_param(self): + """One C++ parameter: type + name (name may be absent).""" + if self.at('const'): + self.next() + t = self.parse_type_name() + if self.at('&') or self.at('*'): + self.next() + name = '' + if self.peek().kind == 'ident': + name = self.next().text + # default value + if self.at('='): + self.next() + self.parse_expr() + return t, name + + def parse_type_name(self): + """Parse a type spelling; return our type tag.""" + parts = [] + t = self.next() + parts.append(t.text) + if t.text == 'std': + self.expect('::') + parts.append('::') + t2 = self.next() + parts.append(t2.text) + if self.at('<'): + self.next() + inner = [] + depth = 1 + while depth: + tk = self.next() + if tk.text == '<': + depth += 1 + elif tk.text == '>': + depth -= 1 + if depth == 0: + break + elif tk.text == '>>': + depth -= 2 + if depth <= 0: + break + else: + inner.append(tk.text) + parts.append('<%s>' % ' '.join(inner)) + elif t.text in ('unsigned', 'long'): + if self.peek().kind == 'ident' and self.peek().text in ( + 'int', 'long'): + parts.append(self.next().text) + return cpp_type_to_py(' '.join(parts).replace(' <', '<') + .replace('> ', '>')) + + def skip_type(self): + self.parse_type_name() + + def try_parse_declaration(self, no_semi=False): + """Try to parse a declaration statement. + + Returns a list of Python lines (e.g. ['x = 1', 'y = 2']) or None + when the statement does not start with a type. When no_semi the + trailing ';' is not consumed (for-loop init). + """ + save = self.i + save_env = dict(self.ctx['env']) + try: + if self.at('const'): + self.next() + # type? + if not self.is_type_start(): + self.i = save + return None + vtype = self.parse_type_name() + if self.at('&') or self.at('*'): + self.next() + if self.peek().kind != 'ident': + self.i = save + self.ctx['env'] = save_env + return None + lines = [] + while True: + name = self.next().text + # locals shadowing Python builtins are renamed so the + # generated code keeps the builtin usable (range -> range_) + if name in PY_BUILTINS: + self.ctx.setdefault('rename', {})[name] = name + '_' + name = name + '_' + init = None + init_kind = None + # C array declarator: Type name[N] = { ... }; + is_array = False + if self.at('['): + is_array = True + self.next() + while not self.at(']') and not self.at_eof(): + self.next() + self.expect(']') + if self.at('='): + self.next() + if self.at('{'): + init = self.parse_brace_init() + init_kind = 'expr' + else: + code, typ = self.parse_expr() + init = code + init_kind = typ + elif self.at('('): + # constructor init: Type name(args) + self.next() + raw_args = [] + if not self.at(')'): + while True: + toks, term = self.collect_arg_tokens() + raw_args.append(toks) + if term == ',': + self.next() + continue + break + self.expect(')') + rng = self._range_ctor(raw_args) + if rng is not None: + init = rng + init_kind = 'range' + else: + typed = [self._tokens_to_expr_typed(a) + for a in raw_args] + if len(typed) == 1 and typed[0][1] in ( + 'vec', 'vecvec'): + # copy ctor: vector x(other) + init = typed[0][0] + init_kind = 'copy' + else: + init = [c for c, _t in typed] + init_kind = 'ctor' + if is_array: + if init is None: + lines.append('%s = []' % name) + else: + lines.append('%s = %s' % (name, init)) + self.ctx['env'][name] = 'vec' + elif vtype.startswith('struct:'): + if init is None: + # initialise every field (vectors to [], scalars + # to their zero) so .push_back / indexing works + sname = vtype[len('struct:'):] + fields = self.ctx.get('struct_map', {}).get( + sname, {}) + dflt = {'vec': '[]', 'vecvec': '[]', + 'double': '0.0', 'int': '0', + 'bool': 'False', 'str': "''"} + if fields: + inits = ', '.join( + '%s=%s' % (f, dflt.get(t, 'None')) + for f, t in fields.items()) + lines.append('%s = SimpleNamespace(%s)' + % (name, inits)) + else: + lines.append('%s = SimpleNamespace()' % name) + else: + raise TranspileError( + 'struct init not supported: %s' % name) + self.ctx['env'][name] = vtype + elif vtype == 'vec' or vtype == 'vecvec': + if init_kind == 'ctor': + if len(init) == 0: + lines.append('%s = []' % name) + elif len(init) == 1: + lines.append('%s = [0.0] * (%s)' % (name, init[0])) + elif len(init) == 2: + lines.append('%s = [%s] * (%s)' + % (name, init[1], init[0])) + else: + raise TranspileError('bad vector ctor init') + elif init_kind == 'copy': + # C++ copy ctor copies; Python would alias + lines.append('%s = list(%s)' % (name, init)) + elif init is None: + lines.append('%s = []' % name) + elif init_kind in ('vec', 'vecvec'): + # C++ copy-init copies; Python would alias + lines.append('%s = list(%s)' % (name, init)) + else: + lines.append('%s = %s' % (name, init)) + self.ctx['env'][name] = vtype + else: + if init is None: + dflt = {'int': '0', 'double': '0.0', + 'bool': 'False', 'str': "''"}.get(vtype, 'None') + lines.append('%s = %s' % (name, dflt)) + else: + lines.append('%s = %s' % (name, init)) + # the declared type wins (except auto, where the + # initialiser's type is the type) + self.ctx['env'][name] = init_kind \ + if vtype == 'auto' else vtype + if self.at(','): + self.next() + if self.peek().kind != 'ident': + raise TranspileError('bad declarator list') + continue + break + if no_semi: + self._for_start = lines[0].split(' = ', 1)[1] \ + if len(lines) == 1 and ' = ' in lines[0] else None + return lines + self.expect(';') + return lines + except TranspileError: + self.i = save + self.ctx['env'] = save_env + return None + + def parse_brace_init(self): + self.expect('{') + elems = [] + if not self.at('}'): + while True: + code, _ = self.parse_expr() + elems.append(code) + if self.at(','): + self.next() + continue + break + self.expect('}') + return '[%s]' % ', '.join(elems) + + def is_type_start(self): + t = self.peek() + if t.kind != 'ident': + return False + if t.text in TYPE_WORDS: + return True + if t.text == 'std': + return (self.peek(1).text == '::' + and self.peek(2).text in ('vector', 'string', 'size_t')) + if t.text.startswith('struct:'): + return True + if t.text in ('OHLCV', 'OHLCVSeries'): + return True + return t.text in self.ctx.get('struct_names', set()) + + # -- expressions (Pratt) -------------------------------------------------- + def parse_expr(self, min_prec=0): + """Parse an expression; return (python_code, type_tag).""" + left, ltype = self.parse_unary() + while True: + t = self.peek() + if t.text == '?': + if 0 < min_prec: + break + self.next() + a, _ = self.parse_expr() + self.expect(':') + b, btype = self.parse_expr() + left = '(%s if %s else %s)' % (a, left, b) + ltype = result_type('?:', ltype, btype) + continue + if t.text in ASSIGN_OPS: + if 0 < min_prec: + break + self.next() + rhs, rtype = self.parse_expr() + left, ltype = self.apply_assign(left, ltype, t.text, rhs, + rtype) + continue + if t.text in BIN_PREC and BIN_PREC[t.text] >= min_prec: + prec = BIN_PREC[t.text] + self.next() + r, rtype = self.parse_expr(prec + 1) + left, ltype = self.apply_binop(left, ltype, t.text, r, + rtype) + continue + break + return left, ltype + + def apply_assign(self, left, ltype, op, rhs, rtype): + if op == '=': + # chained assignment a = b = c: rhs may itself be an assignment + if ltype in ('vec', 'vecvec') and rtype in ('vec', 'vecvec') \ + and ' = ' not in rhs: + # C++ vector assignment copies; Python would alias + return '%s = list(%s)' % (left, rhs), ltype + return '%s = %s' % (left, rhs), ltype + pyop = {'+=': '+=', '-=': '-=', '*=': '*=', '/=': '/=', + '%=': '%='}[op] + if op == '/=' and is_int_type(ltype): + pyop = '//=' + if op == '%=' and is_int_type(ltype): + pyop = '%=' + return '%s %s %s' % (left, pyop, rhs), ltype + + def apply_binop(self, left, ltype, op, right, rtype): + pyop = PY_BIN.get(op, op) + if op in ('/', '%') and is_int_type(ltype) and is_int_type(rtype): + pyop = '//' if op == '/' else '%' + return '(%s %s %s)' % (left, pyop, right), \ + result_type(op, ltype, rtype) + + def parse_unary(self): + t = self.peek() + if t.text == '-': + self.next() + code, typ = self.parse_unary() + return '(-%s)' % code, typ + if t.text == '!': + self.next() + code, typ = self.parse_unary() + return '(not %s)' % code, 'bool' + if t.text in ('++', '--'): + # ++/-- in value position: not used in this corpus (they only + # appear as statements and for-loop increments, handled + # elsewhere); fail loudly rather than mistranslate. + raise TranspileError('prefix %s in value position' % t.text) + if t.text == '(': + # cast or parenthesised expression + save = self.i + self.next() + cast = self.try_parse_cast() + if cast is not None: + code, typ = self.parse_unary() + return self.apply_cast(cast, code, typ) + self.i = save + self.next() + code, typ = self.parse_expr() + self.expect(')') + return self.parse_postfix(code, typ) + if t.text == 'static_cast': + self.next() + self.expect('<') + ctype = self.parse_type_name() + self.expect('>') + self.expect('(') + code, typ = self.parse_expr() + self.expect(')') + return self.apply_cast(ctype, code, typ) + return self.parse_postfix(*self.parse_primary()) + + def try_parse_cast(self): + """After '('; if the contents are a type name + ')', return the tag.""" + save = self.i + try: + if self.at('const'): + self.next() + if not self.is_type_start(): + self.i = save + return None + tag = self.parse_type_name() + if self.at('&') or self.at('*'): + self.next() + if not self.at(')'): + self.i = save + return None + self.next() + return tag + except TranspileError: + self.i = save + return None + + def apply_cast(self, tag, code, typ): + if tag == 'double': + return 'float(%s)' % code, 'double' + if tag == 'int': + return 'int(%s)' % code, 'int' + if tag == 'bool': + return 'bool(%s)' % code, 'bool' + return code, typ + + def parse_primary(self): + t = self.next() + if t.kind == 'number': + txt = t.text.rstrip('fFuUlL') + if txt.lower().startswith('0x'): + return txt, 'int' + if any(c in txt for c in '.eE'): + return txt, 'double' + return txt, 'int' + if t.kind == 'string': + return t.text, 'str' + if t.kind == 'ident': + if t.text == 'true': + return 'True', 'bool' + if t.text == 'false': + return 'False', 'bool' + if t.text == 'nullptr': + return 'None', 'unknown' + # qualified name a::b[::c...] (may include <...> for templates) + name = t.text + qualified = False + while self.at('::'): + qualified = True + self.next() + nxt = self.next() + if nxt.text == 'numeric_limits': + # std::numeric_limits::quiet_NaN() + if self.at('<'): + self.next() + self.parse_type_name() + self.expect('>') + self.expect('::') + what = self.next().text + if what in ('quiet_NaN', 'infinity'): + # consume the trailing () of quiet_NaN() / + # infinity() + if self.at('('): + self.next() + self.expect(')') + return ('float("nan")' if what == 'quiet_NaN' + else 'float("inf")'), 'double' + raise TranspileError( + 'unknown numeric_limits member %s' % what) + name = nxt.text + if self.at('<'): + # template args (e.g. vector as a value? no) + self.next() + depth = 1 + while depth: + tk = self.next() + if tk.text == '<': + depth += 1 + elif tk.text == '>': + depth -= 1 + elif tk.text == '>>': + depth -= 2 + name += '<>' + # unqualified locals that shadow Python builtins were + # renamed at declaration (range -> range_); qualified + # names (std::max, detail::ema_v) are never renamed + if not qualified: + pyname = self.ctx.get('rename', {}).get(name, name) + return pyname, self.ctx['env'].get( + pyname, self.ctx['env'].get(name, 'unknown')) + return name, self.ctx['env'].get(name, 'unknown') + if t.text == '{': + elems = [] + if not self.at('}'): + while True: + code, _ = self.parse_expr() + elems.append(code) + if self.at(','): + self.next() + continue + break + self.expect('}') + return '[%s]' % ', '.join(elems), 'vec' + raise TranspileError('unexpected token %r' % (t.text,)) + + def parse_postfix(self, code, typ): + while True: + if self.at('['): + self.next() + idx, _ = self.parse_expr() + self.expect(']') + code = '%s[%s]' % (code, idx) + typ = 'double' if typ == 'vec' else ( + 'bar' if typ == 'series' else 'unknown') + continue + if self.at('.'): + self.next() + field = self.next().text + if self.at('('): + # method call + code, typ = self.parse_method_call(code, typ, field) + continue + if field in BAR_FIELDS: + code = '%s[%d]' % (code, BAR_FIELDS[field]) + typ = 'double' + else: + code = '%s.%s' % (code, field) + typ = self.ctx['struct_fields'].get(field, 'vec') + continue + if self.at('('): + code, typ = self.parse_call(code, typ) + continue + if self.at('++') or self.at('--'): + # postfix ++/-- in value position: not used in this corpus. + raise TranspileError('postfix ++/-- in value position') + break + return code, typ + + def parse_method_call(self, code, typ, field): + self.expect('(') + args = [] + if not self.at(')'): + while True: + a, at = self.parse_expr() + args.append((a, at)) + if self.at(','): + self.next() + continue + break + self.expect(')') + if field == 'size': + return 'len(%s)' % code, 'int' + if field == 'empty': + return '(not %s)' % code, 'bool' + if field == 'back': + return '%s[-1]' % code, 'double' + if field == 'front': + return '%s[0]' % code, 'double' + if field == 'at': + return '%s[%s]' % (code, args[0][0]), 'double' + if field in ('begin', 'end'): + # iterator marker; only meaningful inside std::sort(...) + return '%s.%s()' % (code, field), 'unknown' + if field == 'push_back': + return '%s.append(%s)' % (code, args[0][0]), 'void' + if field == 'clear': + return '%s.clear()' % code, 'void' + if field == 'assign': + # v.assign(n, val) -> v = [val] * n (statement-level use) + return '%s = [%s] * (%s)' % (code, args[1][0], args[0][0]), 'void' + raise TranspileError('unknown method .%s' % field) + + def parse_call(self, code, typ): + self.expect('(') + args = [] + if not self.at(')'): + while True: + a, at = self.parse_expr() + args.append((a, at)) + if self.at(','): + self.next() + continue + break + self.expect(')') + # std::sort(a.begin(), a.end()) -> a.sort() + if code in ('std::sort', 'sort') and len(args) == 2: + a0 = args[0][0] + if a0.endswith('.begin()'): + return '%s.sort()' % a0[:-len('.begin()')], 'void' + # mapped std functions + base = code.split('::')[-1] + if base in STD_FUNCS: + py, rt = STD_FUNCS[base] + if base == 'max': + return '_fmax(%s)' % ', '.join(a for a, _ in args), 'double' + if base == 'min': + return '_fmin(%s)' % ', '.join(a for a, _ in args), 'double' + return '%s(%s)' % (py, ', '.join(a for a, _ in args)), rt + if base in ('nan_v', 'nanv'): + return 'float("nan")', 'double' + if base in ('fin', 'fin_v'): + return 'math.isfinite(%s)' % args[0][0], 'bool' + if base in SERIES_FUNCS: + return '%s(%s)' % (SERIES_FUNCS[base], + ', '.join(a for a, _ in args)), 'vec' + # helper / ind function: resolve variant + pyname = self.ctx['resolve'](base) + # void helper with out-params: returns a tuple of the out values; + # the call site is rewritten to assign it (see parse_stmt) + outs = self.ctx.get('out_params', {}).get(pyname) + if outs is not None: + out_idx = {i for i, _n in outs} + in_args = [a for idx, (a, _t) in enumerate(args) + if idx not in out_idx] + out_codes = [args[i][0] for i, _n in outs] + return ('%s(%s)' % (pyname, ', '.join(in_args)), + 'outtuple:' + ','.join(out_codes)) + rt = self.ctx['ret_types'].get(pyname, + self.ctx['ret_types'].get(base, + 'unknown')) + return '%s(%s)' % (pyname, ', '.join(a for a, _ in args)), rt + +# -------------------------------------------------------------------------- +# Driver: extract from the C repo, transpile, emit indicators.py +# -------------------------------------------------------------------------- + +IND_CALL_RE = re.compile( + r'(?:^|\n)\s*(?:inline\s+)?([A-Za-z_][\w:<>,\s]*?)\b(ind_[a-z0-9_]+)' + r'\s*\(([^)]*)\)\s*\{') +HELPER_RE = re.compile( + r'inline\s+(std::vector|double|void|int|bool|' + r'std::vector>)\s+([a-z_][a-z0-9_]*)' + r'\s*\(([^)]*)\)\s*\{') +STRUCT_RE = re.compile(r'struct\s+(\w+)\s*\{([^}]*)\};') +FIELD_RE = re.compile( + r'(std::vector|std::vector>|double|int|bool)' + r'\s+(\w+)\s*;') + + +def extract_braced(src, i): + depth = 0 + j = i + while j < len(src): + if src[j] == '{': + depth += 1 + elif src[j] == '}': + depth -= 1 + if depth == 0: + return src[i:j + 1], j + 1 + j += 1 + return src[i:], len(src) + + +def norm_body(body): + n = re.sub(r'\bdetail_[a-z0-9_]+::', '', body) + return re.sub(r'\s+', ' ', n).strip() + + +def parse_header(path): + """Extract ind funcs, helpers, structs from one C header.""" + src = open(path, errors='replace').read() + funcs = [] + for m in IND_CALL_RE.finditer(src): + ret, name, args = (m.group(1).strip(), m.group(2), + m.group(3).strip()) + if not re.search(r'(vector|double|int|Result|bool|void|Series)', + ret): + continue + brace = src.index('{', m.end() - 1) + body, _ = extract_braced(src, brace) + funcs.append({'name': name, 'ret': ret, 'args': args, + 'body': body}) + helpers = {} + for m in HELPER_RE.finditer(src): + ret, name, args = (m.group(1), m.group(2), + m.group(3).strip()) + brace = src.index('{', m.end() - 1) + body, _ = extract_braced(src, brace) + helpers[name] = {'ret': ret, 'args': args, 'body': body, + 'hash': hashlib.md5( + norm_body(body).encode()).hexdigest()[:8]} + structs = {} + for m in STRUCT_RE.finditer(src): + fields = {} + for fm in FIELD_RE.finditer(m.group(2)): + fields[fm.group(2)] = cpp_type_to_py(fm.group(1)) + structs[m.group(1)] = fields + members = dict(re.findall( + r'\b(?:int|double|bool|float)\s+([A-Za-z_][A-Za-z0-9_]*_)\s*=\s*([^;]+);', + src)) + pushes = re.findall(r'lines_\.push_back\((.+?)\);', src, re.S) + return {'funcs': funcs, 'helpers': helpers, 'structs': structs, + 'members': members, + 'pushes': [p.strip().replace('\n', ' ') for p in pushes], + 'src': src} + + +def split_top(s): + out, depth, cur = [], 0, '' + for ch in s: + if ch == '(': + depth += 1 + elif ch == ')': + depth -= 1 + if ch == ',' and depth == 0: + out.append(cur) + cur = '' + else: + cur += ch + if cur.strip(): + out.append(cur) + return [a.strip() for a in out] + + +def extract_calls(crepo): + """Per-kind (call expr, vectors) from the C test sources. + + Mirrors the C smoke drivers: trend cases file, momentum smoke cpp, + volatility spec json. Vectors are the plotted lines. + """ + calls = {} + headers = {} + + def norm_call(expr): + expr = expr.replace('xframe::', '') + expr = re.sub(r'\bseries\b', 's', expr) + return re.sub(r'\s+', ' ', expr).strip() + + def vectors_from_pushes(kind, call): + h = headers.get(kind, {}) + vecs = [] + for p in h.get('pushes', []): + for fld in re.findall(r'(?:result|rc|gr|vr|hb|ha)\.([a-z0-9_]+)', + p): + vecs.append('(%s).%s' % (call, fld)) + if not vecs: + vecs = [call] + vecs = list(dict.fromkeys(vecs)) + if any('lines[' in p for p in h.get('pushes', [])): + src_h = h.get('src', '') + mm = re.search(r'for\s*\(.*?k\s*<\s*(\d+)', src_h) + n = int(mm.group(1)) if mm else 0 + vecs = ['(%s).lines[%d]' % (call, k) for k in range(n)] + return vecs + + comp = os.path.join(crepo, 'widgets', 'components') + for kind in sorted(os.listdir(comp)): + if not kind.startswith('Ind'): + continue + path = os.path.join(comp, kind, kind + '.h') + if os.path.exists(path): + headers[kind] = parse_header(path) + # trend + for line in open(os.path.join(crepo, 'widgets', 'tests', + 'trend_smoke_cases.txt')): + line = line.rstrip('\n') + if not line: + continue + name, expr, _s = line.split('|') + kind = 'Ind' + name + expr = norm_call(expr) + if ').' in expr: + base = expr.split(').', 1)[0] + ')' + calls[kind] = {'expr': base, + 'vectors': vectors_from_pushes(kind, base)} + else: + calls[kind] = {'expr': expr, 'vectors': [expr]} + # momentum + src = open(os.path.join(crepo, 'widgets', 'tests', + 'smoke_momentum_indicators.cpp')).read() + for b in re.findall(r'\{\s*(.*?)\s*\}', src, re.S): + m = re.search(r'auto\s+(v|r)\s*=\s*(?:xframe::)?' + r'(ind_[a-z0-9_]+\([^;]*\));', b, re.S) + if not m: + continue + var, call = m.group(1), norm_call(m.group(2)) + checks = re.findall(r'check_vec\("([^"]+)",\s*([^,]+),\s*250\)', b) + if not checks: + continue + vecs = [] + for _name, vexpr in checks: + vexpr = vexpr.strip() + if var == 'v': + vecs.append(call) + else: + vecs.append(re.sub(r'\br\.', '(' + call + ').', vexpr)) + calls['Ind' + checks[0][0].split('.')[0]] = {'expr': call, + 'vectors': vecs} + # volatility + spec = json.load(open(os.path.join( + crepo, 'widgets', 'tools', + 'stock_indicators_volatility_spec.json'))) + for item in spec: + kind = item['cls'] + func = item['func'] + defaults = [d.strip() for d in + re.findall(r'=\s*([^,]+)', item['params'])] + h = headers.get(kind, {}) + sig = '' + for f in h.get('funcs', []): + if f['name'] == func: + sig = f['args'] + if 'OHLCVSeries' in sig: + first = 's' + elif 'vector' in sig: + first = 'series_closes(s)' + else: + mm = re.search(re.escape(func) + r'\s*\(([^)]*)\)', + h.get('src', '')) + s2 = mm.group(1) if mm else '' + first = 's' if 'OHLCVSeries' in s2 else 'series_closes(s)' + call = '%s(%s)' % (func, ', '.join([first] + defaults)) + calls[kind] = {'expr': call, + 'vectors': vectors_from_pushes(kind, call)} + return calls, headers + + +def parse_call_expr(expr): + """Split a call expr into (func, [param values after the series arg]).""" + m = re.match(r'([a-z0-9_]+)\((.*)\)$', expr) + if not m: + raise TranspileError('cannot parse call expr %r' % expr) + args = split_top(m.group(2)) + params = [] + for a in args[1:]: + a = a.strip() + try: + if re.match(r'^[+-]?\d+$', a): + params.append(int(a)) + else: + params.append(float(a)) + except ValueError: + raise TranspileError('non-numeric param %r in %r' % (a, expr)) + return m.group(1), params + + +def selector_of(vector_expr, func_name): + """How to get one plotted line from the ind function's return value. + + Returns None (whole vector), ('field', name) or ('index', i). + """ + if vector_expr == '%s(' % func_name or re.match( + r'^%s\(.*\)$' % re.escape(func_name), vector_expr): + return None + m = re.match(r'^\(' + re.escape(func_name) + r'\(.*\)\)\.([a-z0-9_]+)$', + vector_expr) + if m: + return ('field', m.group(1)) + m = re.match(r'^\(' + re.escape(func_name) + r'\(.*\)\)\.lines\[(\d+)\]$', + vector_expr) + if m: + return ('index', int(m.group(1))) + raise TranspileError('cannot parse vector expr %r' % vector_expr) + +# -------------------------------------------------------------------------- +# Transpile one function + emit indicators.py +# -------------------------------------------------------------------------- + +PY_BUILTINS = { + 'range', 'min', 'max', 'sum', 'len', 'abs', 'round', 'list', 'dict', + 'int', 'float', 'str', 'bool', 'sorted', 'reversed', 'enumerate', + 'zip', 'open', 'id', 'type', 'format', 'all', 'any', 'map', 'filter', + 'next', 'print', 'input', 'set', 'tuple', 'object', 'slice', 'bytes', +} + + +def out_param_names(args): + """[(index, name)] of non-const scalar reference params in a C++ + argument list — the out-parameters of a void helper (dm_tr, + linreg_parts). const references (inputs) and container/series + references are not out-parameters.""" + out = [] + if args.strip(): + for idx, part in enumerate(split_top(args)): + part = part.strip() + if '&' not in part: + continue + if re.match(r'^\s*const\b', part): + continue + if re.search(r'\b(vector|Series|OHLCV)\b', part): + continue + m = re.search(r'([A-Za-z_]\w*)\s*(=\s*.*)?$', part) + if m: + out.append((idx, m.group(1))) + return out + + +def translate_default(dtxt): + """Translate a C++ default-arg literal to a Python literal.""" + ctx = {'env': {}, 'resolve': lambda n: n, 'ret_types': {}, + 'struct_fields': {}, 'struct_names': set(), 'rename': {}} + toks = tokenize(dtxt) + p = Parser(toks, ctx) + code, _ = p.parse_expr() + if not p.at_eof(): + raise TranspileError('cannot translate default %r' % dtxt) + return code + + +def transpile_function(name, ret, args, body, ctx): + """Transpile one C++ function; return (py_name, py_lines, ret_tag).""" + # parse the signature + params = [] + if args.strip(): + for part in split_top(args): + part = part.strip() + if not part: + continue + # strip leading const, split type/name + part = re.sub(r'^const\s+', '', part) + m = re.match(r'^(.*?)([A-Za-z_]\w*)\s*(=\s*.*)?$', part) + if not m: + raise TranspileError('cannot parse param %r' % part) + type_txt, pname = m.group(1).strip(), m.group(2) + if type_txt.endswith('&') or type_txt.endswith('*'): + type_txt = type_txt[:-1].strip() + ptype = cpp_type_to_py(type_txt) + default = None + if m.group(3): + default = translate_default(m.group(3)[1:].strip()) + params.append((pname, ptype, default)) + env = {} + for pname, ptype, _d in params: + env[pname] = ptype + ret_tag = cpp_type_to_py(ret) if not ret.startswith('std::vector') \ + else 'vec' + if ret.strip() == 'std::vector': + ret_tag = 'vec' + elif ret.strip() == 'std::vector>': + ret_tag = 'vecvec' + elif 'Result' in ret: + ret_tag = 'struct:' + ret.strip() + toks = tokenize(body) + # body starts with '{' + if toks[0].text != '{': + raise TranspileError('function %s body does not start with {' % name) + pctx = dict(ctx) + pctx['env'] = env + pctx['rename'] = {} + # void helpers with out-params return a tuple of them + func_outs = [n for _i, n in out_param_names(args)] if args.strip() \ + else [] + # parameters that shadow Python builtins get a trailing underscore + py_params = [] + for pname, ptype, default in params: + if pname in func_outs: + # out-param: returned as part of a tuple, not passed in + # (kept in env as a local the body assigns) + if pname in PY_BUILTINS: + pctx['rename'][pname] = pname + '_' + continue + if pname in PY_BUILTINS: + pctx['rename'][pname] = pname + '_' + pname = pname + '_' + env[pname] = ptype + py_params.append((pname, default)) + # renamed out-param names, for the tuple returns + pctx['func_out_params'] = [pctx['rename'].get(n, n) + for n in func_outs] + p = Parser(toks[1:], pctx) + lines = p.parse_body() + if func_outs and ret_tag == 'void': + # fall off the end: return the out-values + lines.append((0, 'return (%s)' % ', '.join( + pctx['func_out_params']))) + out = ['def %s(%s):' % (name, ', '.join( + n if d is None else '%s=%s' % (n, d) for n, d in py_params))] + if not lines: + out.append(' pass') + else: + for ind, text in lines: + out.append(' ' * (ind + 1) + text) + return name, out, ret_tag + + +def build_module(crepo, pyrepo): + calls, headers = extract_calls(crepo) + kinds = sorted(calls) + # ---- collect helpers, dedup by (name, body-hash) ---------------------- + helper_bodies = {} # (name, hash) -> {args, body} + kind_helper_map = {} # kind -> {helper name: python name} + multi = {} # helper name -> set of hashes + for kind in kinds: + for hname, h in headers[kind]['helpers'].items(): + multi.setdefault(hname, set()).add(h['hash']) + helper_bodies[(hname, h['hash'])] = h + py_helper_name = {} + for (hname, hh) in helper_bodies: + if len(multi[hname]) == 1: + py_helper_name[(hname, hh)] = hname + else: + py_helper_name[(hname, hh)] = '%s_%s' % (hname, hh) + for kind in kinds: + kind_helper_map[kind] = { + hname: py_helper_name[(hname, h['hash'])] + for hname, h in headers[kind]['helpers'].items()} + # ---- struct field types (all Result structs) ------------------------- + struct_fields = {} + struct_names = set() + struct_map = {} + for kind in kinds: + for sname, fields in headers[kind]['structs'].items(): + struct_names.add(sname) + struct_fields.update(fields) + struct_map.setdefault(sname, fields) + # ---- return types ------------------------------------------------------ + ret_types = {} + # helper signatures: parse from the first header defining each variant + helper_sigs = {} + for kind in kinds: + for hname, h in headers[kind]['helpers'].items(): + key = (hname, h['hash']) + if key not in helper_sigs: + helper_sigs[key] = h['args'] + # return type of a helper, from its C++ signature (verified against + # the headers: most return vector; fin/fin_v bool; nan_v/nanv, + # highest/lowest(_v) and linreg_*_at double; dm_tr/linreg_parts void). + BOOL_HELPERS = {'fin', 'fin_v'} + DOUBLE_HELPERS = {'nan_v', 'nanv', 'highest', 'highest_v', 'lowest', + 'lowest_v', 'linreg_r2_at', 'linreg_slope_at', + 'linreg_value_at'} + VOID_HELPERS = {'dm_tr', 'linreg_parts'} + for (hname, hh), _h in helper_bodies.items(): + py = py_helper_name[(hname, hh)] + if hname in BOOL_HELPERS: + ret_types[py] = 'bool' + elif hname in DOUBLE_HELPERS: + ret_types[py] = 'double' + elif hname in VOID_HELPERS: + ret_types[py] = 'void' + else: + ret_types[py] = 'vec' + # ---- void helpers with out-params (dm_tr, linreg_parts) -------------- + out_params = {} + for (hname, hh), h in helper_bodies.items(): + outs = out_param_names(h['args']) + if outs: + out_params[py_helper_name[(hname, hh)]] = outs + # ---- transpile helpers ------------------------------------------------- + helper_out = OrderedDict() + for (hname, hh) in sorted(helper_bodies): + h = helper_bodies[(hname, hh)] + pyname = py_helper_name[(hname, hh)] + # resolve helper calls within this helper: which header defines + # this variant? any kind whose map has it + owner = next(k for k in kinds + if kind_helper_map[k].get(hname) == pyname) + ctx = make_ctx(owner, kind_helper_map, ret_types, struct_fields, + struct_names, struct_map, out_params) + _n, lines, _r = transpile_function( + pyname, h['ret'], h['args'], h['body'], ctx) + helper_out[pyname] = lines + # ---- transpile ind_* functions ----------------------------------------- + ind_out = OrderedDict() + ind_ret = {} + for kind in kinds: + for f in headers[kind]['funcs']: + ctx = make_ctx(kind, kind_helper_map, ret_types, struct_fields, + struct_names, struct_map, out_params) + name, lines, rtag = transpile_function( + f['name'], f['ret'], f['args'], f['body'], ctx) + ind_out[name] = lines + ind_ret[name] = rtag + ret_types.update(ind_ret) + # NOTE: helper bodies calling ind funcs do not occur (verified), so + # the one-pass order is safe. + # ---- registry ---------------------------------------------------------- + info = OrderedDict() + for kind in kinds: + call = calls[kind] + func_name, params = parse_call_expr(call['expr']) + # first-arg kind from the ind function's signature + sig = None + for f in headers[kind]['funcs']: + if f['name'] == func_name: + sig = f['args'] + series_kind = 'bars' if sig and 'OHLCVSeries' in sig.split(',')[0] \ + else 'closes' + sels = [selector_of(v, func_name) for v in call['vectors']] + info[kind] = {'func': func_name, 'series': series_kind, + 'params': params, 'lines': sels} + return helper_out, ind_out, info, kinds + + +def make_ctx(kind, kind_helper_map, ret_types, struct_fields, + struct_names, struct_map=None, out_params=None): + mapping = kind_helper_map.get(kind, {}) + + def resolve(name): + if name in mapping: + return mapping[name] + return name + + return {'env': {}, 'resolve': resolve, 'ret_types': ret_types, + 'struct_fields': struct_fields, 'struct_names': struct_names, + 'struct_map': struct_map or {}, + 'out_params': out_params or {}} + + +HEADER = '''"""Technical indicators (250): per-kind compute functions. + +Transpiled from the LightGUI C repo (``widgets/components/Ind*/Ind*.h``) +by ``tools/transpile_indicators.py`` -- DO NOT EDIT BY HAND; regenerate. +Each ``ind_*`` function is the C++ widget's own compute: it takes the +OHLCV bars (or the closes) plus its parameters and returns one series +per plotted line (or a result object with named line fields), with the +C++ NaN warm-up semantics (NaN until the window is full, non-finite +inputs skipped, never averaged in). + +Feeding real data: ``IndicatorWidget`` (``lightgui/xframe/core.py``) +holds the series and calls :func:`compute_lines` on every draw, so a +``load_csv`` / ``set_series`` / ``add_point`` immediately recomputes the +lines from the loaded OHLCV data. With no loaded series the widget +plots the built-in deterministic demo series (``stock.demo_series``, +seed 42, 250 bars), exactly as the C++ widgets do with +``make_seeded_series(250)``. + +``INDICATOR_INFO`` maps each palette kind to its compute function, the +series it consumes (``bars`` or ``closes``), its default parameters, +and which lines of the result it plots. +""" + +import math +from types import SimpleNamespace + +from lightgui.xframe.stock import demo_series + + +def _fmax(a, b): + """``std::max`` on doubles: NaN is ignored (the other operand wins).""" + if isinstance(a, float) and math.isnan(a): + return b + if isinstance(b, float) and math.isnan(b): + return a + return a if a > b else b + + +def _fmin(a, b): + """``std::min`` on doubles: NaN is ignored (the other operand wins).""" + if isinstance(a, float) and math.isnan(a): + return b + if isinstance(b, float) and math.isnan(b): + return a + return a if a < b else b + + +def _closes(bars): + return [b[3] for b in bars] + + +def _opens(bars): + return [b[0] for b in bars] + + +def _highs(bars): + return [b[1] for b in bars] + + +def _lows(bars): + return [b[2] for b in bars] + + +def _volumes(bars): + return [b[4] for b in bars] + + +def _typical(bars): + return [(b[1] + b[2] + b[3]) / 3.0 for b in bars] + +''' + + +def emit_module(helper_out, ind_out, info, kinds, out_path, c_head): + parts = [HEADER] + parts.append('# --- shared helpers (deduped by body hash) ---') + parts.append('# C++ provenance: lightgui %s' % c_head) + for pyname, lines in helper_out.items(): + parts.append('') + parts.extend(lines) + parts.append('') + parts.append('# --- per-kind compute functions ---') + for name, lines in ind_out.items(): + parts.append('') + parts.extend(lines) + parts.append('') + parts.append('# --- registry ---') + parts.append('INDICATOR_INFO = {') + for kind in kinds: + e = info[kind] + parts.append(' %r: {"func": %r, "series": %r, "params": %r, ' + '"lines": %r},' % ( + kind, e['func'], e['series'], e['params'], + e['lines'])) + parts.append('}') + parts.append('') + parts.append('') + parts.append('def compute_lines(kind, bars, params=None):') + parts.append(' """Plotted lines for *kind* from OHLCV *bars*.') + parts.append('') + parts.append(' *bars* is a list of (open, high, low, close, volume)') + parts.append(' tuples. Returns a list of series (one float per bar,') + parts.append(' NaN where the indicator has no value yet), in the') + parts.append(' order the widget plots them. *params* overrides the') + parts.append(' kind\'s default parameters positionally.') + parts.append(' """') + parts.append(' entry = INDICATOR_INFO[kind]') + parts.append(' func = globals()[entry["func"]]') + parts.append(' use = list(entry["params"] if params is None else params)') + parts.append(' if entry["series"] == "bars":') + parts.append(' result = func(bars, *use)') + parts.append(' else:') + parts.append(' result = func(_closes(bars), *use)') + parts.append(' lines = []') + parts.append(' for sel in entry["lines"]:') + parts.append(' if sel is None:') + parts.append(' lines.append(result)') + parts.append(' elif sel[0] == "field":') + parts.append(' lines.append(getattr(result, sel[1]))') + parts.append(' else:') + parts.append(' lines.append(result.lines[sel[1]])') + parts.append(' return lines') + parts.append('') + parts.append('') + parts.append('def _bars(widget):') + parts.append(' """Bars a widget plots: its own series when set, else') + parts.append(' the built-in demo series (same fallback as StockWidget).') + parts.append(' A cleared widget (own series == []) plots nothing.') + parts.append(' \"\"\"') + parts.append(' own = widget._series') + parts.append(' if own is not None:') + parts.append(' return own') + parts.append(' return demo_series()') + parts.append('') + parts.append('') + parts.append('def indicator_names():') + parts.append(' """All 250 indicator palette kinds, in palette order."""') + parts.append(' return list(INDICATOR_INFO)') + text = '\n'.join(parts) + with open(out_path, 'w') as f: + f.write(text) + return text + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument('--crepo', default='/opt/lightgui') + ap.add_argument('--pyrepo', default='/opt/lightgui_python') + args = ap.parse_args() + helper_out, ind_out, info, kinds = build_module(args.crepo, + args.pyrepo) + out_path = os.path.join(args.pyrepo, 'lightgui', 'xframe', + 'indicators.py') + c_head = os.popen('cd %s && git rev-parse --short HEAD 2>/dev/null' + % args.crepo).read().strip() + emit_module(helper_out, ind_out, info, kinds, out_path, c_head) + print('wrote %s: %d helpers, %d ind funcs, %d kinds' + % (out_path, len(helper_out), len(ind_out), len(kinds))) + + +if __name__ == '__main__': + main()