Team Ai
Apppublic

diegobeyl/backtesting

sourceHugging Faceupdated 9mo agoView on Hugging Face
2likes
debug_algorithm.py154 linesDownload Raw Back to backtesting_app
1"""2Script de debug para comparar valores del algoritmo con TradingView3"""4import pandas as pd5import yfinance as yf6from datetime import datetime7 8# Descargar datos9ticker = yf.Ticker("BTC-USD")10df = ticker.history(interval="1mo", start="2020-01-01", end="2026-01-01")11 12print("=" * 80)13print("DATOS DE YFINANCE - BTC-USD - 1mo")14print("=" * 80)15 16# Mostrar primeras barras con High, Low, Close17print("\nPrimeras 20 barras:")18print(f"{'Fecha':<12} {'High':>12} {'Low':>12} {'Close':>12}")19print("-" * 50)20for i in range(min(20, len(df))):21    row = df.iloc[i]22    date = str(row.name.date())23    print(f"{date:<12} {row['High']:>12.2f} {row['Low']:>12.2f} {row['Close']:>12.2f}")24 25print("\n" + "=" * 80)26print("SIMULACIÓN DEL ALGORITMO ARIASCAMPOS 5.2")27print("Parámetros: lookbehind=0, stopResetsSupport=True, breakMargin=3%")28print("=" * 80)29 30# Simular algoritmo31lookbehind = 032stopResetsSupport = True33breakMargin = 0.03  # 3% para timeframe mensual34 35# Variables36resistence = None37support = None38tendency = 039resistenceBroken = False40supportBroken = False41min_val = 042max_val = 043 44# Arrays para estado45states = []46 47for i in range(len(df)):48    row = df.iloc[i]49    high = float(row['High'])50    low = float(row['Low'])51    close = float(row['Close'])52    date = str(row.name.date())53    54    high_1 = float(df.iloc[i-1]['High']) if i > 0 else high55    low_1 = float(df.iloc[i-1]['Low']) if i > 0 else low56    57    # Guardar estados previos58    resistenceBroken_1 = resistenceBroken59    supportBroken_1 = supportBroken60    min_1 = min_val61    max_1 = max_val62    tendency_antes = tendency63    64    # Reset65    if i == 0:66        resistence = None67        support = None68        tendency = 069        min_val = low70        max_val = high71    else:72        # max := math.max(high, max[1])73        max_val = max(high, max_1)74        # min := math.min(low, min[1])75        min_val = min(low, min_1)76        77        # if supportBroken[1] → support := na78        if supportBroken_1:79            support = None80        # if resistenceBroken[1] → resistence := na81        if resistenceBroken_1:82            resistence = None83    84    resistenceBroken = False85    supportBroken = False86    87    # Break resistence?88    if not supportBroken and resistence is not None:89        margin_mult = (1 + breakMargin) if tendency == 0 else 1.090        threshold = resistence * margin_mult91        if high > threshold:92            resistenceBroken = True93            min_val = min(low, min_1) if i > 0 else low94            max_val = high95            support = min_val96            97            if tendency == 0:98                if stopResetsSupport:99                    min_val = min(low, low_1)100                support = min_val101            tendency = 1102    103    # Break support?104    if not resistenceBroken and support is not None:105        margin_mult = (1 - breakMargin) if tendency == 1 else 1.0106        threshold = support * margin_mult107        if low < threshold:108            supportBroken = True109            max_val = max(high, max_1) if i > 0 else high110            min_val = low111            resistence = max_val112            113            if tendency == 1:114                if stopResetsSupport:115                    max_val = max(high, high_1)116                    resistence = max_val117                tendency = 0118    119    # Max Max (bearish)120    if not resistenceBroken and not supportBroken and tendency == 0:121        if high > high_1:122            max_val = high123            support = low124    125    # Min min (bullish)126    if not resistenceBroken and not supportBroken and tendency == 1:127        if low < low_1:128            min_val = low129            resistence = high130    131    # Señales132    signal = ""133    if resistenceBroken and tendency_antes == 0 and tendency == 1:134        signal = "LONG"135    if supportBroken and tendency_antes == 1 and tendency == 0:136        signal = "SHORT"137    138    states.append({139        'date': date,140        'high': high,141        'low': low,142        'tendency': 'BULL' if tendency == 1 else 'BEAR',143        'support': support,144        'resistence': resistence,145        'signal': signal146    })147 148print("\n" + f"{'Fecha':<12} {'High':>10} {'Low':>10} {'Tendency':>8} {'Support':>12} {'Resistence':>12} {'Signal':>8}")149print("-" * 80)150for s in states:151    sup = f"{s['support']:.2f}" if s['support'] else "na"152    res = f"{s['resistence']:.2f}" if s['resistence'] else "na"153    print(f"{s['date']:<12} {s['high']:>10.2f} {s['low']:>10.2f} {s['tendency']:>8} {sup:>12} {res:>12} {s['signal']:>8}")154