-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauto_update_config.py
More file actions
187 lines (144 loc) · 7.2 KB
/
auto_update_config.py
File metadata and controls
187 lines (144 loc) · 7.2 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Sistema automático de atualização da configuração ML
Executa apenas quando há dados suficientes para melhorar os thresholds
"""
import os
import json
import pandas as pd
from datetime import datetime, timedelta
from pathlib import Path
class AutoConfigUpdater:
"""Atualiza configuração automaticamente quando necessário"""
def __init__(self):
self.data_dir = Path("data")
self.config_file = "config_ml_amanha.json"
self.log_file = "auto_update_log.txt"
def should_update_config(self):
"""Determina se deve atualizar a configuração baseado nos dados de hoje"""
print("VERIFICANDO: Necessidade de atualizar configuracao...")
# 1. Verificar se já existe configuração
if not os.path.exists(self.config_file):
return True, "Nenhuma configuracao existente"
# 2. Verificar idade da configuração atual
try:
with open(self.config_file, 'r', encoding='utf-8') as f:
config = json.load(f)
config_date = config.get('data_criacao', '')
if config_date:
config_datetime = datetime.strptime(config_date, '%Y-%m-%d %H:%M:%S')
days_old = (datetime.now() - config_datetime).days
if days_old >= 7:
return True, f"Configuracao com {days_old} dias - atualizacao recomendada"
except Exception as e:
return True, f"Erro ao ler configuracao existente: {e}"
# 3. Verificar volume de dados coletados hoje
today_str = datetime.now().strftime("%Y%m%d")
# Contar arquivos de hoje
trade_files = list(self.data_dir.glob(f"trades/trades_{today_str}_*.csv"))
regime_files = list(self.data_dir.glob(f"regimes/regimes_{today_str}_*.json"))
if not trade_files:
return False, "Nenhum dado de trade coletado hoje"
# Verificar tamanho dos arquivos
total_trades = 0
total_regimes = 0
for trade_file in trade_files:
try:
df = pd.read_csv(trade_file)
total_trades += len(df)
except:
continue
for regime_file in regime_files:
if regime_file.stat().st_size > 1000: # Arquivo com conteúdo
try:
with open(regime_file, 'r', encoding='utf-8') as f:
regimes = json.load(f)
total_regimes += len(regimes)
except:
continue
print(f"Dados de hoje: {total_trades:,} trades, {total_regimes:,} analises de regime")
# 4. Critérios para atualização
if total_trades > 500000: # Mais de 500k trades
return True, f"Volume significativo: {total_trades:,} trades coletados"
if total_regimes > 500: # Mais de 500 análises de regime
return True, f"Analises suficientes: {total_regimes:,} regimes registrados"
# 5. Verificar se há dados ML estruturados
ml_files = [f for f in os.listdir('.') if f.startswith(f'ml_dataset_{today_str}')]
if ml_files:
largest_ml = max(ml_files, key=lambda x: os.path.getsize(x))
ml_size = os.path.getsize(largest_ml) / 1024 # KB
if ml_size > 50: # Dataset > 50KB
return True, f"Dataset ML robusto: {largest_ml} ({ml_size:.1f}KB)"
return False, f"Dados insuficientes hoje: {total_trades:,} trades, {total_regimes:,} regimes"
def run_ml_insights_if_needed(self):
"""Executa ml_insights_hoje.py apenas se necessário"""
should_update, reason = self.should_update_config()
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
log_entry = f"{timestamp} - {reason}\n"
print(f"\nDECISAO: {reason}")
if should_update:
print("EXECUTANDO: Atualizacao da configuracao ML...")
# Executar análise ML
try:
import subprocess
result = subprocess.run(['python', 'ml_insights_hoje.py'],
capture_output=True, text=True, encoding='utf-8')
if result.returncode == 0:
log_entry += f"{timestamp} - SUCESSO: Configuracao atualizada com novos dados\n"
print("SUCESSO: Configuracao atualizada!")
return True
else:
log_entry += f"{timestamp} - ERRO: Falha na atualizacao - {result.stderr}\n"
print(f"ERRO na atualizacao: {result.stderr}")
return False
except Exception as e:
log_entry += f"{timestamp} - ERRO: Exception durante atualizacao - {e}\n"
print(f"ERRO: {e}")
return False
else:
print("PULANDO: Atualizacao nao necessaria hoje")
log_entry += f"{timestamp} - PULADO: Atualizacao nao necessaria\n"
# Salvar log
with open(self.log_file, 'a', encoding='utf-8') as f:
f.write(log_entry)
return not should_update # True se não precisou atualizar (tudo OK)
def get_current_config_status(self):
"""Mostra status da configuração atual"""
if not os.path.exists(self.config_file):
return "Nenhuma configuracao encontrada"
try:
with open(self.config_file, 'r', encoding='utf-8') as f:
config = json.load(f)
created = config.get('data_criacao', 'Desconhecido')
based_on = config.get('baseado_em', 'Desconhecido')
params = config.get('parametros_otimizados', {})
temp_min = params.get('temperatura_minima_entrada', 'N/A')
confidence = params.get('confianca_regime_minima', 'N/A')
return f"""
CONFIGURACAO ATUAL:
Criada em: {created}
Baseada em: {based_on}
Temperatura minima: {temp_min}
Confianca minima: {confidence}%
""".strip()
except Exception as e:
return f"Erro ao ler configuracao: {e}"
def main():
"""Execução automática inteligente"""
print("SISTEMA DE ATUALIZACAO AUTOMATICA ML")
print("=" * 60)
updater = AutoConfigUpdater()
# Mostrar status atual
print(updater.get_current_config_status())
# Verificar e atualizar se necessário
success = updater.run_ml_insights_if_needed()
print(f"\n" + "=" * 60)
if success:
print("RESULTADO: Sistema de configuracao atualizado/validado com sucesso!")
print("Amanha o monitor_gui.py usara a melhor configuracao disponivel")
else:
print("ATENCAO: Problema na atualizacao - configuracao anterior mantida")
return success
if __name__ == "__main__":
main()