-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
99 lines (84 loc) · 4.26 KB
/
Copy pathmain.py
File metadata and controls
99 lines (84 loc) · 4.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import argparse
import sys
import pandas as pd
from datetime import datetime
from src.database.db_manager import load_from_sqlite_to_pandas, upload_excel_to_sqlite
from src.engine.operacional import simular_operacional, executar_backtest_completo
from src.analysis.analise_parametros import resumo_analises, analisar_distribuicao_mae_mfe
from src.reports.relatorio_html import gerar_relatorio
from src.engine.trade import gerar_estatisticas_completas, imprimir_stats
from datetime import time
def main():
parser = argparse.ArgumentParser(description="BackTesting Framework - Professional CLI")
# Core Actions
parser.add_argument("--upload", type=str, help="Upload Excel file to database (provide file path)")
parser.add_argument("--run", action="store_true", help="Run the backtest simulation")
parser.add_argument("--report", action="store_true", help="Generate HTML report from simulation results")
parser.add_argument("--optimize", action="store_true", help="Run parameter optimization analysis (simple)")
parser.add_argument("--ga", action="store_true", help="Run Genetic Algorithm optimizer (DEAP)")
parser.add_argument("--pop", type=int, default=None, help="Population size for GA (overrides config)")
parser.add_argument("--gen", type=int, default=None, help="Number of generations for GA (overrides config)")
parser.add_argument("--workers", type=int, default=None, help="Number of CPU workers for GA (default: max)")
parser.add_argument("--all", action="store_true", help="Run full workflow (run, optimize, report)")
# Parameters
parser.add_argument("--contracts", type=int, default=2, help="Number of contracts (default: 2)")
parser.add_argument("--be", type=int, help="Break-even points")
parser.add_argument("--stop-max", type=int, help="Maximum stop points")
parser.add_argument("--verbose", action="store_true", help="Enable verbose output")
parser.add_argument("--title", type=str, default="Backtest results", help="Title for the report")
parser.add_argument("--output", type=str, default="output/relatorio.html", help="Output path for HTML report")
args = parser.parse_args()
# Load data
try:
df = load_from_sqlite_to_pandas().sort_values('Data').reset_index(drop=True)
except Exception as e:
print(f"Error loading database: {e}")
if not args.upload:
print("Try running with --upload <file.xlsx> first.")
return
if args.upload:
print(f"Uploading {args.upload} to database...")
upload_excel_to_sqlite(args.upload)
print("Upload complete.")
if not (args.run or args.all or args.optimize or args.report):
return
# Reload DF after upload
df = load_from_sqlite_to_pandas().sort_values('Data').reset_index(drop=True)
params = {
'n_contratos': args.contracts,
'verbose': args.verbose,
'breakeven_pontos': args.be,
'stop_max': args.stop_max
}
results = []
if args.run or args.all:
print(f"Running simulation with {args.contracts} contracts...")
trades = simular_operacional(
df,
n_contratos=2,
verbose=False,
breakeven_pontos=200,
tipo_parcial=None,
valores_parciais=None,
stop_max=500,
horario_inicial=time(9, 15),
horario_final=time(17, 45),
horario_encerramento=time(18, 00))
output_html = 'output/relatorio_bt_completo.html'
gerar_relatorio(trades, output_html, titulo="Backtest Completo")
print(f"\n[OK] Relatório HTML gerado: {output_html}")
if args.ga:
print(f"\nStarting Genetic Algorithm Optimizer...")
from src.analysis.otimizador import otimizar
otimizar(df, n_workers=args.workers, pop_size=args.pop, ngen=args.gen)
if (args.report or args.all) and results:
print(f"Generating HTML report: {args.output}")
# Ensure output directory exists
import os
os.makedirs(os.path.dirname(args.output), exist_ok=True)
gerar_relatorio(results, args.output, args.title)
print("Report ready.")
if not any([args.upload, args.run, args.report, args.optimize, args.all, args.ga]):
parser.print_help()
if __name__ == "__main__":
main()