"""Independent replication of the three ChartingLens methodology examples. Order filling and trade accounting: Backtesting.py (open source, https://github.com/kernc/backtesting.py), not ChartingLens code. Indicators and statistics: written here from their published definitions. Settings match ChartingLens's documented rules: market orders fill at the next bar's open, no commission, no slippage, one position at a time, the full account in every trade, a position still open at the end reported separately. Usage: python independent_backtest.py (reads data/*.csv, writes results/independent.json) """ import json import math from pathlib import Path import numpy as np import pandas as pd from backtesting import Backtest, Strategy HERE = Path(__file__).parent # ---- indicators (TradingView / Pine Script definitions) ------------------- def sma_seeded(values, length, alpha): """Exponential smoothing seeded with the simple average of the first `length` values (TradingView's ta.ema / ta.rma). NaN before that.""" out = np.full(len(values), np.nan) prev = np.nan window = [] for i, v in enumerate(values): if math.isnan(v): continue window.append(v) if math.isnan(prev): if len(window) >= length: prev = sum(window[-length:]) / length out[i] = prev else: prev = alpha * v + (1 - alpha) * prev out[i] = prev return out def ema(values, length): return sma_seeded(values, length, 2 / (length + 1)) def rsi(close, length): """Wilder's RSI: average gains and losses smoothed with alpha = 1/length.""" change = np.diff(close, prepend=np.nan) gains = np.where(np.isnan(change), np.nan, np.maximum(change, 0)) losses = np.where(np.isnan(change), np.nan, np.maximum(-change, 0)) up = sma_seeded(gains, length, 1 / length) dn = sma_seeded(losses, length, 1 / length) out = np.full(len(close), np.nan) for i in range(len(close)): if math.isnan(up[i]) or math.isnan(dn[i]): continue out[i] = 100.0 if dn[i] == 0 else 0.0 if up[i] == 0 else 100 - 100 / (1 + up[i] / dn[i]) return out def crossover(a, b, i): """Pine ta.crossover: a crosses above b on bar i.""" if i < 1 or any(math.isnan(x) for x in (a[i], b[i], a[i - 1], b[i - 1])): return False return a[i] > b[i] and a[i - 1] <= b[i - 1] def crossunder(a, b, i): if i < 1 or any(math.isnan(x) for x in (a[i], b[i], a[i - 1], b[i - 1])): return False return a[i] < b[i] and a[i - 1] >= b[i - 1] def rolling_prev(values, length, fn): """fn (max/min) of the `length` bars BEFORE bar i (Pine's highest(...)[1]).""" s = pd.Series(values) return getattr(s.rolling(length), fn)().shift(1).to_numpy() # ---- strategies ----------------------------------------------------------- class EmaTrend(Strategy): def init(self): c = np.asarray(self.data.Close, dtype=float) self.fast, self.slow = ema(c, 20), ema(c, 50) def next(self): i = len(self.data) - 1 if crossover(self.fast, self.slow, i) and not self.position: self.buy() if crossunder(self.fast, self.slow, i) and self.position: self.position.close() class RsiMeanReversion(Strategy): def init(self): self.r = rsi(np.asarray(self.data.Close, dtype=float), 14) def next(self): i = len(self.data) - 1 if crossover(self.r, np.full(len(self.r), 30.0), i) and not self.position: self.buy() if crossover(self.r, np.full(len(self.r), 70.0), i) and self.position: self.position.close() class Breakout(Strategy): def init(self): self.upper = rolling_prev(np.asarray(self.data.High, dtype=float), 20, 'max') self.lower = rolling_prev(np.asarray(self.data.Low, dtype=float), 10, 'min') def next(self): i = len(self.data) - 1 close = self.data.Close[-1] if not self.position and not math.isnan(self.upper[i]) and close > self.upper[i]: self.buy() # 8% stop from the entry price, resting from the bar after the fill. for trade in self.trades: if trade.sl is None: trade.sl = trade.entry_price * 0.92 if self.position and not math.isnan(self.lower[i]) and close < self.lower[i]: self.position.close() STRATEGIES = {'ema-20-50-spy': ('SPY', EmaTrend), 'rsi-30-70-aapl': ('AAPL', RsiMeanReversion), 'breakout-msft': ('MSFT', Breakout)} # ---- statistics (ChartingLens methodology definitions) -------------------- def stats(returns): wins = [r for r in returns if r > 0] losses = [r for r in returns if r <= 0] equity, peak, max_dd = 1.0, 1.0, 0.0 for r in returns: equity *= 1 + r / 100 peak = max(peak, equity) max_dd = min(max_dd, (equity / peak - 1) * 100) gross_loss = abs(sum(losses)) return { 'totalTrades': len(returns), 'winningTrades': len(wins), 'losingTrades': len(losses), 'winRate': f"{len(wins) / len(returns) * 100:.1f}" if returns else '0.0', 'totalReturn': f"{(equity - 1) * 100:.2f}", 'maxDrawdown': f"{max_dd:.2f}", 'profitFactor': f"{sum(wins) / gross_loss:.2f}" if gross_loss else 'Inf', 'avgWin': f"{sum(wins) / len(wins):.2f}" if wins else '0.00', 'avgLoss': f"{sum(losses) / len(losses):.2f}" if losses else '0.00', 'bestTrade': f"{max(returns):.2f}" if returns else '0.00', 'worstTrade': f"{min(returns):.2f}" if returns else '0.00', } def run(example_id): symbol, strategy = STRATEGIES[example_id] df = pd.read_csv(HERE / 'data' / f'{symbol}.csv', parse_dates=['date']).set_index('date') df = df.rename(columns=str.capitalize) # Big cash so whole-share rounding never changes a trade; fills and exits # are compared by price, and returns are computed from those prices. bt = Backtest(df, strategy, cash=1e13, commission=0.0, trade_on_close=False, exclusive_orders=False, finalize_trades=False) out = bt.run() tr = out['_trades'] trades = [] for _, t in tr.iterrows(): ret = (t['ExitPrice'] - t['EntryPrice']) / t['EntryPrice'] * 100 trades.append({'entryDate': str(t['EntryTime'].date()), 'exitDate': str(t['ExitTime'].date()), 'entryPrice': float(t['EntryPrice']), 'exitPrice': float(t['ExitPrice']), 'pctReturn': ret}) open_trade = None strat = out['_strategy'] if strat.position: last_close = float(df['Close'].iloc[-1]) entry = float(strat.trades[-1].entry_price) open_trade = {'entryDate': str(df.index[strat.trades[-1].entry_bar].date()), 'entryPrice': entry, 'markPrice': last_close, 'pctReturn': (last_close - entry) / entry * 100} return {'id': example_id, 'symbol': symbol, 'bars': len(df), 'stats': stats([t['pctReturn'] for t in trades]), 'openTrade': open_trade, 'trades': trades, 'engine': 'backtesting.py'} if __name__ == '__main__': import backtesting results = [run(k) for k in STRATEGIES] (HERE / 'results').mkdir(exist_ok=True) (HERE / 'results' / 'independent.json').write_text(json.dumps(results, indent=2)) for r in results: s = r['stats'] print(f"{r['id']:<16} {r['symbol']} {r['bars']} bars trades {s['totalTrades']} return {s['totalReturn']}% " f"maxDD {s['maxDrawdown']}% PF {s['profitFactor']} open {r['openTrade']['pctReturn']:.2f}%" if r['openTrade'] else f"{r['id']:<16} {r['symbol']} {r['bars']} bars trades {s['totalTrades']} return {s['totalReturn']}% maxDD {s['maxDrawdown']}% PF {s['profitFactor']}") print('backtesting.py', backtesting.__version__)