Markdown resultados
Browse files- __pycache__/stocks.cpython-311.pyc +0 -0
- app.py +33 -5
- stocks.py +11 -2
__pycache__/stocks.cpython-311.pyc
CHANGED
Binary files a/__pycache__/stocks.cpython-311.pyc and b/__pycache__/stocks.cpython-311.pyc differ
|
|
app.py
CHANGED
@@ -125,11 +125,14 @@ class GradioInterface:
|
|
125 |
with gr.Row():
|
126 |
# Adicionar uma saída para os resultados
|
127 |
output_md = gr.Markdown()
|
128 |
-
|
|
|
|
|
|
|
129 |
run_btn.click(
|
130 |
self.run_full_analysis,
|
131 |
inputs=[ticker_input, fetch_new, initial_investment, years_back, commission, api_key_input],
|
132 |
-
outputs=[output_md, plot_output]
|
133 |
)
|
134 |
return main_interface
|
135 |
|
@@ -180,11 +183,35 @@ class GradioInterface:
|
|
180 |
|
181 |
progress(0.6, desc="Executando simulação...")
|
182 |
|
183 |
-
final_value = bt_integration.run_simulation(
|
184 |
initial_cash=initial_investment,
|
185 |
commission=commission
|
186 |
)
|
187 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
188 |
progress(0.9, desc="Gerando resultados...")
|
189 |
|
190 |
# Extrair os valores do JSON de sentimento
|
@@ -210,10 +237,11 @@ class GradioInterface:
|
|
210 |
- **Preço vs SMA50**: {result['technical']['price_vs_sma']:.2%}
|
211 |
- **P/E Ratio**: {result['fundamental'].get('trailingPE', 'N/A')}
|
212 |
"""
|
|
|
213 |
# Gerar gráfico simples (exemplo)
|
214 |
plot = self.generate_simple_plot(bt_integration)
|
215 |
|
216 |
-
return output, plot
|
217 |
|
218 |
|
219 |
def generate_simple_plot(self, bt_integration):
|
|
|
125 |
with gr.Row():
|
126 |
# Adicionar uma saída para os resultados
|
127 |
output_md = gr.Markdown()
|
128 |
+
with gr.Row():
|
129 |
+
# Adicionar uma saída para os resultados
|
130 |
+
output_ops = gr.Markdown()
|
131 |
+
|
132 |
run_btn.click(
|
133 |
self.run_full_analysis,
|
134 |
inputs=[ticker_input, fetch_new, initial_investment, years_back, commission, api_key_input],
|
135 |
+
outputs=[output_md, output_ops, plot_output]
|
136 |
)
|
137 |
return main_interface
|
138 |
|
|
|
183 |
|
184 |
progress(0.6, desc="Executando simulação...")
|
185 |
|
186 |
+
final_value, operation_logs = bt_integration.run_simulation(
|
187 |
initial_cash=initial_investment,
|
188 |
commission=commission
|
189 |
)
|
190 |
+
|
191 |
+
# Formatar logs de operação
|
192 |
+
formatted_logs = []
|
193 |
+
for log in operation_logs:
|
194 |
+
if "BUY EXECUTED" in log:
|
195 |
+
parts = log.split(", ")
|
196 |
+
date = parts[0].strip()
|
197 |
+
details = ", ".join(parts[1:]).replace("BUY EXECUTED, ", "")
|
198 |
+
formatted_logs.append(f"- 🟢 **Compra** ({date}): {details}")
|
199 |
+
elif "SELL EXECUTED" in log:
|
200 |
+
parts = log.split(", ")
|
201 |
+
date = parts[0].strip()
|
202 |
+
details = ", ".join(parts[1:]).replace("SELL EXECUTED, ", "")
|
203 |
+
formatted_logs.append(f"- 🔴 **Venda** ({date}): {details}")
|
204 |
+
elif "TRADE PROFIT" in log:
|
205 |
+
parts = log.split(", ")
|
206 |
+
date = parts[0].strip()
|
207 |
+
details = ", ".join(parts[1:])
|
208 |
+
formatted_logs.append(f"- 📊 **Resultado** ({date}): {details}")
|
209 |
+
elif "Final Portfolio Value" in log:
|
210 |
+
continue # Ignora a linha final duplicada
|
211 |
+
|
212 |
+
# Adicionar seção de logs na saída
|
213 |
+
output_ops = "### Histórico de Operações:\n\n" + "\n".join(formatted_logs)
|
214 |
+
|
215 |
progress(0.9, desc="Gerando resultados...")
|
216 |
|
217 |
# Extrair os valores do JSON de sentimento
|
|
|
237 |
- **Preço vs SMA50**: {result['technical']['price_vs_sma']:.2%}
|
238 |
- **P/E Ratio**: {result['fundamental'].get('trailingPE', 'N/A')}
|
239 |
"""
|
240 |
+
|
241 |
# Gerar gráfico simples (exemplo)
|
242 |
plot = self.generate_simple_plot(bt_integration)
|
243 |
|
244 |
+
return output, output_ops, plot
|
245 |
|
246 |
|
247 |
def generate_simple_plot(self, bt_integration):
|
stocks.py
CHANGED
@@ -437,8 +437,14 @@ class BacktraderIntegration:
|
|
437 |
self.cerebro.broker.setcommission(commission=commission)
|
438 |
print(f'\nStarting Portfolio Value: {self.cerebro.broker.getvalue():.2f}')
|
439 |
self.cerebro.run()
|
|
|
|
|
|
|
|
|
|
|
|
|
440 |
print(f'Final Portfolio Value: {self.cerebro.broker.getvalue():.2f}')
|
441 |
-
return self.cerebro.broker.getvalue()
|
442 |
|
443 |
class CustomStrategy(bt.Strategy):
|
444 |
params = (
|
@@ -459,6 +465,7 @@ class BacktraderIntegration:
|
|
459 |
|
460 |
def __init__(self):
|
461 |
# Parâmetros agora são acessados via self.params
|
|
|
462 |
self.recommendation = self.params.analysis['recommendation'] if self.params.analysis else 'HOLD'
|
463 |
self.technical_analysis = self.params.analysis['technical'] if self.params.analysis else None
|
464 |
self.sentiment_analysis = self.params.analysis['sentiment'] if self.params.analysis else None
|
@@ -499,7 +506,9 @@ class BacktraderIntegration:
|
|
499 |
|
500 |
def log(self, txt, dt=None):
|
501 |
dt = dt or self.datas[0].datetime.date(0)
|
502 |
-
|
|
|
|
|
503 |
|
504 |
def notify_order(self, order):
|
505 |
if order.status in [order.Submitted, order.Accepted]:
|
|
|
437 |
self.cerebro.broker.setcommission(commission=commission)
|
438 |
print(f'\nStarting Portfolio Value: {self.cerebro.broker.getvalue():.2f}')
|
439 |
self.cerebro.run()
|
440 |
+
|
441 |
+
# Coletar logs de todas as estratégias
|
442 |
+
operation_logs = []
|
443 |
+
for strategy in self.cerebro.runstrats:
|
444 |
+
operation_logs.extend(strategy[0].operation_logs)
|
445 |
+
|
446 |
print(f'Final Portfolio Value: {self.cerebro.broker.getvalue():.2f}')
|
447 |
+
return self.cerebro.broker.getvalue(), operation_logs # Retorna ambos valores
|
448 |
|
449 |
class CustomStrategy(bt.Strategy):
|
450 |
params = (
|
|
|
465 |
|
466 |
def __init__(self):
|
467 |
# Parâmetros agora são acessados via self.params
|
468 |
+
self.operation_logs = [] # Lista para armazenar os logs
|
469 |
self.recommendation = self.params.analysis['recommendation'] if self.params.analysis else 'HOLD'
|
470 |
self.technical_analysis = self.params.analysis['technical'] if self.params.analysis else None
|
471 |
self.sentiment_analysis = self.params.analysis['sentiment'] if self.params.analysis else None
|
|
|
506 |
|
507 |
def log(self, txt, dt=None):
|
508 |
dt = dt or self.datas[0].datetime.date(0)
|
509 |
+
log_entry = f'{dt.isoformat()}, {txt}'
|
510 |
+
self.operation_logs.append(log_entry) # Armazena na lista
|
511 |
+
print(log_entry) # Mantém o print original
|
512 |
|
513 |
def notify_order(self, order):
|
514 |
if order.status in [order.Submitted, order.Accepted]:
|