Team Ai
Apppublic

diegobeyl/backtesting

sourceHugging Faceupdated 9mo agoView on Hugging Face
2likes
patch_backtester.py53 linesDownload Raw Back to utilities
1# Patch para el backtester: aplicar margen al stop loss como en PineScript
2# El problema: el backtester usa support directo, pero debería aplicar margen
3
4import sys
5
6file_path = r"C:\Users\Javier\Downloads\backtesting_app_v2\backtesting_app\backtesting_app\core\backtester.py"
7
8with open(file_path, 'r', encoding='utf-8') as f:
9    content = f.read()
10
11# Fix 1: Guardar el margen cuando se ejecuta el algoritmo
12old_code_1 = """        # Ejecutar algoritmo
13        algo_result = self.algorithm.run(df, algo_params)"""
14
15new_code_1 = """        # Ejecutar algoritmo
16        algo_result = self.algorithm.run(df, algo_params)
17        
18        # Guardar el margen para aplicarlo al stop loss
19        self._break_margin = algo_result.states[0].extra_data.get('break_margin', 0.0) if algo_result.states else 0.0"""
20
21content = content.replace(old_code_1, new_code_1)
22
23# Fix 2: Aplicar margen al soporte cuando se actualiza el SL para LONG
24old_code_2 = """            # Actualizar SL si el soporte subió
25            if state.support is not None:
26                new_sl = state.support"""
27
28new_code_2 = """            # Actualizar SL si el soporte subió
29            if state.support is not None:
30                # Aplicar margen como en PineScript: support * (1 - breakMargin)
31                new_sl = state.support * (1 - self._break_margin) if hasattr(self, '_break_margin') else state.support"""
32
33content = content.replace(old_code_2, new_code_2)
34
35# Fix 3: Aplicar margen a la resistencia cuando se actualiza el SL para SHORT
36old_code_3 = """            # Actualizar SL si la resistencia bajó
37            if state.resistance is not None:
38                new_sl = state.resistance"""
39
40new_code_3 = """            # Actualizar SL si la resistencia bajó
41            if state.resistance is not None:
42                # Aplicar margen como en PineScript: resistance * (1 + breakMargin)
43                new_sl = state.resistance * (1 + self._break_margin) if hasattr(self, '_break_margin') else state.resistance"""
44
45content = content.replace(old_code_3, new_code_3)
46
47with open(file_path, 'w', encoding='utf-8') as f:
48    f.write(content)
49
50print("Backtester patcheado exitosamente!")
51print(f"- Se aplicará el margen al stop loss para LONG: support * (1 - margin)")
52print(f"- Se aplicará el margen al stop loss para SHORT: resistance * (1 + margin)")
53