Files
lightgui_python/tools/transpile_indicators.py
cnmcdee 3b67cbf9de Ind* indicators: CSV/series support on all 250 kinds
Transpile the C component ind_* function for every kind into
lightgui/xframe/indicators.py (tools/transpile_indicators.py), verified
250/250 against the C++ reference dump (<=1e-9, NaN patterns included).
IndicatorWidget gains the StockWidget series API (set_series, populate,
get_series, add_point, clear, load_csv, item_count, get_lines) and draws
the computed lines (14-colour palette, NaN gaps, dots for isolated
marker points) with the demo series as fallback. Docs in
docs/indicators-data.md; tests/test_indicators_csv.py (17 tests, golden
spot values vs the C++ reference); Xvfb shots via
tools/ind_csv_shots.py.
2026-12-02 11:04:35 +00:00

1891 lines
69 KiB
Python

#!/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<ws>\s+)
| (?P<comment>//[^\n]*|/\*.*?\*/)
| (?P<string>"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')
| (?P<number>(?:\d+\.\d*|\.\d+|\d+)(?:[eE][+-]?\d+)?[fFuUlL]*|0[xX][0-9a-fA-F]+[uUlL]*)
| (?P<ident>[A-Za-z_][A-Za-z0-9_]*)
| (?P<op><<=|>>=|==|!=|<=|>=|&&|\|\||\+\+|--|\+=|-=|\*=|/=|%=|->|::|<<|>>)
| (?P<punct>.)
""", 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<double>':
return 'vec'
if t == 'std::vector<std::vector<double>>':
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] <op> 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 <op'> 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<T> 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<double>::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<double> 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>|double|void|int|bool|'
r'std::vector<std::vector<double>>)\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<double>|std::vector<std::vector<double>>|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<double>' 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<double>':
ret_tag = 'vec'
elif ret.strip() == 'std::vector<std::vector<double>>':
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<double>; 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()