Amós e Souza Fernandes
commited on
Upload 147 files
Browse files- agents/__pycache__/DeepPortfolioAgent.cpython-312.pyc +0 -0
- agents/__pycache__/__init__.cpython-312.pyc +0 -0
- agents/__pycache__/custom_policies.cpython-312.pyc +0 -0
- agents/__pycache__/data_handler_multi_asset.cpython-312.pyc +0 -0
- agents/__pycache__/deep_portfolio.cpython-312.pyc +0 -0
- agents/__pycache__/deep_portfolio_torch.cpython-312.pyc +0 -0
- agents/__pycache__/portfolio_environment.cpython-312.pyc +0 -0
- agents/__pycache__/portfolio_features_extractor_torch.cpython-312.pyc +0 -0
- agents/__pycache__/train_rl_portfolio_agent.cpython-312.pyc +0 -0
- agents/__pycache__/train_rl_portfolio_agent_from_app.cpython-312.pyc +0 -0
- agents/config.py +2 -2
- agents/custom_policies.py +1 -1
- agents/portfolio_environment.py +1 -1
- agents/portfolio_features_extractor_torch.py +1 -1
- agents/ppo_deep_portfolio_tensorboard/PPO_10/events.out.tfevents.1750497081.codespaces-72cb68.2589.0 +3 -0
- agents/ppo_deep_portfolio_tensorboard/PPO_11/events.out.tfevents.1750534135.codespaces-72cb68.3018.0 +3 -0
- agents/ppo_deep_portfolio_tensorboard/PPO_12/events.out.tfevents.1750560310.codespaces-72cb68.253920.0 +3 -0
- agents/ppo_deep_portfolio_tensorboard/PPO_13/events.out.tfevents.1750568153.codespaces-72cb68.2534.0 +3 -0
- agents/ppo_deep_portfolio_tensorboard/PPO_14/events.out.tfevents.1750587177.verticalagent-X555LPB.125274.0 +3 -0
- agents/ppo_deep_portfolio_tensorboard/PPO_15/events.out.tfevents.1750636729.verticalagent-X555LPB.266088.0 +3 -0
- agents/ppo_deep_portfolio_tensorboard/PPO_16/events.out.tfevents.1750638335.verticalagent-X555LPB.270772.0 +3 -0
- agents/ppo_deep_portfolio_tensorboard/PPO_17/events.out.tfevents.1750638480.verticalagent-X555LPB.271132.0 +3 -0
- agents/ppo_deep_portfolio_tensorboard/PPO_18/events.out.tfevents.1750639418.verticalagent-X555LPB.273960.0 +3 -0
- agents/ppo_deep_portfolio_tensorboard/PPO_19/events.out.tfevents.1750642515.verticalagent-X555LPB.284046.0 +3 -0
- agents/ppo_deep_portfolio_tensorboard/PPO_4/events.out.tfevents.1750432903.verticalagent-X555LPB.48747.0 +3 -0
- agents/ppo_deep_portfolio_tensorboard/PPO_5/events.out.tfevents.1750410414.codespaces-72cb68.3578.0 +2 -2
- agents/ppo_deep_portfolio_tensorboard/PPO_6/events.out.tfevents.1750420189.codespaces-72cb68.98042.0 +3 -0
- agents/ppo_deep_portfolio_tensorboard/PPO_7/events.out.tfevents.1750426315.codespaces-72cb68.6534.0 +3 -0
- agents/ppo_deep_portfolio_tensorboard/PPO_8/events.out.tfevents.1750432976.codespaces-72cb68.3219.0 +3 -0
- agents/ppo_deep_portfolio_tensorboard/PPO_9/events.out.tfevents.1750459752.codespaces-72cb68.259038.0 +3 -0
- agents/requirements.txt +1 -1
- agents/rl_agent.py +1 -1
- agents/train_rl_portfolio_agent.py +2 -2
- agents/train_rl_portfolio_agent_from_app.py +763 -0
- app.py +751 -751
- graficos_tese/figura_1.png +0 -0
- graficos_tese/figura_2.png +0 -0
- graficos_tese/figura_3.png +0 -0
- graficos_tese/figura_3_1.png +0 -0
- graficos_tese/figura_4.png +0 -0
- ppo_deep_portfolio_tensorboard/PPO_1/events.out.tfevents.1750765461.verticalagent-X555LPB.73418.0 +3 -0
- scripts/gerador_de_grafico.py +139 -0
- scripts/train_rl_portfolio_agent.py +1 -1
agents/__pycache__/DeepPortfolioAgent.cpython-312.pyc
CHANGED
|
Binary files a/agents/__pycache__/DeepPortfolioAgent.cpython-312.pyc and b/agents/__pycache__/DeepPortfolioAgent.cpython-312.pyc differ
|
|
|
agents/__pycache__/__init__.cpython-312.pyc
CHANGED
|
Binary files a/agents/__pycache__/__init__.cpython-312.pyc and b/agents/__pycache__/__init__.cpython-312.pyc differ
|
|
|
agents/__pycache__/custom_policies.cpython-312.pyc
CHANGED
|
Binary files a/agents/__pycache__/custom_policies.cpython-312.pyc and b/agents/__pycache__/custom_policies.cpython-312.pyc differ
|
|
|
agents/__pycache__/data_handler_multi_asset.cpython-312.pyc
CHANGED
|
Binary files a/agents/__pycache__/data_handler_multi_asset.cpython-312.pyc and b/agents/__pycache__/data_handler_multi_asset.cpython-312.pyc differ
|
|
|
agents/__pycache__/deep_portfolio.cpython-312.pyc
CHANGED
|
Binary files a/agents/__pycache__/deep_portfolio.cpython-312.pyc and b/agents/__pycache__/deep_portfolio.cpython-312.pyc differ
|
|
|
agents/__pycache__/deep_portfolio_torch.cpython-312.pyc
CHANGED
|
Binary files a/agents/__pycache__/deep_portfolio_torch.cpython-312.pyc and b/agents/__pycache__/deep_portfolio_torch.cpython-312.pyc differ
|
|
|
agents/__pycache__/portfolio_environment.cpython-312.pyc
CHANGED
|
Binary files a/agents/__pycache__/portfolio_environment.cpython-312.pyc and b/agents/__pycache__/portfolio_environment.cpython-312.pyc differ
|
|
|
agents/__pycache__/portfolio_features_extractor_torch.cpython-312.pyc
CHANGED
|
Binary files a/agents/__pycache__/portfolio_features_extractor_torch.cpython-312.pyc and b/agents/__pycache__/portfolio_features_extractor_torch.cpython-312.pyc differ
|
|
|
agents/__pycache__/train_rl_portfolio_agent.cpython-312.pyc
CHANGED
|
Binary files a/agents/__pycache__/train_rl_portfolio_agent.cpython-312.pyc and b/agents/__pycache__/train_rl_portfolio_agent.cpython-312.pyc differ
|
|
|
agents/__pycache__/train_rl_portfolio_agent_from_app.cpython-312.pyc
ADDED
|
Binary file (16.2 kB). View file
|
|
|
agents/config.py
CHANGED
|
@@ -101,8 +101,8 @@ LEARNING_RATE=0.0005
|
|
| 101 |
PPO_LEARNING_RATE = 0.0003 # Padrão do SB3 PPO, pode ajustar
|
| 102 |
PPO_N_STEPS = 2048
|
| 103 |
PPO_BATCH_SIZE_RL = 64 # Mini-batch size do PPO
|
| 104 |
-
PPO_ENT_COEF = 0.
|
| 105 |
-
PPO_TOTAL_TIMESTEPS = 1000000 # Comece com menos para teste (ex: 50k-100k)
|
| 106 |
|
| 107 |
# --- Parâmetros do Ambiente RL ---
|
| 108 |
# RISK_FREE_RATE_ANNUAL = 0.02 # Taxa livre de risco anual (ex: 2%)
|
|
|
|
| 101 |
PPO_LEARNING_RATE = 0.0003 # Padrão do SB3 PPO, pode ajustar
|
| 102 |
PPO_N_STEPS = 2048
|
| 103 |
PPO_BATCH_SIZE_RL = 64 # Mini-batch size do PPO
|
| 104 |
+
PPO_ENT_COEF = 0.0
|
| 105 |
+
PPO_TOTAL_TIMESTEPS = 2048 #1000000 # Comece com menos para teste (ex: 50k-100k)
|
| 106 |
|
| 107 |
# --- Parâmetros do Ambiente RL ---
|
| 108 |
# RISK_FREE_RATE_ANNUAL = 0.02 # Taxa livre de risco anual (ex: 2%)
|
agents/custom_policies.py
CHANGED
|
@@ -39,7 +39,7 @@ from stable_baselines3.common.policies import ActorCriticPolicy
|
|
| 39 |
from typing import List, Dict, Any, Optional, Union, Type
|
| 40 |
# Importar sua rede e configs
|
| 41 |
#import agents.DeepPortfolioAgent as DeepPortfolioAgent
|
| 42 |
-
from portfolio_features_extractor_torch import PortfolioFeaturesExtractorTorch
|
| 43 |
# from ..config import (NUM_ASSETS, WINDOW_SIZE, NUM_FEATURES_PER_ASSET, ...) # Importe do seu config real
|
| 44 |
# VALORES DE EXEMPLO (PEGUE DO SEU CONFIG.PY REAL)
|
| 45 |
NUM_ASSETS_POLICY = 4
|
|
|
|
| 39 |
from typing import List, Dict, Any, Optional, Union, Type
|
| 40 |
# Importar sua rede e configs
|
| 41 |
#import agents.DeepPortfolioAgent as DeepPortfolioAgent
|
| 42 |
+
from agents.portfolio_features_extractor_torch import PortfolioFeaturesExtractorTorch
|
| 43 |
# from ..config import (NUM_ASSETS, WINDOW_SIZE, NUM_FEATURES_PER_ASSET, ...) # Importe do seu config real
|
| 44 |
# VALORES DE EXEMPLO (PEGUE DO SEU CONFIG.PY REAL)
|
| 45 |
NUM_ASSETS_POLICY = 4
|
agents/portfolio_environment.py
CHANGED
|
@@ -28,7 +28,7 @@ class PortfolioEnv(gym.Env): # Renomeado para seguir convenção de Gymnasium (O
|
|
| 28 |
initial_balance=100000,
|
| 29 |
window_size=WINDOW_SIZE_ENV,
|
| 30 |
transaction_cost_pct=0.001,
|
| 31 |
-
reward_window_size=
|
| 32 |
risk_free_rate_per_step=None): # Custo de transação de 0.1%
|
| 33 |
super(PortfolioEnv, self).__init__()
|
| 34 |
|
|
|
|
| 28 |
initial_balance=100000,
|
| 29 |
window_size=WINDOW_SIZE_ENV,
|
| 30 |
transaction_cost_pct=0.001,
|
| 31 |
+
reward_window_size=240, # Janela para cálculo do Sharpe Ratio (ex: 60 passos/horas)
|
| 32 |
risk_free_rate_per_step=None): # Custo de transação de 0.1%
|
| 33 |
super(PortfolioEnv, self).__init__()
|
| 34 |
|
agents/portfolio_features_extractor_torch.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
import torch
|
| 2 |
import torch.nn as nn
|
| 3 |
from stable_baselines3.common.torch_layers import BaseFeaturesExtractor
|
| 4 |
-
from deep_portfolio_torch import DeepPortfolioAgentNetworkTorch
|
| 5 |
|
| 6 |
class PortfolioFeaturesExtractorTorch(BaseFeaturesExtractor):
|
| 7 |
def __init__(self, observation_space, features_dim=32,
|
|
|
|
| 1 |
import torch
|
| 2 |
import torch.nn as nn
|
| 3 |
from stable_baselines3.common.torch_layers import BaseFeaturesExtractor
|
| 4 |
+
from agents.deep_portfolio_torch import DeepPortfolioAgentNetworkTorch
|
| 5 |
|
| 6 |
class PortfolioFeaturesExtractorTorch(BaseFeaturesExtractor):
|
| 7 |
def __init__(self, observation_space, features_dim=32,
|
agents/ppo_deep_portfolio_tensorboard/PPO_10/events.out.tfevents.1750497081.codespaces-72cb68.2589.0
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6ea8284249717efcc6b46e7957eef6b8ceff0c6d92487095fdbe12f141125074
|
| 3 |
+
size 254591
|
agents/ppo_deep_portfolio_tensorboard/PPO_11/events.out.tfevents.1750534135.codespaces-72cb68.3018.0
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8c4af51ef094dc62cefc525b73b30f2f35ea2a3572dc386c6653c97511d71d8f
|
| 3 |
+
size 255329
|
agents/ppo_deep_portfolio_tensorboard/PPO_12/events.out.tfevents.1750560310.codespaces-72cb68.253920.0
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:37b09133c93eec65e524f5a76873048d399c6dab52f5516f1a01e4c6df736f2a
|
| 3 |
+
size 14741
|
agents/ppo_deep_portfolio_tensorboard/PPO_13/events.out.tfevents.1750568153.codespaces-72cb68.2534.0
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:790362af681bc65a145098768cb0d33b0537524b368420f92f1902de8c559e1b
|
| 3 |
+
size 177101
|
agents/ppo_deep_portfolio_tensorboard/PPO_14/events.out.tfevents.1750587177.verticalagent-X555LPB.125274.0
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5a125c886db6fb22c394b8fc76d1ac2c99ed0fe68ba5713a69e4fea0551c5c35
|
| 3 |
+
size 36143
|
agents/ppo_deep_portfolio_tensorboard/PPO_15/events.out.tfevents.1750636729.verticalagent-X555LPB.266088.0
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ed84c8ebfc3274f6f2d0dff3f5f7278f4aca81954e7f45121a0180504654e164
|
| 3 |
+
size 135
|
agents/ppo_deep_portfolio_tensorboard/PPO_16/events.out.tfevents.1750638335.verticalagent-X555LPB.270772.0
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:68d42ca276a5b5bc587bd082ac51200daca54a62ba8a75af0bcd916712f4ebf4
|
| 3 |
+
size 88
|
agents/ppo_deep_portfolio_tensorboard/PPO_17/events.out.tfevents.1750638480.verticalagent-X555LPB.271132.0
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e42d9077440ade5a761b7142c9645030018a476581f6e1701f809afe490c58ac
|
| 3 |
+
size 135
|
agents/ppo_deep_portfolio_tensorboard/PPO_18/events.out.tfevents.1750639418.verticalagent-X555LPB.273960.0
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:811fff7b41423665bb07a8490f6d6c8eb4cba229a7f40de47eb2e51fba4e35a3
|
| 3 |
+
size 1353
|
agents/ppo_deep_portfolio_tensorboard/PPO_19/events.out.tfevents.1750642515.verticalagent-X555LPB.284046.0
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:41a733e48ed3b1b43aff5d822a5446021f1c7cbb8a3623c7f52ed5922cf56ba5
|
| 3 |
+
size 6623
|
agents/ppo_deep_portfolio_tensorboard/PPO_4/events.out.tfevents.1750432903.verticalagent-X555LPB.48747.0
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bac721e2582379367b5c5d34d2c4701faa4acd5e7636209da9d24e159745dce7
|
| 3 |
+
size 4409
|
agents/ppo_deep_portfolio_tensorboard/PPO_5/events.out.tfevents.1750410414.codespaces-72cb68.3578.0
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f2be104d088941c9ada02fc21bc986f601b40ccedb0ef248d24b693691e0d112
|
| 3 |
+
size 75995
|
agents/ppo_deep_portfolio_tensorboard/PPO_6/events.out.tfevents.1750420189.codespaces-72cb68.98042.0
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4bf0bafaf0ed17d2ecfbf48d6e7f5373463e0f80d31d2073815c9e2f01bd0d7d
|
| 3 |
+
size 3789
|
agents/ppo_deep_portfolio_tensorboard/PPO_7/events.out.tfevents.1750426315.codespaces-72cb68.6534.0
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b47ae9addc8cf7c11c10ffb947882b6ecfccb18e81edc411914e69befbdad729
|
| 3 |
+
size 8837
|
agents/ppo_deep_portfolio_tensorboard/PPO_8/events.out.tfevents.1750432976.codespaces-72cb68.3219.0
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0bd83f315568a2b8f49e639649430e8b1ab42914debb7d427bd0e53d26fcc2fd
|
| 3 |
+
size 165293
|
agents/ppo_deep_portfolio_tensorboard/PPO_9/events.out.tfevents.1750459752.codespaces-72cb68.259038.0
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f12a32b38018d82fb198d90d7f18f1eb5c6ca5ead634f29032fe9cfb887a69ba
|
| 3 |
+
size 140939
|
agents/requirements.txt
CHANGED
|
@@ -10,7 +10,7 @@ httpx
|
|
| 10 |
pydantic
|
| 11 |
python-dotenv
|
| 12 |
loguru
|
| 13 |
-
# agno @ git+https://github.com/agno-agi/agno.git
|
| 14 |
jinja2
|
| 15 |
yfinance
|
| 16 |
PyJWT
|
|
|
|
| 10 |
pydantic
|
| 11 |
python-dotenv
|
| 12 |
loguru
|
| 13 |
+
# agno @ git+https://github.com/agno-agi/agno.git Obs importante
|
| 14 |
jinja2
|
| 15 |
yfinance
|
| 16 |
PyJWT
|
agents/rl_agent.py
CHANGED
|
@@ -5,5 +5,5 @@ from atcoin_env import TradingEnv # custom env
|
|
| 5 |
def train_rl_model():
|
| 6 |
env = TradingEnv()
|
| 7 |
model = PPO("MlpPolicy", env, verbose=1)
|
| 8 |
-
model.learn(total_timesteps=
|
| 9 |
model.save("models/ppo_trading")
|
|
|
|
| 5 |
def train_rl_model():
|
| 6 |
env = TradingEnv()
|
| 7 |
model = PPO("MlpPolicy", env, verbose=1)
|
| 8 |
+
model.learn(total_timesteps=50000)
|
| 9 |
model.save("models/ppo_trading")
|
agents/train_rl_portfolio_agent.py
CHANGED
|
@@ -635,7 +635,7 @@ print("Ambiente de Portfólio Criado.")
|
|
| 635 |
learning_rate_ppo = PPO_LEARNING_RATE # Ex: 3e-4 ou 1e-4 (do config.py)
|
| 636 |
n_steps_ppo = 2048
|
| 637 |
batch_size_ppo = 64
|
| 638 |
-
ent_coef_ppo = 0.
|
| 639 |
|
| 640 |
# policy_kwargs para passar para o __init__ da CustomPortfolioPolicySB3, se necessário
|
| 641 |
# (além dos que já são passados para o features_extractor_kwargs)
|
|
@@ -659,7 +659,7 @@ model_ppo = PPO(
|
|
| 659 |
)
|
| 660 |
|
| 661 |
print("Iniciando treinamento do agente PPO com rede customizada...")
|
| 662 |
-
model_ppo.learn(total_timesteps=
|
| 663 |
|
| 664 |
model_ppo.save("app/model/ppo_custom_deep_portfolio_agent")
|
| 665 |
print("Modelo RL com política customizada treinado e salvo.")
|
|
|
|
| 635 |
learning_rate_ppo = PPO_LEARNING_RATE # Ex: 3e-4 ou 1e-4 (do config.py)
|
| 636 |
n_steps_ppo = 2048
|
| 637 |
batch_size_ppo = 64
|
| 638 |
+
ent_coef_ppo = 0.0
|
| 639 |
|
| 640 |
# policy_kwargs para passar para o __init__ da CustomPortfolioPolicySB3, se necessário
|
| 641 |
# (além dos que já são passados para o features_extractor_kwargs)
|
|
|
|
| 659 |
)
|
| 660 |
|
| 661 |
print("Iniciando treinamento do agente PPO com rede customizada...")
|
| 662 |
+
model_ppo.learn(total_timesteps=100000, progress_bar=True) # Comece com menos timesteps para teste (ex: 50k)
|
| 663 |
|
| 664 |
model_ppo.save("app/model/ppo_custom_deep_portfolio_agent")
|
| 665 |
print("Modelo RL com política customizada treinado e salvo.")
|
agents/train_rl_portfolio_agent_from_app.py
ADDED
|
@@ -0,0 +1,763 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# train_rl_portfolio_agent.py
|
| 2 |
+
from stable_baselines3 import PPO
|
| 3 |
+
from stable_baselines3.common.env_checker import check_env
|
| 4 |
+
#from transformers import logger
|
| 5 |
+
|
| 6 |
+
# rnn/agents/custom_policies.py (NOVO ARQUIVO, ou adicione ao deep_portfolio.py)
|
| 7 |
+
|
| 8 |
+
import gymnasium as gym # Usar gymnasium
|
| 9 |
+
import tensorflow as tf
|
| 10 |
+
from stable_baselines3.common.torch_layers import BaseFeaturesExtractor as PyTorchBaseFeaturesExtractor
|
| 11 |
+
|
| 12 |
+
from stable_baselines3.common.torch_layers import MlpExtractor
|
| 13 |
+
import torch.nn as nn
|
| 14 |
+
|
| 15 |
+
class CustomMlpExtractor(MlpExtractor):
|
| 16 |
+
def __init__(self, input_dim, net_arch, activation_fn, device):
|
| 17 |
+
super().__init__(input_dim, net_arch, activation_fn, device)
|
| 18 |
+
|
| 19 |
+
def forward(self, features):
|
| 20 |
+
for layer in self.policy_net:
|
| 21 |
+
if isinstance(layer, nn.ReLU):
|
| 22 |
+
features = layer(features) # Passando 'features' como argumento
|
| 23 |
+
else:
|
| 24 |
+
features = layer(features)
|
| 25 |
+
return features
|
| 26 |
+
# Para TensorFlow, precisamos de um extrator de features compatível ou construir a política de forma diferente.
|
| 27 |
+
# Stable Baselines3 tem melhor suporte nativo para PyTorch. Para TF, é um pouco mais manual.
|
| 28 |
+
# VAMOS USAR A ABORDAGEM DE POLÍTICA CUSTOMIZADA COM TF DIRETAMENTE.
|
| 29 |
+
from stable_baselines3.common.policies import ActorCriticPolicy
|
| 30 |
+
from typing import List, Dict, Any, Optional, Union, Type
|
| 31 |
+
# Importar sua rede e configs
|
| 32 |
+
#import agents.DeepPortfolioAgent as DeepPortfolioAgent
|
| 33 |
+
from agents.DeepPortfolioAgent import DeepPortfolioAgentNetwork
|
| 34 |
+
# from ..config import (NUM_ASSETS, WINDOW_SIZE, NUM_FEATURES_PER_ASSET, ...) # Importe do seu config real
|
| 35 |
+
# VALORES DE EXEMPLO (PEGUE DO SEU CONFIG.PY REAL)
|
| 36 |
+
NUM_ASSETS_POLICY = 4
|
| 37 |
+
WINDOW_SIZE_POLICY = 60
|
| 38 |
+
NUM_FEATURES_PER_ASSET_POLICY = 26
|
| 39 |
+
# Hiperparâmetros para DeepPortfolioAgentNetwork quando usada como extrator
|
| 40 |
+
ASSET_CNN_FILTERS1_POLICY = 32
|
| 41 |
+
ASSET_CNN_FILTERS2_POLICY = 64
|
| 42 |
+
ASSET_LSTM_UNITS1_POLICY = 64
|
| 43 |
+
ASSET_LSTM_UNITS2_POLICY = 32 # Esta será a dimensão das features latentes para ator/crítico
|
| 44 |
+
ASSET_DROPOUT_POLICY = 0.2
|
| 45 |
+
MHA_NUM_HEADS_POLICY = 4
|
| 46 |
+
MHA_KEY_DIM_DIVISOR_POLICY = 2 # Para key_dim = 32 // 2 = 16
|
| 47 |
+
FINAL_DENSE_UNITS1_POLICY = 128
|
| 48 |
+
FINAL_DENSE_UNITS2_POLICY = ASSET_LSTM_UNITS2_POLICY # A saída da dense2 SÃO as features latentes
|
| 49 |
+
FINAL_DROPOUT_POLICY = 0.3
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class TFPortfolioFeaturesExtractor(tf.keras.layers.Layer): # Herda de tf.keras.layers.Layer
|
| 53 |
+
"""
|
| 54 |
+
Extrator de features customizado para SB3 que usa DeepPortfolioAgentNetwork.
|
| 55 |
+
A observação do ambiente é (batch, window, num_assets * num_features_per_asset).
|
| 56 |
+
A saída são as features latentes (batch, latent_dim).
|
| 57 |
+
"""
|
| 58 |
+
def __init__(self, observation_space: gym.spaces.Box, features_dim: int = ASSET_LSTM_UNITS2_POLICY):
|
| 59 |
+
super(TFPortfolioFeaturesExtractor, self).__init__()
|
| 60 |
+
self.features_dim = features_dim # SB3 usa isso para saber o tamanho da saída
|
| 61 |
+
|
| 62 |
+
# Instanciar a rede base para extrair features
|
| 63 |
+
# Ela deve retornar as ativações ANTES da camada softmax de alocação.
|
| 64 |
+
self.network = DeepPortfolioAgentNetwork(
|
| 65 |
+
num_assets=NUM_ASSETS_POLICY,
|
| 66 |
+
sequence_length=WINDOW_SIZE_POLICY,
|
| 67 |
+
num_features_per_asset=NUM_FEATURES_PER_ASSET_POLICY,
|
| 68 |
+
asset_cnn_filters1=ASSET_CNN_FILTERS1_POLICY,
|
| 69 |
+
asset_cnn_filters2=ASSET_CNN_FILTERS2_POLICY,
|
| 70 |
+
asset_lstm_units1=ASSET_LSTM_UNITS1_POLICY,
|
| 71 |
+
asset_lstm_units2=ASSET_LSTM_UNITS2_POLICY, # Define a saída do asset_processor
|
| 72 |
+
asset_dropout=ASSET_DROPOUT_POLICY,
|
| 73 |
+
mha_num_heads=MHA_NUM_HEADS_POLICY,
|
| 74 |
+
mha_key_dim_divisor=MHA_KEY_DIM_DIVISOR_POLICY,
|
| 75 |
+
final_dense_units1=FINAL_DENSE_UNITS1_POLICY,
|
| 76 |
+
final_dense_units2=self.features_dim, # A saída da dense2 é a nossa feature latente
|
| 77 |
+
final_dropout=FINAL_DROPOUT_POLICY,
|
| 78 |
+
output_latent_features=True,
|
| 79 |
+
use_sentiment_analysis=True # MUITO IMPORTANTE!
|
| 80 |
+
)
|
| 81 |
+
print("TFPortfolioFeaturesExtractor inicializado e usando DeepPortfolioAgentNetwork (output_latent_features=True).")
|
| 82 |
+
|
| 83 |
+
def call(self, observations: tf.Tensor, training: bool = False) -> tf.Tensor:
|
| 84 |
+
# A DeepPortfolioAgentNetwork já lida com o fatiamento e processamento.
|
| 85 |
+
# Ela foi configurada para retornar features latentes.
|
| 86 |
+
return self.network(observations, training=training)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class CustomPolicy(ActorCriticPolicy):
|
| 90 |
+
def __init__(self, *args, **kwargs):
|
| 91 |
+
super().__init__(*args, **kwargs)
|
| 92 |
+
self.mlp_extractor = CustomMlpExtractor(
|
| 93 |
+
input_dim=self.observation_space.shape[0],
|
| 94 |
+
net_arch=[64, 64], # Exemplo de arquitetura
|
| 95 |
+
activation_fn=nn.ReLU,
|
| 96 |
+
device=self.device
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class CustomPortfolioPolicySB3(ActorCriticPolicy):
|
| 102 |
+
def __init__(
|
| 103 |
+
self,
|
| 104 |
+
observation_space: gym.spaces.Space,
|
| 105 |
+
action_space: gym.spaces.Space,
|
| 106 |
+
lr_schedule, # Função que retorna a taxa de aprendizado
|
| 107 |
+
net_arch: Optional[List[Union[int, Dict[str, List[int]]]]] = None, # Arquitetura para MLPs pós-extrator
|
| 108 |
+
activation_fn: Type[tf.Module] = tf.nn.relu, # Usar tf.nn.relu para TF
|
| 109 |
+
# Adicionar quaisquer outros parâmetros específicos que o extrator precise
|
| 110 |
+
features_extractor_kwargs: Optional[Dict[str, Any]] = None,
|
| 111 |
+
**kwargs,
|
| 112 |
+
):
|
| 113 |
+
if features_extractor_kwargs is None:
|
| 114 |
+
features_extractor_kwargs = {}
|
| 115 |
+
|
| 116 |
+
# A dimensão das features que o nosso extrator PortfolioFeatureExtractor vai cuspir.
|
| 117 |
+
# Deve ser igual a ASSET_LSTM_UNITS2_POLICY (ou final_dense_units2 do extrator)
|
| 118 |
+
# Se não for passado, o construtor do ActorCriticPolicy pode tentar inferir.
|
| 119 |
+
# Vamos passar explicitamente para garantir.
|
| 120 |
+
features_extractor_kwargs.setdefault("features_dim", ASSET_LSTM_UNITS2_POLICY) # Ou o valor que você definiu
|
| 121 |
+
|
| 122 |
+
super().__init__(
|
| 123 |
+
observation_space,
|
| 124 |
+
action_space,
|
| 125 |
+
lr_schedule,
|
| 126 |
+
net_arch=net_arch, # Para camadas Dense APÓS o extrator de features
|
| 127 |
+
activation_fn=activation_fn,
|
| 128 |
+
features_extractor_class=TFPortfolioFeaturesExtractor,
|
| 129 |
+
features_extractor_kwargs=features_extractor_kwargs,
|
| 130 |
+
**kwargs,
|
| 131 |
+
)
|
| 132 |
+
# Otimizador é criado na classe base.
|
| 133 |
+
# As redes de ator e crítico são construídas no método _build da classe base,
|
| 134 |
+
# usando o self.features_extractor e depois o self.mlp_extractor (que é
|
| 135 |
+
# construído com base no net_arch).
|
| 136 |
+
|
| 137 |
+
# Não precisamos sobrescrever _build_mlp_extractor se o features_extractor
|
| 138 |
+
# já fizer o trabalho pesado e o net_arch padrão para as cabeças for suficiente.
|
| 139 |
+
# Se quisermos MLPs customizados para ator e crítico APÓS o extrator:
|
| 140 |
+
# def _build_mlp_extractor(self) -> None:
|
| 141 |
+
# # self.mlp_extractor é uma instância de MlpExtractor (ou similar)
|
| 142 |
+
# # A entrada para ele é self.features_extractor.features_dim
|
| 143 |
+
# # Aqui, net_arch definiria a estrutura do mlp_extractor
|
| 144 |
+
# self.mlp_extractor = MlpExtractor(
|
| 145 |
+
# feature_dim=self.features_extractor.features_dim,
|
| 146 |
+
# net_arch=self.net_arch, # net_arch é uma lista de ints para camadas da política e valor
|
| 147 |
+
# activation_fn=self.activation_fn,
|
| 148 |
+
# device=self.device,
|
| 149 |
+
# )
|
| 150 |
+
# As redes de ação e valor (action_net, value_net) são então criadas
|
| 151 |
+
# no _build da classe ActorCriticPolicy, no topo do mlp_extractor.# rnn/agents/custom_policies.py (NOVO ARQUIVO, ou adicione ao deep_portfolio.py)
|
| 152 |
+
|
| 153 |
+
import gymnasium as gym # Usar gymnasium
|
| 154 |
+
import tensorflow as tf
|
| 155 |
+
from stable_baselines3.common.torch_layers import BaseFeaturesExtractor as PyTorchBaseFeaturesExtractor
|
| 156 |
+
|
| 157 |
+
from stable_baselines3.common.torch_layers import MlpExtractor
|
| 158 |
+
import torch.nn as nn
|
| 159 |
+
|
| 160 |
+
class CustomMlpExtractor(MlpExtractor):
|
| 161 |
+
def __init__(self, input_dim, net_arch, activation_fn, device):
|
| 162 |
+
super().__init__(input_dim, net_arch, activation_fn, device)
|
| 163 |
+
|
| 164 |
+
def forward(self, features):
|
| 165 |
+
for layer in self.policy_net:
|
| 166 |
+
if isinstance(layer, nn.ReLU):
|
| 167 |
+
features = layer(features) # Passando 'features' como argumento
|
| 168 |
+
else:
|
| 169 |
+
features = layer(features)
|
| 170 |
+
return features
|
| 171 |
+
# Para TensorFlow, precisamos de um extrator de features compatível ou construir a política de forma diferente.
|
| 172 |
+
# Stable Baselines3 tem melhor suporte nativo para PyTorch. Para TF, é um pouco mais manual.
|
| 173 |
+
# VAMOS USAR A ABORDAGEM DE POLÍTICA CUSTOMIZADA COM TF DIRETAMENTE.
|
| 174 |
+
from stable_baselines3.common.policies import ActorCriticPolicy
|
| 175 |
+
from typing import List, Dict, Any, Optional, Union, Type
|
| 176 |
+
# Importar sua rede e configs
|
| 177 |
+
#import agents.DeepPortfolioAgent as DeepPortfolioAgent
|
| 178 |
+
from agents.DeepPortfolioAgent import DeepPortfolioAgentNetwork
|
| 179 |
+
# from ..config import (NUM_ASSETS, WINDOW_SIZE, NUM_FEATURES_PER_ASSET, ...) # Importe do seu config real
|
| 180 |
+
# VALORES DE EXEMPLO (PEGUE DO SEU CONFIG.PY REAL)
|
| 181 |
+
NUM_ASSETS_POLICY = 4
|
| 182 |
+
WINDOW_SIZE_POLICY = 60
|
| 183 |
+
NUM_FEATURES_PER_ASSET_POLICY = 26
|
| 184 |
+
# Hiperparâmetros para DeepPortfolioAgentNetwork quando usada como extrator
|
| 185 |
+
ASSET_CNN_FILTERS1_POLICY = 32
|
| 186 |
+
ASSET_CNN_FILTERS2_POLICY = 64
|
| 187 |
+
ASSET_LSTM_UNITS1_POLICY = 64
|
| 188 |
+
ASSET_LSTM_UNITS2_POLICY = 32 # Esta será a dimensão das features latentes para ator/crítico
|
| 189 |
+
ASSET_DROPOUT_POLICY = 0.2
|
| 190 |
+
MHA_NUM_HEADS_POLICY = 4
|
| 191 |
+
MHA_KEY_DIM_DIVISOR_POLICY = 2 # Para key_dim = 32 // 2 = 16
|
| 192 |
+
FINAL_DENSE_UNITS1_POLICY = 128
|
| 193 |
+
FINAL_DENSE_UNITS2_POLICY = ASSET_LSTM_UNITS2_POLICY # A saída da dense2 SÃO as features latentes
|
| 194 |
+
FINAL_DROPOUT_POLICY = 0.3
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
class TFPortfolioFeaturesExtractor(tf.keras.layers.Layer): # Herda de tf.keras.layers.Layer
|
| 198 |
+
"""
|
| 199 |
+
Extrator de features customizado para SB3 que usa DeepPortfolioAgentNetwork.
|
| 200 |
+
A observação do ambiente é (batch, window, num_assets * num_features_per_asset).
|
| 201 |
+
A saída são as features latentes (batch, latent_dim).
|
| 202 |
+
"""
|
| 203 |
+
def __init__(self, observation_space: gym.spaces.Box, features_dim: int = ASSET_LSTM_UNITS2_POLICY):
|
| 204 |
+
super(TFPortfolioFeaturesExtractor, self).__init__()
|
| 205 |
+
self.features_dim = features_dim # SB3 usa isso para saber o tamanho da saída
|
| 206 |
+
|
| 207 |
+
# Instanciar a rede base para extrair features
|
| 208 |
+
# Ela deve retornar as ativações ANTES da camada softmax de alocação.
|
| 209 |
+
self.network = DeepPortfolioAgentNetwork(
|
| 210 |
+
num_assets=NUM_ASSETS_POLICY,
|
| 211 |
+
sequence_length=WINDOW_SIZE_POLICY,
|
| 212 |
+
num_features_per_asset=NUM_FEATURES_PER_ASSET_POLICY,
|
| 213 |
+
asset_cnn_filters1=ASSET_CNN_FILTERS1_POLICY,
|
| 214 |
+
asset_cnn_filters2=ASSET_CNN_FILTERS2_POLICY,
|
| 215 |
+
asset_lstm_units1=ASSET_LSTM_UNITS1_POLICY,
|
| 216 |
+
asset_lstm_units2=ASSET_LSTM_UNITS2_POLICY, # Define a saída do asset_processor
|
| 217 |
+
asset_dropout=ASSET_DROPOUT_POLICY,
|
| 218 |
+
mha_num_heads=MHA_NUM_HEADS_POLICY,
|
| 219 |
+
mha_key_dim_divisor=MHA_KEY_DIM_DIVISOR_POLICY,
|
| 220 |
+
final_dense_units1=FINAL_DENSE_UNITS1_POLICY,
|
| 221 |
+
final_dense_units2=self.features_dim, # A saída da dense2 é a nossa feature latente
|
| 222 |
+
final_dropout=FINAL_DROPOUT_POLICY,
|
| 223 |
+
output_latent_features=True,
|
| 224 |
+
use_sentiment_analysis=True # MUITO IMPORTANTE!
|
| 225 |
+
)
|
| 226 |
+
print("TFPortfolioFeaturesExtractor inicializado e usando DeepPortfolioAgentNetwork (output_latent_features=True).")
|
| 227 |
+
|
| 228 |
+
def call(self, observations: tf.Tensor, training: bool = False) -> tf.Tensor:
|
| 229 |
+
# A DeepPortfolioAgentNetwork já lida com o fatiamento e processamento.
|
| 230 |
+
# Ela foi configurada para retornar features latentes.
|
| 231 |
+
return self.network(observations, training=training)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
class CustomPolicy(ActorCriticPolicy):
|
| 235 |
+
def __init__(self, *args, **kwargs):
|
| 236 |
+
super().__init__(*args, **kwargs)
|
| 237 |
+
self.mlp_extractor = CustomMlpExtractor(
|
| 238 |
+
input_dim=self.observation_space.shape[0],
|
| 239 |
+
net_arch=[64, 64], # Exemplo de arquitetura
|
| 240 |
+
activation_fn=nn.ReLU,
|
| 241 |
+
device=self.device
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
class CustomPortfolioPolicySB3(ActorCriticPolicy):
|
| 247 |
+
def __init__(
|
| 248 |
+
self,
|
| 249 |
+
observation_space: gym.spaces.Space,
|
| 250 |
+
action_space: gym.spaces.Space,
|
| 251 |
+
lr_schedule, # Função que retorna a taxa de aprendizado
|
| 252 |
+
net_arch: Optional[List[Union[int, Dict[str, List[int]]]]] = None, # Arquitetura para MLPs pós-extrator
|
| 253 |
+
activation_fn: Type[tf.Module] = tf.nn.relu, # Usar tf.nn.relu para TF
|
| 254 |
+
# Adicionar quaisquer outros parâmetros específicos que o extrator precise
|
| 255 |
+
features_extractor_kwargs: Optional[Dict[str, Any]] = None,
|
| 256 |
+
**kwargs,
|
| 257 |
+
):
|
| 258 |
+
if features_extractor_kwargs is None:
|
| 259 |
+
features_extractor_kwargs = {}
|
| 260 |
+
|
| 261 |
+
# A dimensão das features que o nosso extrator PortfolioFeatureExtractor vai cuspir.
|
| 262 |
+
# Deve ser igual a ASSET_LSTM_UNITS2_POLICY (ou final_dense_units2 do extrator)
|
| 263 |
+
# Se não for passado, o construtor do ActorCriticPolicy pode tentar inferir.
|
| 264 |
+
# Vamos passar explicitamente para garantir.
|
| 265 |
+
features_extractor_kwargs.setdefault("features_dim", ASSET_LSTM_UNITS2_POLICY) # Ou o valor que você definiu
|
| 266 |
+
|
| 267 |
+
super().__init__(
|
| 268 |
+
observation_space,
|
| 269 |
+
action_space,
|
| 270 |
+
lr_schedule,
|
| 271 |
+
net_arch=net_arch, # Para camadas Dense APÓS o extrator de features
|
| 272 |
+
activation_fn=activation_fn,
|
| 273 |
+
features_extractor_class=TFPortfolioFeaturesExtractor,
|
| 274 |
+
features_extractor_kwargs=features_extractor_kwargs,
|
| 275 |
+
**kwargs,
|
| 276 |
+
)
|
| 277 |
+
# Otimizador é criado na classe base.
|
| 278 |
+
# As redes de ator e crítico são construídas no método _build da classe base,
|
| 279 |
+
# usando o self.features_extractor e depois o self.mlp_extractor (que é
|
| 280 |
+
# construído com base no net_arch).
|
| 281 |
+
|
| 282 |
+
# Não precisamos sobrescrever _build_mlp_extractor se o features_extractor
|
| 283 |
+
# já fizer o trabalho pesado e o net_arch padrão para as cabeças for suficiente.
|
| 284 |
+
# Se quisermos MLPs customizados para ator e crítico APÓS o extrator:
|
| 285 |
+
# def _build_mlp_extractor(self) -> None:
|
| 286 |
+
# # self.mlp_extractor é uma instância de MlpExtractor (ou similar)
|
| 287 |
+
# # A entrada para ele é self.features_extractor.features_dim
|
| 288 |
+
# # Aqui, net_arch definiria a estrutura do mlp_extractor
|
| 289 |
+
# self.mlp_extractor = MlpExtractor(
|
| 290 |
+
# feature_dim=self.features_extractor.features_dim,
|
| 291 |
+
# net_arch=self.net_arch, # net_arch é uma lista de ints para camadas da política e valor
|
| 292 |
+
# activation_fn=self.activation_fn,
|
| 293 |
+
# device=self.device,
|
| 294 |
+
# )
|
| 295 |
+
# As redes de ação e valor (action_net, value_net) são então criadas
|
| 296 |
+
# no _build da classe ActorCriticPolicy, no topo do mlp_extractor.# rnn/agents/custom_policies.py (NOVO ARQUIVO, ou adicione ao deep_portfolio.py)
|
| 297 |
+
|
| 298 |
+
import gymnasium as gym # Usar gymnasium
|
| 299 |
+
import tensorflow as tf
|
| 300 |
+
from stable_baselines3.common.torch_layers import BaseFeaturesExtractor as PyTorchBaseFeaturesExtractor
|
| 301 |
+
|
| 302 |
+
from stable_baselines3.common.torch_layers import MlpExtractor
|
| 303 |
+
import torch.nn as nn
|
| 304 |
+
|
| 305 |
+
class CustomMlpExtractor(MlpExtractor):
|
| 306 |
+
def __init__(self, input_dim, net_arch, activation_fn, device):
|
| 307 |
+
super().__init__(input_dim, net_arch, activation_fn, device)
|
| 308 |
+
|
| 309 |
+
def forward(self, features):
|
| 310 |
+
for layer in self.policy_net:
|
| 311 |
+
if isinstance(layer, nn.ReLU):
|
| 312 |
+
features = layer(features) # Passando 'features' como argumento
|
| 313 |
+
else:
|
| 314 |
+
features = layer(features)
|
| 315 |
+
return features
|
| 316 |
+
# Para TensorFlow, precisamos de um extrator de features compatível ou construir a política de forma diferente.
|
| 317 |
+
# Stable Baselines3 tem melhor suporte nativo para PyTorch. Para TF, é um pouco mais manual.
|
| 318 |
+
# VAMOS USAR A ABORDAGEM DE POLÍTICA CUSTOMIZADA COM TF DIRETAMENTE.
|
| 319 |
+
from stable_baselines3.common.policies import ActorCriticPolicy
|
| 320 |
+
from typing import List, Dict, Any, Optional, Union, Type
|
| 321 |
+
# Importar sua rede e configs
|
| 322 |
+
#import agents.DeepPortfolioAgent as DeepPortfolioAgent
|
| 323 |
+
from agents.DeepPortfolioAgent import DeepPortfolioAgentNetwork
|
| 324 |
+
# from ..config import (NUM_ASSETS, WINDOW_SIZE, NUM_FEATURES_PER_ASSET, ...) # Importe do seu config real
|
| 325 |
+
# VALORES DE EXEMPLO (PEGUE DO SEU CONFIG.PY REAL)
|
| 326 |
+
NUM_ASSETS_POLICY = 4
|
| 327 |
+
WINDOW_SIZE_POLICY = 60
|
| 328 |
+
NUM_FEATURES_PER_ASSET_POLICY = 26
|
| 329 |
+
# Hiperparâmetros para DeepPortfolioAgentNetwork quando usada como extrator
|
| 330 |
+
ASSET_CNN_FILTERS1_POLICY = 32
|
| 331 |
+
ASSET_CNN_FILTERS2_POLICY = 64
|
| 332 |
+
ASSET_LSTM_UNITS1_POLICY = 64
|
| 333 |
+
ASSET_LSTM_UNITS2_POLICY = 32 # Esta será a dimensão das features latentes para ator/crítico
|
| 334 |
+
ASSET_DROPOUT_POLICY = 0.2
|
| 335 |
+
MHA_NUM_HEADS_POLICY = 4
|
| 336 |
+
MHA_KEY_DIM_DIVISOR_POLICY = 2 # Para key_dim = 32 // 2 = 16
|
| 337 |
+
FINAL_DENSE_UNITS1_POLICY = 128
|
| 338 |
+
FINAL_DENSE_UNITS2_POLICY = ASSET_LSTM_UNITS2_POLICY # A saída da dense2 SÃO as features latentes
|
| 339 |
+
FINAL_DROPOUT_POLICY = 0.3
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
class TFPortfolioFeaturesExtractor(tf.keras.layers.Layer): # Herda de tf.keras.layers.Layer
|
| 343 |
+
"""
|
| 344 |
+
Extrator de features customizado para SB3 que usa DeepPortfolioAgentNetwork.
|
| 345 |
+
A observação do ambiente é (batch, window, num_assets * num_features_per_asset).
|
| 346 |
+
A saída são as features latentes (batch, latent_dim).
|
| 347 |
+
"""
|
| 348 |
+
def __init__(self, observation_space: gym.spaces.Box, features_dim: int = ASSET_LSTM_UNITS2_POLICY):
|
| 349 |
+
super(TFPortfolioFeaturesExtractor, self).__init__()
|
| 350 |
+
self.features_dim = features_dim # SB3 usa isso para saber o tamanho da saída
|
| 351 |
+
|
| 352 |
+
# Instanciar a rede base para extrair features
|
| 353 |
+
# Ela deve retornar as ativações ANTES da camada softmax de alocação.
|
| 354 |
+
self.network = DeepPortfolioAgentNetwork(
|
| 355 |
+
num_assets=NUM_ASSETS_POLICY,
|
| 356 |
+
sequence_length=WINDOW_SIZE_POLICY,
|
| 357 |
+
num_features_per_asset=NUM_FEATURES_PER_ASSET_POLICY,
|
| 358 |
+
asset_cnn_filters1=ASSET_CNN_FILTERS1_POLICY,
|
| 359 |
+
asset_cnn_filters2=ASSET_CNN_FILTERS2_POLICY,
|
| 360 |
+
asset_lstm_units1=ASSET_LSTM_UNITS1_POLICY,
|
| 361 |
+
asset_lstm_units2=ASSET_LSTM_UNITS2_POLICY, # Define a saída do asset_processor
|
| 362 |
+
asset_dropout=ASSET_DROPOUT_POLICY,
|
| 363 |
+
mha_num_heads=MHA_NUM_HEADS_POLICY,
|
| 364 |
+
mha_key_dim_divisor=MHA_KEY_DIM_DIVISOR_POLICY,
|
| 365 |
+
final_dense_units1=FINAL_DENSE_UNITS1_POLICY,
|
| 366 |
+
final_dense_units2=self.features_dim, # A saída da dense2 é a nossa feature latente
|
| 367 |
+
final_dropout=FINAL_DROPOUT_POLICY,
|
| 368 |
+
output_latent_features=True,
|
| 369 |
+
use_sentiment_analysis=True # MUITO IMPORTANTE!
|
| 370 |
+
)
|
| 371 |
+
print("TFPortfolioFeaturesExtractor inicializado e usando DeepPortfolioAgentNetwork (output_latent_features=True).")
|
| 372 |
+
|
| 373 |
+
def call(self, observations: tf.Tensor, training: bool = False) -> tf.Tensor:
|
| 374 |
+
# A DeepPortfolioAgentNetwork já lida com o fatiamento e processamento.
|
| 375 |
+
# Ela foi configurada para retornar features latentes.
|
| 376 |
+
return self.network(observations, training=training)
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
class CustomPolicy(ActorCriticPolicy):
|
| 380 |
+
def __init__(self, *args, **kwargs):
|
| 381 |
+
super().__init__(*args, **kwargs)
|
| 382 |
+
self.mlp_extractor = CustomMlpExtractor(
|
| 383 |
+
input_dim=self.observation_space.shape[0],
|
| 384 |
+
net_arch=[64, 64], # Exemplo de arquitetura
|
| 385 |
+
activation_fn=nn.ReLU,
|
| 386 |
+
device=self.device
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
class CustomPortfolioPolicySB3(ActorCriticPolicy):
|
| 392 |
+
def __init__(
|
| 393 |
+
self,
|
| 394 |
+
observation_space: gym.spaces.Space,
|
| 395 |
+
action_space: gym.spaces.Space,
|
| 396 |
+
lr_schedule, # Função que retorna a taxa de aprendizado
|
| 397 |
+
net_arch: Optional[List[Union[int, Dict[str, List[int]]]]] = None, # Arquitetura para MLPs pós-extrator
|
| 398 |
+
activation_fn: Type[tf.Module] = tf.nn.relu, # Usar tf.nn.relu para TF
|
| 399 |
+
# Adicionar quaisquer outros parâmetros específicos que o extrator precise
|
| 400 |
+
features_extractor_kwargs: Optional[Dict[str, Any]] = None,
|
| 401 |
+
**kwargs,
|
| 402 |
+
):
|
| 403 |
+
if features_extractor_kwargs is None:
|
| 404 |
+
features_extractor_kwargs = {}
|
| 405 |
+
|
| 406 |
+
# A dimensão das features que o nosso extrator PortfolioFeatureExtractor vai cuspir.
|
| 407 |
+
# Deve ser igual a ASSET_LSTM_UNITS2_POLICY (ou final_dense_units2 do extrator)
|
| 408 |
+
# Se não for passado, o construtor do ActorCriticPolicy pode tentar inferir.
|
| 409 |
+
# Vamos passar explicitamente para garantir.
|
| 410 |
+
features_extractor_kwargs.setdefault("features_dim", ASSET_LSTM_UNITS2_POLICY) # Ou o valor que você definiu
|
| 411 |
+
|
| 412 |
+
super().__init__(
|
| 413 |
+
observation_space,
|
| 414 |
+
action_space,
|
| 415 |
+
lr_schedule,
|
| 416 |
+
net_arch=net_arch, # Para camadas Dense APÓS o extrator de features
|
| 417 |
+
activation_fn=activation_fn,
|
| 418 |
+
features_extractor_class=TFPortfolioFeaturesExtractor,
|
| 419 |
+
features_extractor_kwargs=features_extractor_kwargs,
|
| 420 |
+
**kwargs,
|
| 421 |
+
)
|
| 422 |
+
# Otimizador é criado na classe base.
|
| 423 |
+
# As redes de ator e crítico são construídas no método _build da classe base,
|
| 424 |
+
# usando o self.features_extractor e depois o self.mlp_extractor (que é
|
| 425 |
+
# construído com base no net_arch).
|
| 426 |
+
|
| 427 |
+
# Não precisamos sobrescrever _build_mlp_extractor se o features_extractor
|
| 428 |
+
# já fizer o trabalho pesado e o net_arch padrão para as cabeças for suficiente.
|
| 429 |
+
# Se quisermos MLPs customizados para ator e crítico APÓS o extrator:
|
| 430 |
+
# def _build_mlp_extractor(self) -> None:
|
| 431 |
+
# # self.mlp_extractor é uma instância de MlpExtractor (ou similar)
|
| 432 |
+
# # A entrada para ele é self.features_extractor.features_dim
|
| 433 |
+
# # Aqui, net_arch definiria a estrutura do mlp_extractor
|
| 434 |
+
# self.mlp_extractor = MlpExtractor(
|
| 435 |
+
# feature_dim=self.features_extractor.features_dim,
|
| 436 |
+
# net_arch=self.net_arch, # net_arch é uma lista de ints para camadas da política e valor
|
| 437 |
+
# activation_fn=self.activation_fn,
|
| 438 |
+
# device=self.device,
|
| 439 |
+
# )
|
| 440 |
+
# As redes de ação e valor (action_net, value_net) são então criadas
|
| 441 |
+
# no _build da classe ActorCriticPolicy, no topo do mlp_extractor.# rnn/agents/custom_policies.py (NOVO ARQUIVO, ou adicione ao deep_portfolio.py)
|
| 442 |
+
|
| 443 |
+
import gymnasium as gym # Usar gymnasium
|
| 444 |
+
import tensorflow as tf
|
| 445 |
+
from stable_baselines3.common.torch_layers import BaseFeaturesExtractor as PyTorchBaseFeaturesExtractor
|
| 446 |
+
|
| 447 |
+
from stable_baselines3.common.torch_layers import MlpExtractor
|
| 448 |
+
import torch.nn as nn
|
| 449 |
+
|
| 450 |
+
class CustomMlpExtractor(MlpExtractor):
|
| 451 |
+
def __init__(self, input_dim, net_arch, activation_fn, device):
|
| 452 |
+
super().__init__(input_dim, net_arch, activation_fn, device)
|
| 453 |
+
|
| 454 |
+
def forward(self, features):
|
| 455 |
+
for layer in self.policy_net:
|
| 456 |
+
if isinstance(layer, nn.ReLU):
|
| 457 |
+
features = layer(features) # Passando 'features' como argumento
|
| 458 |
+
else:
|
| 459 |
+
features = layer(features)
|
| 460 |
+
return features
|
| 461 |
+
# Para TensorFlow, precisamos de um extrator de features compatível ou construir a política de forma diferente.
|
| 462 |
+
# Stable Baselines3 tem melhor suporte nativo para PyTorch. Para TF, é um pouco mais manual.
|
| 463 |
+
# VAMOS USAR A ABORDAGEM DE POLÍTICA CUSTOMIZADA COM TF DIRETAMENTE.
|
| 464 |
+
from stable_baselines3.common.policies import ActorCriticPolicy
|
| 465 |
+
from typing import List, Dict, Any, Optional, Union, Type
|
| 466 |
+
# Importar sua rede e configs
|
| 467 |
+
#import agents.DeepPortfolioAgent as DeepPortfolioAgent
|
| 468 |
+
from agents.DeepPortfolioAgent import DeepPortfolioAgentNetwork
|
| 469 |
+
# from ..config import (NUM_ASSETS, WINDOW_SIZE, NUM_FEATURES_PER_ASSET, ...) # Importe do seu config real
|
| 470 |
+
# VALORES DE EXEMPLO (PEGUE DO SEU CONFIG.PY REAL)
|
| 471 |
+
NUM_ASSETS_POLICY = 4
|
| 472 |
+
WINDOW_SIZE_POLICY = 60
|
| 473 |
+
NUM_FEATURES_PER_ASSET_POLICY = 26
|
| 474 |
+
# Hiperparâmetros para DeepPortfolioAgentNetwork quando usada como extrator
|
| 475 |
+
ASSET_CNN_FILTERS1_POLICY = 32
|
| 476 |
+
ASSET_CNN_FILTERS2_POLICY = 64
|
| 477 |
+
ASSET_LSTM_UNITS1_POLICY = 64
|
| 478 |
+
ASSET_LSTM_UNITS2_POLICY = 32 # Esta será a dimensão das features latentes para ator/crítico
|
| 479 |
+
ASSET_DROPOUT_POLICY = 0.2
|
| 480 |
+
MHA_NUM_HEADS_POLICY = 4
|
| 481 |
+
MHA_KEY_DIM_DIVISOR_POLICY = 2 # Para key_dim = 32 // 2 = 16
|
| 482 |
+
FINAL_DENSE_UNITS1_POLICY = 128
|
| 483 |
+
FINAL_DENSE_UNITS2_POLICY = ASSET_LSTM_UNITS2_POLICY # A saída da dense2 SÃO as features latentes
|
| 484 |
+
FINAL_DROPOUT_POLICY = 0.3
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
class TFPortfolioFeaturesExtractor(tf.keras.layers.Layer): # Herda de tf.keras.layers.Layer
|
| 488 |
+
"""
|
| 489 |
+
Extrator de features customizado para SB3 que usa DeepPortfolioAgentNetwork.
|
| 490 |
+
A observação do ambiente é (batch, window, num_assets * num_features_per_asset).
|
| 491 |
+
A saída são as features latentes (batch, latent_dim).
|
| 492 |
+
"""
|
| 493 |
+
def __init__(self, observation_space: gym.spaces.Box, features_dim: int = ASSET_LSTM_UNITS2_POLICY):
|
| 494 |
+
super(TFPortfolioFeaturesExtractor, self).__init__()
|
| 495 |
+
self.features_dim = features_dim # SB3 usa isso para saber o tamanho da saída
|
| 496 |
+
|
| 497 |
+
# Instanciar a rede base para extrair features
|
| 498 |
+
# Ela deve retornar as ativações ANTES da camada softmax de alocação.
|
| 499 |
+
self.network = DeepPortfolioAgentNetwork(
|
| 500 |
+
num_assets=NUM_ASSETS_POLICY,
|
| 501 |
+
sequence_length=WINDOW_SIZE_POLICY,
|
| 502 |
+
num_features_per_asset=NUM_FEATURES_PER_ASSET_POLICY,
|
| 503 |
+
asset_cnn_filters1=ASSET_CNN_FILTERS1_POLICY,
|
| 504 |
+
asset_cnn_filters2=ASSET_CNN_FILTERS2_POLICY,
|
| 505 |
+
asset_lstm_units1=ASSET_LSTM_UNITS1_POLICY,
|
| 506 |
+
asset_lstm_units2=ASSET_LSTM_UNITS2_POLICY, # Define a saída do asset_processor
|
| 507 |
+
asset_dropout=ASSET_DROPOUT_POLICY,
|
| 508 |
+
mha_num_heads=MHA_NUM_HEADS_POLICY,
|
| 509 |
+
mha_key_dim_divisor=MHA_KEY_DIM_DIVISOR_POLICY,
|
| 510 |
+
final_dense_units1=FINAL_DENSE_UNITS1_POLICY,
|
| 511 |
+
final_dense_units2=self.features_dim, # A saída da dense2 é a nossa feature latente
|
| 512 |
+
final_dropout=FINAL_DROPOUT_POLICY,
|
| 513 |
+
output_latent_features=True,
|
| 514 |
+
use_sentiment_analysis=True # MUITO IMPORTANTE!
|
| 515 |
+
)
|
| 516 |
+
print("TFPortfolioFeaturesExtractor inicializado e usando DeepPortfolioAgentNetwork (output_latent_features=True).")
|
| 517 |
+
|
| 518 |
+
def call(self, observations: tf.Tensor, training: bool = False) -> tf.Tensor:
|
| 519 |
+
# A DeepPortfolioAgentNetwork já lida com o fatiamento e processamento.
|
| 520 |
+
# Ela foi configurada para retornar features latentes.
|
| 521 |
+
return self.network(observations, training=training)
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
class CustomPolicy(ActorCriticPolicy):
|
| 525 |
+
def __init__(self, *args, **kwargs):
|
| 526 |
+
super().__init__(*args, **kwargs)
|
| 527 |
+
self.mlp_extractor = CustomMlpExtractor(
|
| 528 |
+
input_dim=self.observation_space.shape[0],
|
| 529 |
+
net_arch=[64, 64], # Exemplo de arquitetura
|
| 530 |
+
activation_fn=nn.ReLU,
|
| 531 |
+
device=self.device
|
| 532 |
+
)
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
|
| 536 |
+
class CustomPortfolioPolicySB3(ActorCriticPolicy):
|
| 537 |
+
def __init__(
|
| 538 |
+
self,
|
| 539 |
+
observation_space: gym.spaces.Space,
|
| 540 |
+
action_space: gym.spaces.Space,
|
| 541 |
+
lr_schedule, # Função que retorna a taxa de aprendizado
|
| 542 |
+
net_arch: Optional[List[Union[int, Dict[str, List[int]]]]] = None, # Arquitetura para MLPs pós-extrator
|
| 543 |
+
activation_fn: Type[tf.Module] = tf.nn.relu, # Usar tf.nn.relu para TF
|
| 544 |
+
# Adicionar quaisquer outros parâmetros específicos que o extrator precise
|
| 545 |
+
features_extractor_kwargs: Optional[Dict[str, Any]] = None,
|
| 546 |
+
**kwargs,
|
| 547 |
+
):
|
| 548 |
+
if features_extractor_kwargs is None:
|
| 549 |
+
features_extractor_kwargs = {}
|
| 550 |
+
|
| 551 |
+
# A dimensão das features que o nosso extrator PortfolioFeatureExtractor vai cuspir.
|
| 552 |
+
# Deve ser igual a ASSET_LSTM_UNITS2_POLICY (ou final_dense_units2 do extrator)
|
| 553 |
+
# Se não for passado, o construtor do ActorCriticPolicy pode tentar inferir.
|
| 554 |
+
# Vamos passar explicitamente para garantir.
|
| 555 |
+
features_extractor_kwargs.setdefault("features_dim", ASSET_LSTM_UNITS2_POLICY) # Ou o valor que você definiu
|
| 556 |
+
|
| 557 |
+
super().__init__(
|
| 558 |
+
observation_space,
|
| 559 |
+
action_space,
|
| 560 |
+
lr_schedule,
|
| 561 |
+
net_arch=net_arch, # Para camadas Dense APÓS o extrator de features
|
| 562 |
+
activation_fn=activation_fn,
|
| 563 |
+
features_extractor_class=TFPortfolioFeaturesExtractor,
|
| 564 |
+
features_extractor_kwargs=features_extractor_kwargs,
|
| 565 |
+
**kwargs,
|
| 566 |
+
)
|
| 567 |
+
# Otimizador é criado na classe base.
|
| 568 |
+
# As redes de ator e crítico são construídas no método _build da classe base,
|
| 569 |
+
# usando o self.features_extractor e depois o self.mlp_extractor (que é
|
| 570 |
+
# construído com base no net_arch).
|
| 571 |
+
|
| 572 |
+
# Não precisamos sobrescrever _build_mlp_extractor se o features_extractor
|
| 573 |
+
# já fizer o trabalho pesado e o net_arch padrão para as cabeças for suficiente.
|
| 574 |
+
# Se quisermos MLPs customizados para ator e crítico APÓS o extrator:
|
| 575 |
+
# def _build_mlp_extractor(self) -> None:
|
| 576 |
+
# # self.mlp_extractor é uma instância de MlpExtractor (ou similar)
|
| 577 |
+
# # A entrada para ele é self.features_extractor.features_dim
|
| 578 |
+
# # Aqui, net_arch definiria a estrutura do mlp_extractor
|
| 579 |
+
# self.mlp_extractor = MlpExtractor(
|
| 580 |
+
# feature_dim=self.features_extractor.features_dim,
|
| 581 |
+
# net_arch=self.net_arch, # net_arch é uma lista de ints para camadas da política e valor
|
| 582 |
+
# activation_fn=self.activation_fn,
|
| 583 |
+
# device=self.device,
|
| 584 |
+
# )
|
| 585 |
+
# As redes de ação e valor (action_net, value_net) são então criadas
|
| 586 |
+
# no _build da classe ActorCriticPolicy, no topo do mlp_extractor.
|
| 587 |
+
|
| 588 |
+
from agents.custom_policies import CustomPortfolioPolicySB3 # Importar a política customizada
|
| 589 |
+
#from .deep_portfolio import NUM_ASSETS_CONF, WINDOW_SIZE_CONF, NUM_FEATURES_PER_ASSET_CONF # Se precisar para policy_kwargs
|
| 590 |
+
# (Importe as configs do config.py)
|
| 591 |
+
#from ..config import LEARNING_RATE as PPO_LEARNING_RATE
|
| 592 |
+
PPO_LEARNING_RATE = 0.0005
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
from agents.data_handler_multi_asset import get_multi_asset_data_for_rl, MULTI_ASSET_SYMBOLS # Do seu config/data_handler
|
| 596 |
+
from agents.portfolio_environment import PortfolioEnv
|
| 597 |
+
from agents.deep_portfolio import DeepPortfolioAI # Seu modelo (usado como policy)
|
| 598 |
+
# from config import ... # Outras configs
|
| 599 |
+
|
| 600 |
+
RISK_FREE_RATE_ANNUAL = 0.2
|
| 601 |
+
REWARD_WINDOW = 252
|
| 602 |
+
frisk_free_per_step = 0.0
|
| 603 |
+
|
| 604 |
+
# Janela de recompensa para Sharpe (ex: últimos 60 passos/horas)
|
| 605 |
+
# Deve ser menor ou igual ao ep_len_mean ou um valor razoável
|
| 606 |
+
reward_calc_window = 60
|
| 607 |
+
|
| 608 |
+
# 1. Carregar e preparar dados multi-ativos
|
| 609 |
+
# (MULTI_ASSET_SYMBOLS viria do config.py)
|
| 610 |
+
asset_keys_list = list(MULTI_ASSET_SYMBOLS.keys()) # ['crypto_eth', 'crypto_ada', ...]
|
| 611 |
+
|
| 612 |
+
multi_asset_df = get_multi_asset_data_for_rl(
|
| 613 |
+
MULTI_ASSET_SYMBOLS,
|
| 614 |
+
timeframe_yf='1h', # Ou TIMEFRAME_YFINANCE do config
|
| 615 |
+
days_to_fetch=365*2,
|
| 616 |
+
logger_instance=any
|
| 617 |
+
# Ou DAYS_TO_FETCH do config
|
| 618 |
+
)
|
| 619 |
+
|
| 620 |
+
print("Imprimindo retorno para df_combined passado para train_rl_portifolio")
|
| 621 |
+
print(multi_asset_df)
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
#-------------------
|
| 625 |
+
|
| 626 |
+
if multi_asset_df is None or multi_asset_df.empty:
|
| 627 |
+
print("Falha ao carregar dados multi-ativos. Encerrando treinamento RL.")
|
| 628 |
+
exit()
|
| 629 |
+
|
| 630 |
+
env = PortfolioEnv(df_multi_asset_features=multi_asset_df, asset_symbols_list=asset_keys_list)
|
| 631 |
+
print("Ambiente de Portfólio Criado.")
|
| 632 |
+
|
| 633 |
+
# --- Usar a Política Customizada ---
|
| 634 |
+
# Hiperparâmetros para o PPO
|
| 635 |
+
learning_rate_ppo = PPO_LEARNING_RATE # Ex: 3e-4 ou 1e-4 (do config.py)
|
| 636 |
+
n_steps_ppo = 2048
|
| 637 |
+
batch_size_ppo = 64
|
| 638 |
+
ent_coef_ppo = 0.0
|
| 639 |
+
|
| 640 |
+
# policy_kwargs para passar para o __init__ da CustomPortfolioPolicySB3, se necessário
|
| 641 |
+
# (além dos que já são passados para o features_extractor_kwargs)
|
| 642 |
+
# Exemplo: Se você adicionou mais args ao __init__ de CustomPortfolioPolicySB3
|
| 643 |
+
# policy_custom_kwargs = dict(
|
| 644 |
+
# meu_parametro_customizado=valor,
|
| 645 |
+
# # features_extractor_kwargs já é tratado pela classe base se você passar features_extractor_class
|
| 646 |
+
# )
|
| 647 |
+
|
| 648 |
+
print("Instanciando PPO com Política Customizada (DeepPortfolioAgentNetwork)...")
|
| 649 |
+
model_ppo = PPO(
|
| 650 |
+
CustomPortfolioPolicySB3,
|
| 651 |
+
env,
|
| 652 |
+
verbose=1,
|
| 653 |
+
learning_rate=learning_rate_ppo, # Pode ser uma função lr_schedule
|
| 654 |
+
n_steps=n_steps_ppo,
|
| 655 |
+
batch_size=batch_size_ppo,
|
| 656 |
+
ent_coef=ent_coef_ppo,
|
| 657 |
+
# policy_kwargs=policy_custom_kwargs, # Se tiver kwargs específicos para a política
|
| 658 |
+
tensorboard_log="./ppo_deep_portfolio_tensorboard/"
|
| 659 |
+
)
|
| 660 |
+
|
| 661 |
+
print("Iniciando treinamento do agente PPO com rede customizada...")
|
| 662 |
+
model_ppo.learn(total_timesteps=100000, progress_bar=True) # Comece com menos timesteps para teste (ex: 50k)
|
| 663 |
+
|
| 664 |
+
model_ppo.save("app/model/ppo_custom_deep_portfolio_agent")
|
| 665 |
+
print("Modelo RL com política customizada treinado e salvo.")
|
| 666 |
+
|
| 667 |
+
model_ppo.save("app/model/model3")
|
| 668 |
+
print("Modelo RL com política customizada treinado e salvo.")
|
| 669 |
+
|
| 670 |
+
model_ppo.save("app/model/model2.h5")
|
| 671 |
+
print("Modelo RL com política customizada treinado e salvo.")
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
#----------
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
|
| 680 |
+
# if multi_asset_df is None or multi_asset_df.empty:
|
| 681 |
+
# print("Falha ao carregar dados multi-ativos. Encerrando treinamento RL.")
|
| 682 |
+
# exit()
|
| 683 |
+
|
| 684 |
+
# # 2. Criar o Ambiente
|
| 685 |
+
# # O multi_asset_df já deve ter as features para observação E as colunas de preço de close original
|
| 686 |
+
# env = PortfolioEnv(df_multi_asset_features=multi_asset_df, asset_symbols_list=asset_keys_list)
|
| 687 |
+
|
| 688 |
+
|
| 689 |
+
# risk_free_per_step = 0.0
|
| 690 |
+
|
| 691 |
+
# # Janela de recompensa para Sharpe (ex: últimos 60 passos/horas)
|
| 692 |
+
# # Deve ser menor ou igual ao ep_len_mean ou um valor razoável
|
| 693 |
+
# reward_calc_window = 60
|
| 694 |
+
|
| 695 |
+
# env = PortfolioEnv(
|
| 696 |
+
# df_multi_asset_features=multi_asset_df,
|
| 697 |
+
# asset_symbols_list=asset_keys_list,
|
| 698 |
+
# initial_balance=100000, # Do config
|
| 699 |
+
# window_size=60, # Do config
|
| 700 |
+
# transaction_cost_pct=0.001, # Do config ou defina aqui
|
| 701 |
+
# reward_window_size=reward_calc_window,
|
| 702 |
+
# risk_free_rate_per_step=risk_free_per_step
|
| 703 |
+
# )
|
| 704 |
+
|
| 705 |
+
# # Opcional: Verificar se o ambiente está em conformidade com a API do Gymnasium
|
| 706 |
+
# # check_env(env) # Pode dar avisos/erros se algo estiver errado
|
| 707 |
+
# print("Ambiente de Portfólio Criado.")
|
| 708 |
+
# print(f"Observation Space: {env.observation_space.shape}")
|
| 709 |
+
# print(f"Action Space: {env.action_space.shape}")
|
| 710 |
+
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
|
| 714 |
+
# # 3. Definir a Política de Rede Neural
|
| 715 |
+
# # Stable-Baselines3 permite que você defina uma arquitetura customizada.
|
| 716 |
+
# # Precisamos de uma forma de passar sua arquitetura DeepPortfolioAI para o PPO.
|
| 717 |
+
# # Uma maneira é criar uma classe de política customizada.
|
| 718 |
+
# # Por agora, vamos usar a política padrão "MlpPolicy" e depois vemos como integrar a sua.
|
| 719 |
+
# # Ou, se DeepPortfolioAI for uma tf.keras.Model, podemos tentar usá-la em policy_kwargs.
|
| 720 |
+
|
| 721 |
+
# # Para usar sua DeepPortfolioAI, você precisaria de uma FeatureExtractor customizada
|
| 722 |
+
# # ou uma política que a incorpore, o que é mais avançado com Stable-Baselines3.
|
| 723 |
+
# # Vamos começar com MlpPolicy para testar o ambiente.
|
| 724 |
+
|
| 725 |
+
# # policy_kwargs = dict(
|
| 726 |
+
# # features_extractor_class=YourCustomFeatureExtractor, # Se a entrada precisar de tratamento especial
|
| 727 |
+
# # features_extractor_kwargs=dict(features_dim=128),
|
| 728 |
+
# # net_arch=[dict(pi=[256, 128], vf=[256, 128])] # Exemplo de arquitetura para policy e value networks
|
| 729 |
+
# # )
|
| 730 |
+
# # Ou, se o DeepPortfolioAI puder ser adaptado para ser a policy_network:
|
| 731 |
+
# policy_kwargs = dict(
|
| 732 |
+
# net_arch=dict(
|
| 733 |
+
# pi=[{'model': DeepPortfolioAI(num_assets=env.num_assets)}], # Não é direto assim
|
| 734 |
+
# vf=[] # Value function pode ser separada ou compartilhada
|
| 735 |
+
# )
|
| 736 |
+
# )
|
| 737 |
+
|
| 738 |
+
# # Para começar e testar o ambiente, use a MlpPolicy padrão.
|
| 739 |
+
# # O input da MlpPolicy será a observação achatada (WINDOW_SIZE * num_total_features).
|
| 740 |
+
# # Isso pode não ser ideal para dados sequenciais. "MlpLstmPolicy" é melhor.
|
| 741 |
+
|
| 742 |
+
# model_ppo = PPO("MlpPolicy", env, verbose=1, ent_coef=0.01, tensorboard_log="./ppo_portfolio_tensorboard/")
|
| 743 |
+
# # Se "MlpLstmPolicy" não funcionar bem com o shape da observação (janela, features_totais),
|
| 744 |
+
# # você pode precisar de um FeatureExtractor que achate a janela, ou uma política customizada.
|
| 745 |
+
|
| 746 |
+
# # 4. Treinar o Agente
|
| 747 |
+
# print("Iniciando treinamento do agente PPO...")
|
| 748 |
+
# model_ppo.learn(total_timesteps=int("1000000"), progress_bar=True) # Aumente timesteps para treino real
|
| 749 |
+
|
| 750 |
+
# # 5. Salvar o Modelo Treinado
|
| 751 |
+
# model_ppo.save("rl_models/ppo_deep_portfolio_agent")
|
| 752 |
+
# print("Modelo RL treinado salvo.")
|
| 753 |
+
|
| 754 |
+
|
| 755 |
+
# # (Opcional) Testar o agente treinado
|
| 756 |
+
# obs, _ = env.reset()
|
| 757 |
+
# for _ in range(200):
|
| 758 |
+
# action, _states = model_ppo.predict(obs, deterministic=True)
|
| 759 |
+
# obs, rewards, terminated, truncated, info = env.step(action)
|
| 760 |
+
# env.render()
|
| 761 |
+
# if terminated or truncated:
|
| 762 |
+
# obs, _ = env.reset()
|
| 763 |
+
# env.close()
|
app.py
CHANGED
|
@@ -1,752 +1,752 @@
|
|
| 1 |
-
# rnn/app.py
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
import os
|
| 6 |
-
import uuid
|
| 7 |
-
import time
|
| 8 |
-
import hmac
|
| 9 |
-
import hashlib
|
| 10 |
-
import json
|
| 11 |
-
from datetime import datetime, timedelta
|
| 12 |
-
from typing import Dict, Any, List, Optional
|
| 13 |
-
from rnn.app.ccxt_utils import get_ccxt_exchange, fetch_crypto_data
|
| 14 |
-
|
| 15 |
-
import httpx # Para fazer chamadas HTTP assíncronas (para o callback)
|
| 16 |
-
from fastapi import FastAPI, Request, HTTPException, Depends, Header, BackgroundTasks
|
| 17 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 18 |
-
from fastapi.responses import HTMLResponse, JSONResponse
|
| 19 |
-
from fastapi.staticfiles import StaticFiles
|
| 20 |
-
from jinja2 import Environment, FileSystemLoader
|
| 21 |
-
from pydantic import BaseModel, Field
|
| 22 |
-
|
| 23 |
-
from rnn.app.model.rnn_predictor import RNNModelPredictor
|
| 24 |
-
from rnn.app.utils.logger import get_logger
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
logger = get_logger()
|
| 29 |
-
|
| 30 |
-
# --- Configuração Inicial e Variáveis de Ambiente (Secrets do Hugging Face) ---
|
| 31 |
-
AIBANK_API_KEY = os.environ.get("AIBANK_API_KEY") # Chave que o aibank usa para chamar esta API RNN
|
| 32 |
-
AIBANK_CALLBACK_URL = os.environ.get("AIBANK_CALLBACK_URL") # URL no aibank para onde esta API RNN enviará o resultado
|
| 33 |
-
CALLBACK_SHARED_SECRET = os.environ.get("CALLBACK_SHARED_SECRET") # Segredo para assinar/verificar o payload do callback
|
| 34 |
-
|
| 35 |
-
# Chaves para serviços externos
|
| 36 |
-
MARKET_DATA_API_KEY = os.environ.get("MARKET_DATA_API_KEY")
|
| 37 |
-
EXCHANGE_API_KEY = os.environ.get("EXCHANGE_API_KEY")
|
| 38 |
-
EXCHANGE_API_SECRET = os.environ.get("EXCHANGE_API_SECRET")
|
| 39 |
-
|
| 40 |
-
if not AIBANK_API_KEY:
|
| 41 |
-
logger.warning("AIBANK_API_KEY não configurada. A autenticação para /api/invest falhou.")
|
| 42 |
-
if not AIBANK_CALLBACK_URL:
|
| 43 |
-
logger.warning("AIBANK_CALLBACK_URL não configurada. O callback para o aibank falhou.")
|
| 44 |
-
if not CALLBACK_SHARED_SECRET:
|
| 45 |
-
logger.warning("CALLBACK_SHARED_SECRET não configurado. A segurança do callback está comprometida.")
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
app = FastAPI(title="ATCoin Neural Agents - Investment API")
|
| 51 |
-
|
| 52 |
-
# --- Middlewares ---
|
| 53 |
-
app.add_middleware(
|
| 54 |
-
CORSMiddleware,
|
| 55 |
-
allow_origins=[
|
| 56 |
-
"http://localhost:3000", # URL desenvolvimento local
|
| 57 |
-
"http://aibank.app.br", # URL de produção
|
| 58 |
-
"https://*.aibank.app.br", # subdomínios
|
| 59 |
-
"https://*.hf.space" # HF Space
|
| 60 |
-
],
|
| 61 |
-
allow_credentials=True,
|
| 62 |
-
allow_methods=["*"],
|
| 63 |
-
allow_headers=["*"],
|
| 64 |
-
)
|
| 65 |
-
|
| 66 |
-
# --- Simulação de Banco de Dados de Transações DEV ---
|
| 67 |
-
# Em produção MongoDB
|
| 68 |
-
transactions_db: Dict[str, Dict[str, Any]] = {}
|
| 69 |
-
|
| 70 |
-
# --- Modelos Pydantic ---
|
| 71 |
-
class InvestmentRequest(BaseModel):
|
| 72 |
-
client_id: str
|
| 73 |
-
amount: float = Field(..., gt=0) # Garante que o montante seja positivo
|
| 74 |
-
aibank_transaction_token: str # Token único gerado pelo aibank para rastreamento
|
| 75 |
-
|
| 76 |
-
class InvestmentResponse(BaseModel):
|
| 77 |
-
status: str
|
| 78 |
-
message: str
|
| 79 |
-
rnn_transaction_id: str # ID da transação this.API
|
| 80 |
-
|
| 81 |
-
class InvestmentResultPayload(BaseModel): # Payload para o callback para o aibank
|
| 82 |
-
rnn_transaction_id: str
|
| 83 |
-
aibank_transaction_token: str
|
| 84 |
-
client_id: str
|
| 85 |
-
initial_amount: float
|
| 86 |
-
final_amount: float
|
| 87 |
-
profit_loss: float
|
| 88 |
-
status: str # "completed", "failed"
|
| 89 |
-
timestamp: datetime
|
| 90 |
-
details: str = ""
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
# --- Dependência de Autenticação ---
|
| 94 |
-
async def verify_aibank_key(authorization: str = Header(None)):
|
| 95 |
-
if not AIBANK_API_KEY: # Checagem se a chave do servidor está configurada
|
| 96 |
-
logger.error("CRITICAL: AIBANK_API_KEY (server-side) não está configurada nos Secrets.")
|
| 97 |
-
raise HTTPException(status_code=500, detail="Internal Server Configuration Error: Missing server API Key.")
|
| 98 |
-
|
| 99 |
-
if authorization is None:
|
| 100 |
-
logger.warning("Authorization header ausente na chamada do AIBank.")
|
| 101 |
-
raise HTTPException(status_code=401, detail="Authorization header is missing")
|
| 102 |
-
|
| 103 |
-
parts = authorization.split()
|
| 104 |
-
if len(parts) != 2 or parts[0].lower() != 'bearer':
|
| 105 |
-
logger.warning(f"Formato inválido do Authorization header: {authorization}")
|
| 106 |
-
raise HTTPException(status_code=401, detail="Authorization header must be 'Bearer <token>'")
|
| 107 |
-
|
| 108 |
-
token_from_aibank = parts[1]
|
| 109 |
-
if not hmac.compare_digest(token_from_aibank, AIBANK_API_KEY):
|
| 110 |
-
logger.warning(f"Chave de API inválida fornecida pelo AIBank. Token: {token_from_aibank[:10]}...")
|
| 111 |
-
raise HTTPException(status_code=403, detail="Invalid API Key provided by AIBank.")
|
| 112 |
-
logger.info("API Key do AIBank verificada com sucesso.")
|
| 113 |
-
return True
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
# --- Lógica de Negócio Principal (Simulada e em Background) ---
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
async def execute_investment_strategy_background(
|
| 120 |
-
rnn_tx_id: str,
|
| 121 |
-
client_id: str,
|
| 122 |
-
amount: float,
|
| 123 |
-
aibank_tx_token: str
|
| 124 |
-
):
|
| 125 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Iniciando estratégia de investimento para cliente {client_id}, valor {amount}.")
|
| 126 |
-
transactions_db[rnn_tx_id]["status"] = "processing"
|
| 127 |
-
transactions_db[rnn_tx_id]["status_details"] = "Initializing investment cycle"
|
| 128 |
-
|
| 129 |
-
final_status = "completed"
|
| 130 |
-
error_details = "" # Acumula mensagens de erro de várias etapas
|
| 131 |
-
calculated_final_amount = amount
|
| 132 |
-
|
| 133 |
-
# Inicializa a exchange ccxt usando o utilitário
|
| 134 |
-
# O logger do app.py é passado para ccxt_utils para que os logs apareçam no mesmo stream
|
| 135 |
-
exchange = await get_ccxt_exchange(logger_instance=logger) # MODIFICADO
|
| 136 |
-
|
| 137 |
-
if not exchange:
|
| 138 |
-
# get_ccxt_exchange já loga o erro. Se a exchange é crucial, podemos falhar aqui.
|
| 139 |
-
logger.warning(f"BG TASK [{rnn_tx_id}]: Falha ao inicializar a exchange. A estratégia pode não funcionar como esperado para cripto.")
|
| 140 |
-
# Se as chaves CCXT foram fornecidas no ambiente mas a exchange falhou, considere isso um erro de config.
|
| 141 |
-
if os.environ.get("CCXT_API_KEY") and os.environ.get("CCXT_API_SECRET"):
|
| 142 |
-
error_details += "Failed to initialize CCXT exchange despite API keys being present; "
|
| 143 |
-
final_status = "failed_config"
|
| 144 |
-
# (PULAR PARA CALLBACK - veja a seção de tratamento de erro crítico abaixo)
|
| 145 |
-
|
| 146 |
-
# =========================================================================
|
| 147 |
-
# 1. COLETAR DADOS DE MERCADO
|
| 148 |
-
# =========================================================================
|
| 149 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Coletando dados de mercado...")
|
| 150 |
-
transactions_db[rnn_tx_id]["status_details"] = "Fetching market data"
|
| 151 |
-
market_data_results = {"crypto": {}, "stocks": {}, "other": {}}
|
| 152 |
-
critical_data_fetch_failed = False # Flag para falha crítica na coleta de dados
|
| 153 |
-
|
| 154 |
-
# --- Coleta de dados de Cripto via ccxt_utils ---
|
| 155 |
-
if exchange:
|
| 156 |
-
crypto_pairs_to_fetch = ["BTC/USDT", "ETH/USDT", "SOL/USDT"] # Mantenha configurável
|
| 157 |
-
|
| 158 |
-
crypto_data, crypto_fetch_ok, crypto_err_msg = await fetch_crypto_data(
|
| 159 |
-
exchange,
|
| 160 |
-
crypto_pairs_to_fetch,
|
| 161 |
-
logger_instance=logger
|
| 162 |
-
)
|
| 163 |
-
market_data_results["crypto"] = crypto_data
|
| 164 |
-
if not crypto_fetch_ok:
|
| 165 |
-
error_details += f"Crypto data fetch issues: {crypto_err_msg}; "
|
| 166 |
-
# Decida se a falha na coleta de cripto é crítica
|
| 167 |
-
# Se for, defina critical_data_fetch_failed = True
|
| 168 |
-
if os.environ.get("CCXT_API_KEY"): # Se esperávamos dados de cripto
|
| 169 |
-
critical_data_fetch_failed = True
|
| 170 |
-
logger.error(f"BG TASK [{rnn_tx_id}]: Falha crítica na coleta de dados de cripto.")
|
| 171 |
-
else:
|
| 172 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Instância da exchange ccxt não disponível. Pulando coleta de dados de cripto.")
|
| 173 |
-
if os.environ.get("CCXT_API_KEY"): # Se esperávamos dados de cripto mas a exchange não inicializou
|
| 174 |
-
error_details += "CCXT exchange not initialized, crypto data skipped; "
|
| 175 |
-
critical_data_fetch_failed = True
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
# --- Coleta de dados para outros tipos de ativos (ex: Ações com yfinance) ---
|
| 179 |
-
# (Sua lógica yfinance aqui, se aplicável, similarmente atualizando market_data_results["stocks"])
|
| 180 |
-
# try:
|
| 181 |
-
# import yfinance as yf # Mova para o topo do app.py se for usar
|
| 182 |
-
# # ... lógica yfinance ...
|
| 183 |
-
# except Exception as e_yf:
|
| 184 |
-
# logger.warning(f"BG TASK [{rnn_tx_id}]: Falha ao buscar dados de ações com yfinance: {e_yf}")
|
| 185 |
-
# error_details += f"YFinance data fetch failed: {str(e_yf)}; "
|
| 186 |
-
# # Decida se isso é crítico: critical_data_fetch_failed = True
|
| 187 |
-
|
| 188 |
-
market_data_results["other"]['simulated_index_level'] = random.uniform(10000, 15000) # Mantém simulação
|
| 189 |
-
|
| 190 |
-
transactions_db[rnn_tx_id]["market_data_collected"] = market_data_results
|
| 191 |
-
|
| 192 |
-
# --- PONTO DE CHECAGEM PARA FALHA CRÍTICA NA COLETA DE DADOS ---
|
| 193 |
-
if critical_data_fetch_failed:
|
| 194 |
-
final_status = "failed_market_data"
|
| 195 |
-
logger.error(f"BG TASK [{rnn_tx_id}]: Coleta de dados de mercado falhou criticamente. {error_details}")
|
| 196 |
-
# Pular para a seção de callback
|
| 197 |
-
# (A lógica de envio do callback precisa ser alcançada)
|
| 198 |
-
else:
|
| 199 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Coleta de dados de mercado concluída.")
|
| 200 |
-
transactions_db[rnn_tx_id]["status_details"] = "Processing RNN analysis"
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
# =========================================================================
|
| 207 |
-
# 2. ANÁLISE PELA RNN E TOMADA DE DECISÃO
|
| 208 |
-
# =========================================================================
|
| 209 |
-
investment_decisions: List[Dict[str, Any]] = []
|
| 210 |
-
total_usd_allocated_by_rnn = 0.0
|
| 211 |
-
loop = asyncio.get_running_loop()
|
| 212 |
-
|
| 213 |
-
if final_status == "completed":
|
| 214 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Executando análise RNN...")
|
| 215 |
-
transactions_db[rnn_tx_id]["status_details"] = "Running RNN model"
|
| 216 |
-
rnn_analysis_success = True
|
| 217 |
-
|
| 218 |
-
# CORRIGIDO: Acessando app.state.rnn_predictor
|
| 219 |
-
predictor: Optional[RNNModelPredictor] = getattr(app.state, 'rnn_predictor', None)
|
| 220 |
-
|
| 221 |
-
try:
|
| 222 |
-
crypto_data_for_rnn = market_data_results.get("crypto", {})
|
| 223 |
-
candidate_assets = [
|
| 224 |
-
asset_key for asset_key, data in crypto_data_for_rnn.items()
|
| 225 |
-
if data and not data.get("error") and data.get("ohlcv_1h") # Apenas com dados válidos
|
| 226 |
-
]
|
| 227 |
-
|
| 228 |
-
# --- Parâmetros de Gerenciamento de Risco e Alocação (AJUSTE FINO É CRUCIAL) ---
|
| 229 |
-
# Risco total do portfólio para este ciclo (ex: não usar mais que 50% do capital total em novas posições)
|
| 230 |
-
MAX_CAPITAL_DEPLOYMENT_PCT_THIS_CYCLE = 0.75 # Usar até 75% do 'amount'
|
| 231 |
-
|
| 232 |
-
# Risco por ativo individual (percentual do 'amount' TOTAL)
|
| 233 |
-
MAX_ALLOCATION_PER_ASSET_PCT_OF_TOTAL = 0.15 # Ex: máx 15% do capital total em UM ativo
|
| 234 |
-
MIN_ALLOCATION_PER_ASSET_PCT_OF_TOTAL = 0.02 # Ex: mín 2% do capital total para valer a pena
|
| 235 |
-
|
| 236 |
-
MIN_USD_PER_ORDER = 25.00 # Mínimo de USD por ordem
|
| 237 |
-
MAX_CONCURRENT_POSITIONS = 4 # Máximo de posições abertas simultaneamente
|
| 238 |
-
|
| 239 |
-
# Limiares de Confiança da RNN
|
| 240 |
-
CONFIDENCE_STRONG_BUY = 0.80 # Confiança para considerar uma alocação maior
|
| 241 |
-
CONFIDENCE_MODERATE_BUY = 0.65 # Confiança mínima para considerar uma alocação base
|
| 242 |
-
CONFIDENCE_WEAK_BUY = 0.55 # Confiança para uma alocação muito pequena ou nenhuma
|
| 243 |
-
|
| 244 |
-
allocated_capital_this_cycle = 0.0
|
| 245 |
-
|
| 246 |
-
# Para diversificação, podemos querer limitar a avaliação ou dar pesos
|
| 247 |
-
# random.shuffle(candidate_assets)
|
| 248 |
-
|
| 249 |
-
for asset_key in candidate_assets:
|
| 250 |
-
if len(investment_decisions) >= MAX_CONCURRENT_POSITIONS:
|
| 251 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Limite de {MAX_CONCURRENT_POSITIONS} posições concorrentes atingido.")
|
| 252 |
-
break
|
| 253 |
-
|
| 254 |
-
# Verifica se já usamos o capital máximo para o ciclo
|
| 255 |
-
if allocated_capital_this_cycle >= amount * MAX_CAPITAL_DEPLOYMENT_PCT_THIS_CYCLE:
|
| 256 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Limite de capital para o ciclo ({MAX_CAPITAL_DEPLOYMENT_PCT_THIS_CYCLE*100}%) atingido.")
|
| 257 |
-
break
|
| 258 |
-
|
| 259 |
-
asset_symbol = asset_key.replace("_", "/")
|
| 260 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: RNN avaliando ativo: {asset_symbol}")
|
| 261 |
-
|
| 262 |
-
signal, confidence_prob = await predictor.predict_for_asset(
|
| 263 |
-
crypto_data_for_rnn[asset_key],
|
| 264 |
-
loop=loop
|
| 265 |
-
)
|
| 266 |
-
|
| 267 |
-
if signal == 1 and confidence_prob is not None: # Sinal de COMPRA e confiança válida
|
| 268 |
-
target_usd_allocation = 0.0
|
| 269 |
-
|
| 270 |
-
if confidence_prob >= CONFIDENCE_STRONG_BUY:
|
| 271 |
-
# Alocação maior para sinais fortes
|
| 272 |
-
# Ex: entre 60% e 100% da alocação máxima permitida por ativo
|
| 273 |
-
alloc_factor = 0.6 + 0.4 * ((confidence_prob - CONFIDENCE_STRONG_BUY) / (1.0 - CONFIDENCE_STRONG_BUY + 1e-6))
|
| 274 |
-
target_usd_allocation = (amount * MAX_ALLOCATION_PER_ASSET_PCT_OF_TOTAL) * alloc_factor
|
| 275 |
-
reason = f"RNN STRONG BUY signal (Conf: {confidence_prob:.3f})"
|
| 276 |
-
elif confidence_prob >= CONFIDENCE_MODERATE_BUY:
|
| 277 |
-
# Alocação base para sinais moderados
|
| 278 |
-
# Ex: entre 30% e 60% da alocação máxima permitida por ativo
|
| 279 |
-
alloc_factor = 0.3 + 0.3 * ((confidence_prob - CONFIDENCE_MODERATE_BUY) / (CONFIDENCE_STRONG_BUY - CONFIDENCE_MODERATE_BUY + 1e-6))
|
| 280 |
-
target_usd_allocation = (amount * MAX_ALLOCATION_PER_ASSET_PCT_OF_TOTAL) * alloc_factor
|
| 281 |
-
reason = f"RNN MODERATE BUY signal (Conf: {confidence_prob:.3f})"
|
| 282 |
-
elif confidence_prob >= CONFIDENCE_WEAK_BUY:
|
| 283 |
-
# Alocação pequena para sinais fracos (ou nenhuma)
|
| 284 |
-
alloc_factor = 0.1 + 0.2 * ((confidence_prob - CONFIDENCE_WEAK_BUY) / (CONFIDENCE_MODERATE_BUY - CONFIDENCE_WEAK_BUY + 1e-6))
|
| 285 |
-
target_usd_allocation = (amount * MAX_ALLOCATION_PER_ASSET_PCT_OF_TOTAL) * alloc_factor
|
| 286 |
-
reason = f"RNN WEAK BUY signal (Conf: {confidence_prob:.3f})"
|
| 287 |
-
else:
|
| 288 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Sinal COMPRA para {asset_symbol} mas confiança ({confidence_prob:.3f}) abaixo do limiar WEAK_BUY ({CONFIDENCE_WEAK_BUY}). Pulando.")
|
| 289 |
-
continue
|
| 290 |
-
|
| 291 |
-
# Garantir que a alocação não seja menor que a mínima permitida (percentual do total)
|
| 292 |
-
target_usd_allocation = max(target_usd_allocation, amount * MIN_ALLOCATION_PER_ASSET_PCT_OF_TOTAL)
|
| 293 |
-
|
| 294 |
-
# Garantir que não exceda o capital restante disponível neste CICLO
|
| 295 |
-
capital_left_for_this_cycle = (amount * MAX_CAPITAL_DEPLOYMENT_PCT_THIS_CYCLE) - allocated_capital_this_cycle
|
| 296 |
-
actual_usd_allocation = min(target_usd_allocation, capital_left_for_this_cycle)
|
| 297 |
-
|
| 298 |
-
# Garantir que a ordem mínima em USD seja respeitada
|
| 299 |
-
if actual_usd_allocation < MIN_USD_PER_ORDER:
|
| 300 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Alocação final ({actual_usd_allocation:.2f}) para {asset_symbol} abaixo do mínimo de ordem ({MIN_USD_PER_ORDER}). Pulando.")
|
| 301 |
-
continue
|
| 302 |
-
|
| 303 |
-
# Adicionar à lista de decisões
|
| 304 |
-
investment_decisions.append({
|
| 305 |
-
"asset_id": asset_symbol, "type": "CRYPTO", "action": "BUY",
|
| 306 |
-
"target_usd_amount": round(actual_usd_allocation, 2),
|
| 307 |
-
"rnn_confidence": round(confidence_prob, 4),
|
| 308 |
-
"reasoning": reason
|
| 309 |
-
})
|
| 310 |
-
allocated_capital_this_cycle += round(actual_usd_allocation, 2)
|
| 311 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Decisão: COMPRAR {actual_usd_allocation:.2f} USD de {asset_symbol}. {reason}")
|
| 312 |
-
|
| 313 |
-
# ... (restante da lógica para signal 0 ou None) ...
|
| 314 |
-
except Exception as e: # Captura exceções da lógica da RNN
|
| 315 |
-
logger.error(f"BG TASK [{rnn_tx_id}]: Erro CRÍTICO durante análise/predição RNN: {str(e)}", exc_info=True)
|
| 316 |
-
rnn_analysis_success = False # Marca que a análise RNN falhou
|
| 317 |
-
error_details += f"Critical RNN analysis/prediction error: {str(e)}; "
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
total_usd_allocated_by_rnn = allocated_capital_this_cycle
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
if not predictor or not predictor.model: # Verifica se o preditor e o modelo interno existem
|
| 326 |
-
logger.warning(f"BG TASK [{rnn_tx_id}]: Instância do preditor RNN não disponível ou modelo interno não carregado. Pulando análise RNN.")
|
| 327 |
-
rnn_analysis_success = False
|
| 328 |
-
error_details += "RNN model/predictor not available for prediction; "
|
| 329 |
-
else:
|
| 330 |
-
try:
|
| 331 |
-
# ... (lógica de iteração sobre `candidate_assets` e chamada a `predictor.predict_for_asset` como na resposta anterior)
|
| 332 |
-
# ... (lógica de alocação de capital como na resposta anterior)
|
| 333 |
-
# Garantir que toda essa lógica está dentro deste bloco 'else'
|
| 334 |
-
crypto_data_for_rnn = market_data_results.get("crypto", {})
|
| 335 |
-
candidate_assets = [
|
| 336 |
-
asset_key for asset_key, data in crypto_data_for_rnn.items()
|
| 337 |
-
if data and not data.get("error") and data.get("ohlcv_1h")
|
| 338 |
-
]
|
| 339 |
-
|
| 340 |
-
MAX_RISK_PER_ASSET_PCT = 0.05
|
| 341 |
-
MIN_USD_PER_ORDER = 20.00
|
| 342 |
-
MAX_CONCURRENT_POSITIONS = 5
|
| 343 |
-
CONFIDENCE_THRESHOLD_FOR_MAX_ALLOC = 0.85
|
| 344 |
-
CONFIDENCE_THRESHOLD_FOR_MIN_ALLOC = 0.60
|
| 345 |
-
BASE_ALLOCATION_PCT_OF_TOTAL_CAPITAL = 0.10
|
| 346 |
-
|
| 347 |
-
allocated_capital_this_cycle = 0.0
|
| 348 |
-
|
| 349 |
-
for asset_key in candidate_assets:
|
| 350 |
-
if len(investment_decisions) >= MAX_CONCURRENT_POSITIONS:
|
| 351 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Limite de posições concorrentes ({MAX_CONCURRENT_POSITIONS}) atingido.")
|
| 352 |
-
break
|
| 353 |
-
if allocated_capital_this_cycle >= amount * 0.90:
|
| 354 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Limite de capital do ciclo atingido.")
|
| 355 |
-
break
|
| 356 |
-
|
| 357 |
-
asset_symbol = asset_key.replace("_", "/")
|
| 358 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: RNN avaliando ativo: {asset_symbol}")
|
| 359 |
-
|
| 360 |
-
signal, confidence_prob = await predictor.predict_for_asset(
|
| 361 |
-
crypto_data_for_rnn[asset_key],
|
| 362 |
-
loop=loop
|
| 363 |
-
# window_size e expected_features serão os defaults de rnn_predictor.py
|
| 364 |
-
# ou podem ser passados explicitamente se você quiser variar por ativo
|
| 365 |
-
)
|
| 366 |
-
|
| 367 |
-
if signal == 1:
|
| 368 |
-
if confidence_prob is None or confidence_prob < CONFIDENCE_THRESHOLD_FOR_MIN_ALLOC:
|
| 369 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Sinal COMPRA para {asset_symbol} mas confiança ({confidence_prob}) abaixo do mínimo {CONFIDENCE_THRESHOLD_FOR_MIN_ALLOC}. Pulando.")
|
| 370 |
-
continue
|
| 371 |
-
|
| 372 |
-
confidence_factor = 0.5
|
| 373 |
-
if confidence_prob >= CONFIDENCE_THRESHOLD_FOR_MAX_ALLOC:
|
| 374 |
-
confidence_factor = 1.0
|
| 375 |
-
elif confidence_prob > CONFIDENCE_THRESHOLD_FOR_MIN_ALLOC:
|
| 376 |
-
confidence_factor = 0.5 + 0.5 * (
|
| 377 |
-
(confidence_prob - CONFIDENCE_THRESHOLD_FOR_MIN_ALLOC) /
|
| 378 |
-
(CONFIDENCE_THRESHOLD_FOR_MAX_ALLOC - CONFIDENCE_THRESHOLD_FOR_MIN_ALLOC)
|
| 379 |
-
)
|
| 380 |
-
|
| 381 |
-
potential_usd_allocation = amount * BASE_ALLOCATION_PCT_OF_TOTAL_CAPITAL * confidence_factor
|
| 382 |
-
potential_usd_allocation = min(potential_usd_allocation, amount * MAX_RISK_PER_ASSET_PCT)
|
| 383 |
-
remaining_capital_for_cycle = amount - allocated_capital_this_cycle # Recalcula a cada iteração
|
| 384 |
-
actual_usd_allocation = min(potential_usd_allocation, remaining_capital_for_cycle)
|
| 385 |
-
|
| 386 |
-
if actual_usd_allocation < MIN_USD_PER_ORDER:
|
| 387 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Alocação calculada ({actual_usd_allocation:.2f}) para {asset_symbol} abaixo do mínimo ({MIN_USD_PER_ORDER}). Pulando.")
|
| 388 |
-
continue
|
| 389 |
-
|
| 390 |
-
investment_decisions.append({
|
| 391 |
-
"asset_id": asset_symbol, "type": "CRYPTO", "action": "BUY",
|
| 392 |
-
"target_usd_amount": round(actual_usd_allocation, 2),
|
| 393 |
-
"rnn_confidence": round(confidence_prob, 4) if confidence_prob is not None else None,
|
| 394 |
-
"reasoning": f"RNN signal BUY for {asset_symbol} with confidence {confidence_prob:.2f}"
|
| 395 |
-
})
|
| 396 |
-
allocated_capital_this_cycle += round(actual_usd_allocation, 2)
|
| 397 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Decisão: COMPRAR {actual_usd_allocation:.2f} USD de {asset_symbol} (Conf: {confidence_prob:.2f})")
|
| 398 |
-
|
| 399 |
-
elif signal == 0:
|
| 400 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: RNN sinal NÃO COMPRAR para {asset_symbol} (Conf: {confidence_prob:.2f if confidence_prob is not None else 'N/A'})")
|
| 401 |
-
else:
|
| 402 |
-
logger.warning(f"BG TASK [{rnn_tx_id}]: RNN não gerou sinal para {asset_symbol}.")
|
| 403 |
-
|
| 404 |
-
if not investment_decisions:
|
| 405 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: RNN não gerou decisões de COMPRA válidas após avaliação e alocação.")
|
| 406 |
-
|
| 407 |
-
except Exception as e: # Captura exceções da lógica da RNN
|
| 408 |
-
logger.error(f"BG TASK [{rnn_tx_id}]: Erro CRÍTICO durante análise/predição RNN: {str(e)}", exc_info=True)
|
| 409 |
-
rnn_analysis_success = False # Marca que a análise RNN falhou
|
| 410 |
-
error_details += f"Critical RNN analysis/prediction error: {str(e)}; "
|
| 411 |
-
|
| 412 |
-
if not rnn_analysis_success: # Se a flag foi setada para False
|
| 413 |
-
final_status = "failed_rnn_analysis"
|
| 414 |
-
|
| 415 |
-
transactions_db[rnn_tx_id]["rnn_decisions"] = investment_decisions
|
| 416 |
-
|
| 417 |
-
total_usd_allocated_by_rnn = allocated_capital_this_cycle
|
| 418 |
-
transactions_db[rnn_tx_id]["status_details"] = "Preparing to execute orders"
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
# =========================================================================
|
| 430 |
-
# 3. EXECUÇÃO DE ORDENS (Só executa se a RNN não falhou e gerou ordens)
|
| 431 |
-
# =========================================================================
|
| 432 |
-
executed_trades_info: List[Dict[str, Any]] = []
|
| 433 |
-
current_portfolio_value = 0.0 # Valor dos ativos comprados, baseado no custo
|
| 434 |
-
cash_remaining_after_execution = amount # Começa com todo o montante
|
| 435 |
-
|
| 436 |
-
if final_status == "completed" and investment_decisions and exchange:
|
| 437 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Executando {len(investment_decisions)} ordens...")
|
| 438 |
-
transactions_db[rnn_tx_id]["status_details"] = "Executing investment orders"
|
| 439 |
-
order_execution_overall_success = True
|
| 440 |
-
|
| 441 |
-
# Placeholder para LÓGICA REAL DE EXECUÇÃO DE ORDENS (CREATE_ORDER_PLACEHOLDER)
|
| 442 |
-
# Esta seção precisa ser preenchida com:
|
| 443 |
-
# 1. Iterar sobre `investment_decisions`.
|
| 444 |
-
# 2. Para cada decisão de "BUY":
|
| 445 |
-
# a. Determinar o símbolo correto na exchange (ex: "BTC/USDT").
|
| 446 |
-
# b. Obter o preço atual (ticker) para calcular a quantidade de ativo a comprar.
|
| 447 |
-
# `amount_of_asset = target_usd_amount / current_price_of_asset`
|
| 448 |
-
# c. Considerar saldo disponível na exchange (se estiver gerenciando isso).
|
| 449 |
-
# d. Criar a ordem via `await exchange.create_market_buy_order(symbol, amount_of_asset)`
|
| 450 |
-
# ou `create_limit_buy_order(symbol, amount_of_asset, limit_price)`.
|
| 451 |
-
# Para ordens limite, a RNN precisaria fornecer o `limit_price`.
|
| 452 |
-
# e. Tratar respostas da exchange (sucesso, falha, ID da ordem).
|
| 453 |
-
# `ccxt.InsufficientFunds`, `ccxt.InvalidOrder`, etc.
|
| 454 |
-
# f. Armazenar detalhes da ordem em `executed_trades_info`:
|
| 455 |
-
# { "asset_id": ..., "order_id_exchange": ..., "type": "market/limit", "side": "buy",
|
| 456 |
-
# "requested_usd_amount": ..., "asset_quantity_ordered": ...,
|
| 457 |
-
# "status_from_exchange": ..., "filled_quantity": ..., "average_fill_price": ...,
|
| 458 |
-
# "cost_in_usd": ..., "fees_paid": ..., "timestamp": ... }
|
| 459 |
-
# g. Atualizar `current_portfolio_value` com o `cost_in_usd` da ordem preenchida.
|
| 460 |
-
# h. Deduzir `cost_in_usd` de `cash_remaining_after_execution`.
|
| 461 |
-
# 3. Para decisões de "SELL" (se sua RNN gerar):
|
| 462 |
-
# a. Verificar se você possui o ativo (requer gerenciamento de portfólio).
|
| 463 |
-
# b. Criar ordem de venda.
|
| 464 |
-
# c. Atualizar `current_portfolio_value` e `cash_remaining_after_execution`.
|
| 465 |
-
|
| 466 |
-
# Simulação atual:
|
| 467 |
-
for decision in investment_decisions:
|
| 468 |
-
if decision.get("action") == "BUY" and decision.get("type") == "CRYPTO":
|
| 469 |
-
asset_symbol = decision["asset_id"]
|
| 470 |
-
usd_to_spend = decision["target_usd_amount"]
|
| 471 |
-
|
| 472 |
-
# Simular pequena chance de falha na ordem
|
| 473 |
-
if random.random() < 0.05:
|
| 474 |
-
logger.warning(f"BG TASK [{rnn_tx_id}]: Falha simulada ao executar ordem para {asset_symbol}.")
|
| 475 |
-
executed_trades_info.append({
|
| 476 |
-
"asset_id": asset_symbol, "status": "failed_simulated",
|
| 477 |
-
"requested_usd_amount": usd_to_spend, "error": "Simulated exchange rejection"
|
| 478 |
-
})
|
| 479 |
-
order_execution_overall_success = False # Marca que pelo menos uma falhou
|
| 480 |
-
continue # Pula para a próxima decisão
|
| 481 |
-
|
| 482 |
-
# Simular slippage e custo
|
| 483 |
-
simulated_cost = usd_to_spend * random.uniform(0.995, 1.005) # +/- 0.5% slippage
|
| 484 |
-
|
| 485 |
-
# Garantir que não estamos gastando mais do que o caixa restante
|
| 486 |
-
if simulated_cost > cash_remaining_after_execution:
|
| 487 |
-
simulated_cost = cash_remaining_after_execution # Gasta apenas o que tem
|
| 488 |
-
if simulated_cost < 1: # Se não há quase nada, não faz a ordem
|
| 489 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Saldo insuficiente ({cash_remaining_after_execution:.2f}) para ordem de {asset_symbol}, pulando.")
|
| 490 |
-
continue
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
if simulated_cost > 0:
|
| 494 |
-
current_portfolio_value += simulated_cost
|
| 495 |
-
cash_remaining_after_execution -= simulated_cost
|
| 496 |
-
executed_trades_info.append({
|
| 497 |
-
"asset_id": asset_symbol, "order_id_exchange": f"sim_ord_{uuid.uuid4()}",
|
| 498 |
-
"type": "market", "side": "buy",
|
| 499 |
-
"requested_usd_amount": usd_to_spend,
|
| 500 |
-
"status_from_exchange": "filled", "cost_in_usd": round(simulated_cost, 2),
|
| 501 |
-
"timestamp": datetime.utcnow().isoformat()
|
| 502 |
-
})
|
| 503 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Ordem simulada para {asset_symbol} (custo: {simulated_cost:.2f} USD) preenchida.")
|
| 504 |
-
|
| 505 |
-
await asyncio.sleep(random.uniform(1, 2) * len(investment_decisions) if investment_decisions else 1)
|
| 506 |
-
|
| 507 |
-
if not order_execution_overall_success:
|
| 508 |
-
error_details += "One or more orders failed during execution; "
|
| 509 |
-
# Decida se isso torna o status final 'failed_order_execution' ou se 'completed_with_partial_failure'
|
| 510 |
-
# final_status = "completed_with_partial_failure" # Exemplo de um novo status
|
| 511 |
-
|
| 512 |
-
elif not exchange and investment_decisions:
|
| 513 |
-
logger.warning(f"BG TASK [{rnn_tx_id}]: Decisões de investimento geradas, mas a exchange não está disponível para execução.")
|
| 514 |
-
error_details += "Exchange not available for order execution; "
|
| 515 |
-
final_status = "failed_order_execution" # Se a execução é crítica
|
| 516 |
-
cash_remaining_after_execution = amount # Nada foi gasto
|
| 517 |
-
|
| 518 |
-
transactions_db[rnn_tx_id]["executed_trades"] = executed_trades_info
|
| 519 |
-
transactions_db[rnn_tx_id]["cash_after_execution"] = round(cash_remaining_after_execution, 2)
|
| 520 |
-
transactions_db[rnn_tx_id]["portfolio_value_after_execution"] = round(current_portfolio_value, 2)
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
# =========================================================================
|
| 524 |
-
# 4. SIMULAÇÃO DO PERÍODO DE INVESTIMENTO E CÁLCULO DE LUCRO/PERDA (Só se não houve falha crítica antes)
|
| 525 |
-
# =========================================================================
|
| 526 |
-
value_of_investments_at_eod = current_portfolio_value # Começa com o valor de custo
|
| 527 |
-
|
| 528 |
-
if final_status == "completed": # Ou "completed_with_partial_failure"
|
| 529 |
-
transactions_db[rnn_tx_id]["status_details"] = "Simulating EOD valuation"
|
| 530 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Simulando valorização do portfólio no final do dia...")
|
| 531 |
-
await asyncio.sleep(random.uniform(3, 7))
|
| 532 |
-
|
| 533 |
-
if current_portfolio_value > 0:
|
| 534 |
-
# Simular mudança de valor do portfólio. A meta de 4.2% é sobre o capital INVESTIDO.
|
| 535 |
-
# O lucro/perda é aplicado ao `current_portfolio_value` (o que foi efetivamente comprado).
|
| 536 |
-
daily_return_factor = 0.042 # A meta
|
| 537 |
-
simulated_performance_factor = random.uniform(0.7, 1.3) # Variação em torno da meta (pode ser prejuízo)
|
| 538 |
-
# Para ser mais realista, o fator de performance deveria ser algo como:
|
| 539 |
-
# random.uniform(-0.05, 0.08) -> -5% a +8% de retorno diário sobre o investido (ainda alto)
|
| 540 |
-
# E não diretamente ligado à meta de 4.2%
|
| 541 |
-
|
| 542 |
-
# Ajuste para uma simulação de retorno mais plausível (ainda agressiva)
|
| 543 |
-
# Suponha que o retorno diário real possa variar de -3% a +5% sobre o investido
|
| 544 |
-
actual_daily_return_on_portfolio = random.uniform(-0.03, 0.05)
|
| 545 |
-
|
| 546 |
-
profit_or_loss_on_portfolio = current_portfolio_value * actual_daily_return_on_portfolio
|
| 547 |
-
value_of_investments_at_eod = current_portfolio_value + profit_or_loss_on_portfolio
|
| 548 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Portfólio inicial: {current_portfolio_value:.2f}, Retorno simulado: {actual_daily_return_on_portfolio*100:.2f}%, "
|
| 549 |
-
f"Lucro/Prejuízo no portfólio: {profit_or_loss_on_portfolio:.2f}, Valor EOD do portfólio: {value_of_investments_at_eod:.2f}")
|
| 550 |
-
else:
|
| 551 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Nenhum portfólio para valorizar no EOD (nada foi comprado).")
|
| 552 |
-
value_of_investments_at_eod = 0.0
|
| 553 |
-
|
| 554 |
-
# O calculated_final_amount é o valor dos investimentos liquidados + o caixa que não foi usado
|
| 555 |
-
calculated_final_amount = value_of_investments_at_eod + cash_remaining_after_execution
|
| 556 |
-
|
| 557 |
-
else: # Se houve falha antes, o valor final é o que sobrou após a falha
|
| 558 |
-
calculated_final_amount = cash_remaining_after_execution + current_portfolio_value # current_portfolio_value pode ser 0 ou parcial
|
| 559 |
-
logger.warning(f"BG TASK [{rnn_tx_id}]: Ciclo de investimento não concluído normalmente ({final_status}). Valor final baseado no estado atual.")
|
| 560 |
-
|
| 561 |
-
transactions_db[rnn_tx_id]["eod_portfolio_value_simulated"] = round(value_of_investments_at_eod, 2)
|
| 562 |
-
transactions_db[rnn_tx_id]["final_calculated_amount"] = round(calculated_final_amount, 2)
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
# =========================================================================
|
| 566 |
-
# 5. TOKENIZAÇÃO / REGISTRO DA OPERAÇÃO (Só se não houve falha crítica antes)
|
| 567 |
-
# =========================================================================
|
| 568 |
-
if final_status not in ["failed_config", "failed_market_data", "failed_rnn_analysis"]: # Prossegue se ao menos tentou executar
|
| 569 |
-
transactions_db[rnn_tx_id]["status_details"] = "Finalizing transaction log (tokenization)"
|
| 570 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Registrando (tokenizando) operação detalhadamente...")
|
| 571 |
-
# Placeholder para LÓGICA REAL DE TOKENIZAÇÃO (TOKENIZATION_PLACEHOLDER)
|
| 572 |
-
# 1. Coletar todos os dados relevantes da transação de `transactions_db[rnn_tx_id]`
|
| 573 |
-
# (market_data_collected, rnn_decisions, executed_trades, eod_portfolio_value_simulated, etc.)
|
| 574 |
-
# 2. Se for usar blockchain:
|
| 575 |
-
# a. Preparar os dados para um contrato inteligente.
|
| 576 |
-
# b. Interagir com o contrato (ex: web3.py para Ethereum).
|
| 577 |
-
# c. Armazenar o hash da transação da blockchain.
|
| 578 |
-
# 3. Se for um registro interno avançado:
|
| 579 |
-
# a. Assinar digitalmente os dados da transação.
|
| 580 |
-
# b. Armazenar em um sistema de log imutável ou banco de dados com auditoria.
|
| 581 |
-
|
| 582 |
-
# Simulação atual (hash dos dados da transação):
|
| 583 |
-
transaction_data_for_hash = {
|
| 584 |
-
"rnn_tx_id": rnn_tx_id, "client_id": client_id, "initial_amount": amount,
|
| 585 |
-
"final_amount_calculated": calculated_final_amount,
|
| 586 |
-
# Incluir resumos ou hashes dos dados coletados para não tornar o hash gigante
|
| 587 |
-
"market_data_summary_keys": list(transactions_db[rnn_tx_id].get("market_data_collected", {}).keys()),
|
| 588 |
-
"rnn_decisions_count": len(transactions_db[rnn_tx_id].get("rnn_decisions", [])),
|
| 589 |
-
"executed_trades_count": len(transactions_db[rnn_tx_id].get("executed_trades", [])),
|
| 590 |
-
"eod_portfolio_value": transactions_db[rnn_tx_id].get("eod_portfolio_value_simulated"),
|
| 591 |
-
"timestamp": datetime.utcnow().isoformat()
|
| 592 |
-
}
|
| 593 |
-
ordered_tx_data_str = json.dumps(transaction_data_for_hash, sort_keys=True)
|
| 594 |
-
proof_token_hash = hashlib.sha256(ordered_tx_data_str.encode('utf-8')).hexdigest()
|
| 595 |
-
|
| 596 |
-
transactions_db[rnn_tx_id]["proof_of_operation_token"] = proof_token_hash
|
| 597 |
-
transactions_db[rnn_tx_id]["tokenization_method"] = "internal_summary_hash_proof"
|
| 598 |
-
await asyncio.sleep(0.5) # Simula tempo de escrita/hash
|
| 599 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Operação registrada. Prova (hash): {proof_token_hash[:10]}...")
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
# =========================================================================
|
| 603 |
-
# 6. PREPARAR E ENVIAR CALLBACK PARA AIBANK
|
| 604 |
-
# =========================================================================
|
| 605 |
-
if exchange and hasattr(exchange, 'close'):
|
| 606 |
-
try:
|
| 607 |
-
await exchange.close()
|
| 608 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Conexão ccxt fechada.")
|
| 609 |
-
except Exception as e_close: # Especificar o tipo de exceção se souber
|
| 610 |
-
logger.warning(f"BG TASK [{rnn_tx_id}]: Erro ao fechar conexão ccxt: {str(e_close)}")
|
| 611 |
-
|
| 612 |
-
if not AIBANK_CALLBACK_URL or not CALLBACK_SHARED_SECRET:
|
| 613 |
-
logger.error(f"BG TASK [{rnn_tx_id}]: Configuração de callback ausente. Não é possível notificar o AIBank.")
|
| 614 |
-
transactions_db[rnn_tx_id]["callback_status"] = "config_missing_critical"
|
| 615 |
-
return
|
| 616 |
-
|
| 617 |
-
# Certifique-se que `final_status` reflete o estado real da operação
|
| 618 |
-
# Se `error_details` não estiver vazio e `final_status` ainda for "completed", ajuste-o
|
| 619 |
-
if error_details and final_status == "completed":
|
| 620 |
-
final_status = "completed_with_warnings" # Ou um status mais apropriado
|
| 621 |
-
|
| 622 |
-
callback_payload_data = InvestmentResultPayload(
|
| 623 |
-
rnn_transaction_id=rnn_tx_id, aibank_transaction_token=aibank_tx_token, client_id=client_id,
|
| 624 |
-
initial_amount=amount, final_amount=round(calculated_final_amount, 2), # Arredonda para 2 casas decimais
|
| 625 |
-
profit_loss=round(calculated_final_amount - amount, 2),
|
| 626 |
-
status=final_status, timestamp=datetime.utcnow(),
|
| 627 |
-
details=error_details if error_details else "Investment cycle processed."
|
| 628 |
-
)
|
| 629 |
-
payload_json_str = callback_payload_data.model_dump_json() # Garante que está usando a string serializada
|
| 630 |
-
|
| 631 |
-
signature = hmac.new(CALLBACK_SHARED_SECRET.encode('utf-8'), payload_json_str.encode('utf-8'), hashlib.sha256).hexdigest()
|
| 632 |
-
headers = {'Content-Type': 'application/json', 'X-RNN-Signature': signature}
|
| 633 |
-
|
| 634 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Enviando callback para AIBank ({AIBANK_CALLBACK_URL}) com status final '{final_status}'. Payload: {payload_json_str}")
|
| 635 |
-
transactions_db[rnn_tx_id]["callback_status"] = "sending"
|
| 636 |
-
try:
|
| 637 |
-
async with httpx.AsyncClient(timeout=30.0) as client: # Timeout global para o cliente
|
| 638 |
-
response = await client.post(AIBANK_CALLBACK_URL, content=payload_json_str, headers=headers)
|
| 639 |
-
response.raise_for_status()
|
| 640 |
-
logger.info(f"BG TASK [{rnn_tx_id}]: Callback para AIBank enviado com sucesso. Resposta: {response.status_code}")
|
| 641 |
-
transactions_db[rnn_tx_id]["callback_status"] = f"sent_success_{response.status_code}"
|
| 642 |
-
except httpx.RequestError as e_req:
|
| 643 |
-
logger.error(f"BG TASK [{rnn_tx_id}]: Erro de REDE ao enviar callback para AIBank: {e_req}")
|
| 644 |
-
transactions_db[rnn_tx_id]["callback_status"] = "sent_failed_network_error"
|
| 645 |
-
except httpx.HTTPStatusError as e_http:
|
| 646 |
-
logger.error(f"BG TASK [{rnn_tx_id}]: Erro HTTP do AIBank ao receber callback: {e_http.response.status_code} - {e_http.response.text[:200]}")
|
| 647 |
-
transactions_db[rnn_tx_id]["callback_status"] = f"sent_failed_http_error_{e_http.response.status_code}"
|
| 648 |
-
except Exception as e_cb_final:
|
| 649 |
-
logger.error(f"BG TASK [{rnn_tx_id}]: Erro INESPERADO ao enviar callback: {e_cb_final}", exc_info=True)
|
| 650 |
-
transactions_db[rnn_tx_id]["callback_status"] = "sent_failed_unknown_error"
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
import asyncio
|
| 654 |
-
import random
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
# --- Endpoints da API ---
|
| 659 |
-
@app.post("/api/invest",
|
| 660 |
-
response_model=InvestmentResponse,
|
| 661 |
-
dependencies=[Depends(verify_aibank_key)])
|
| 662 |
-
async def initiate_investment(
|
| 663 |
-
request_data: InvestmentRequest,
|
| 664 |
-
background_tasks: BackgroundTasks
|
| 665 |
-
):
|
| 666 |
-
"""
|
| 667 |
-
Endpoint para o AIBank iniciar um ciclo de investimento.
|
| 668 |
-
Responde rapidamente e executa a lógica pesada em background.
|
| 669 |
-
"""
|
| 670 |
-
logger.info(f"Requisição de investimento recebida para client_id: {request_data.client_id}, "
|
| 671 |
-
f"amount: {request_data.amount}, aibank_tx_token: {request_data.aibank_transaction_token}")
|
| 672 |
-
|
| 673 |
-
rnn_tx_id = str(uuid.uuid4())
|
| 674 |
-
|
| 675 |
-
# Armazena informações iniciais da transação DB real para ser mais robusto
|
| 676 |
-
transactions_db[rnn_tx_id] = {
|
| 677 |
-
"rnn_transaction_id": rnn_tx_id,
|
| 678 |
-
"aibank_transaction_token": request_data.aibank_transaction_token,
|
| 679 |
-
"client_id": request_data.client_id,
|
| 680 |
-
"initial_amount": request_data.amount,
|
| 681 |
-
"status": "pending_background_processing",
|
| 682 |
-
"received_at": datetime.utcnow().isoformat(),
|
| 683 |
-
"callback_status": "not_sent_yet"
|
| 684 |
-
}
|
| 685 |
-
|
| 686 |
-
# Adiciona a tarefa de longa duração ao background
|
| 687 |
-
background_tasks.add_task(
|
| 688 |
-
execute_investment_strategy_background,
|
| 689 |
-
rnn_tx_id,
|
| 690 |
-
request_data.client_id,
|
| 691 |
-
request_data.amount,
|
| 692 |
-
request_data.aibank_transaction_token
|
| 693 |
-
)
|
| 694 |
-
|
| 695 |
-
logger.info(f"Estratégia de investimento para rnn_tx_id: {rnn_tx_id} agendada para execução em background.")
|
| 696 |
-
return InvestmentResponse(
|
| 697 |
-
status="pending",
|
| 698 |
-
message="Investment request received and is being processed in the background. Await callback for results.",
|
| 699 |
-
rnn_transaction_id=rnn_tx_id
|
| 700 |
-
)
|
| 701 |
-
|
| 702 |
-
@app.get("/api/transaction_status/{rnn_tx_id}", response_class=JSONResponse)
|
| 703 |
-
async def get_transaction_status(rnn_tx_id: str):
|
| 704 |
-
""" Endpoint para verificar o status de uma transação (para debug/admin) """
|
| 705 |
-
transaction = transactions_db.get(rnn_tx_id)
|
| 706 |
-
if not transaction:
|
| 707 |
-
raise HTTPException(status_code=404, detail="Transaction not found")
|
| 708 |
-
return transaction
|
| 709 |
-
|
| 710 |
-
|
| 711 |
-
# --- Dashboard (Existente, adaptado) ---
|
| 712 |
-
# Setup para arquivos estáticos e templates
|
| 713 |
-
|
| 714 |
-
try:
|
| 715 |
-
app.mount("/static", StaticFiles(directory="rnn/static"), name="static")
|
| 716 |
-
templates = Environment(loader=FileSystemLoader("rnn/templates"))
|
| 717 |
-
except RuntimeError as e:
|
| 718 |
-
logger.warning(f"Não foi possível montar /static ou carregar templates: {e}. O dashboard pode não funcionar.")
|
| 719 |
-
templates = None # Para evitar erros se o loader falhar
|
| 720 |
-
|
| 721 |
-
@app.get("/", response_class=HTMLResponse)
|
| 722 |
-
async def index(request: Request):
|
| 723 |
-
if not templates:
|
| 724 |
-
return HTMLResponse("<html><body><h1>Dashboard indisponível</h1><p>Configuração de templates/estáticos falhou.</p></body></html>")
|
| 725 |
-
|
| 726 |
-
agora = datetime.now()
|
| 727 |
-
agentes_simulados = [
|
| 728 |
-
# dados de agentes ...
|
| 729 |
-
]
|
| 730 |
-
template = templates.get_template("index.html")
|
| 731 |
-
# Adicionar transações recentes ao contexto do template
|
| 732 |
-
recent_txs = list(transactions_db.values())[-5:] # Últimas 5 transações
|
| 733 |
-
return HTMLResponse(template.render(request=request, agentes=agentes_simulados, transactions=recent_txs))
|
| 734 |
-
|
| 735 |
-
# --- Imports para Background Task ---
|
| 736 |
-
import asyncio
|
| 737 |
-
import random
|
| 738 |
-
|
| 739 |
-
# Função de logger dummy
|
| 740 |
-
# class DummyLogger:
|
| 741 |
-
# def info(self, msg, *args, **kwargs): print(f"INFO: {msg}")
|
| 742 |
-
# def warning(self, msg, *args, **kwargs): print(f"WARNING: {msg}")
|
| 743 |
-
# def error(self, msg, *args, **kwargs): print(f"ERROR: {msg}", kwargs.get('exc_info'))
|
| 744 |
-
|
| 745 |
-
# if __name__ == "__main__": # Para teste local
|
| 746 |
-
# # logger = DummyLogger() # se não tiver get_logger()
|
| 747 |
-
# # Configuração das variáveis de ambiente para teste local
|
| 748 |
-
# os.environ["AIBANK_API_KEY"] = "test_aibank_key_from_rnn_server"
|
| 749 |
-
# os.environ["AIBANK_CALLBACK_URL"] = "http://localhost:8001/api/rnn_investment_result_callback" # URL do aibank simulado
|
| 750 |
-
# os.environ["CALLBACK_SHARED_SECRET"] = "super_secret_for_callback_signing"
|
| 751 |
-
# # import uvicorn
|
| 752 |
# # uvicorn.run(app, host="0.0.0.0", port=8000)
|
|
|
|
| 1 |
+
# rnn/app.py
|
| 2 |
+
from agents.train_rl_portfolio_agent_from_app import model_ppo
|
| 3 |
+
model_ppo()
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import uuid
|
| 7 |
+
import time
|
| 8 |
+
import hmac
|
| 9 |
+
import hashlib
|
| 10 |
+
import json
|
| 11 |
+
from datetime import datetime, timedelta
|
| 12 |
+
from typing import Dict, Any, List, Optional
|
| 13 |
+
from rnn.app.utils.ccxt_utils import get_ccxt_exchange, fetch_crypto_data
|
| 14 |
+
|
| 15 |
+
import httpx # Para fazer chamadas HTTP assíncronas (para o callback)
|
| 16 |
+
from fastapi import FastAPI, Request, HTTPException, Depends, Header, BackgroundTasks
|
| 17 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 18 |
+
from fastapi.responses import HTMLResponse, JSONResponse
|
| 19 |
+
from fastapi.staticfiles import StaticFiles
|
| 20 |
+
from jinja2 import Environment, FileSystemLoader
|
| 21 |
+
from pydantic import BaseModel, Field
|
| 22 |
+
|
| 23 |
+
from rnn.app.model.rnn_predictor import RNNModelPredictor
|
| 24 |
+
from rnn.app.utils.logger import get_logger
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
logger = get_logger()
|
| 29 |
+
|
| 30 |
+
# --- Configuração Inicial e Variáveis de Ambiente (Secrets do Hugging Face) ---
|
| 31 |
+
AIBANK_API_KEY = os.environ.get("AIBANK_API_KEY") # Chave que o aibank usa para chamar esta API RNN
|
| 32 |
+
AIBANK_CALLBACK_URL = os.environ.get("AIBANK_CALLBACK_URL") # URL no aibank para onde esta API RNN enviará o resultado
|
| 33 |
+
CALLBACK_SHARED_SECRET = os.environ.get("CALLBACK_SHARED_SECRET") # Segredo para assinar/verificar o payload do callback
|
| 34 |
+
|
| 35 |
+
# Chaves para serviços externos
|
| 36 |
+
MARKET_DATA_API_KEY = os.environ.get("MARKET_DATA_API_KEY")
|
| 37 |
+
EXCHANGE_API_KEY = os.environ.get("EXCHANGE_API_KEY")
|
| 38 |
+
EXCHANGE_API_SECRET = os.environ.get("EXCHANGE_API_SECRET")
|
| 39 |
+
|
| 40 |
+
if not AIBANK_API_KEY:
|
| 41 |
+
logger.warning("AIBANK_API_KEY não configurada. A autenticação para /api/invest falhou.")
|
| 42 |
+
if not AIBANK_CALLBACK_URL:
|
| 43 |
+
logger.warning("AIBANK_CALLBACK_URL não configurada. O callback para o aibank falhou.")
|
| 44 |
+
if not CALLBACK_SHARED_SECRET:
|
| 45 |
+
logger.warning("CALLBACK_SHARED_SECRET não configurado. A segurança do callback está comprometida.")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
app = FastAPI(title="ATCoin Neural Agents - Investment API")
|
| 51 |
+
|
| 52 |
+
# --- Middlewares ---
|
| 53 |
+
app.add_middleware(
|
| 54 |
+
CORSMiddleware,
|
| 55 |
+
allow_origins=[
|
| 56 |
+
"http://localhost:3000", # URL desenvolvimento local
|
| 57 |
+
"http://aibank.app.br", # URL de produção
|
| 58 |
+
"https://*.aibank.app.br", # subdomínios
|
| 59 |
+
"https://*.hf.space" # HF Space
|
| 60 |
+
],
|
| 61 |
+
allow_credentials=True,
|
| 62 |
+
allow_methods=["*"],
|
| 63 |
+
allow_headers=["*"],
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
# --- Simulação de Banco de Dados de Transações DEV ---
|
| 67 |
+
# Em produção MongoDB
|
| 68 |
+
transactions_db: Dict[str, Dict[str, Any]] = {}
|
| 69 |
+
|
| 70 |
+
# --- Modelos Pydantic ---
|
| 71 |
+
class InvestmentRequest(BaseModel):
|
| 72 |
+
client_id: str
|
| 73 |
+
amount: float = Field(..., gt=0) # Garante que o montante seja positivo
|
| 74 |
+
aibank_transaction_token: str # Token único gerado pelo aibank para rastreamento
|
| 75 |
+
|
| 76 |
+
class InvestmentResponse(BaseModel):
|
| 77 |
+
status: str
|
| 78 |
+
message: str
|
| 79 |
+
rnn_transaction_id: str # ID da transação this.API
|
| 80 |
+
|
| 81 |
+
class InvestmentResultPayload(BaseModel): # Payload para o callback para o aibank
|
| 82 |
+
rnn_transaction_id: str
|
| 83 |
+
aibank_transaction_token: str
|
| 84 |
+
client_id: str
|
| 85 |
+
initial_amount: float
|
| 86 |
+
final_amount: float
|
| 87 |
+
profit_loss: float
|
| 88 |
+
status: str # "completed", "failed"
|
| 89 |
+
timestamp: datetime
|
| 90 |
+
details: str = ""
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
# --- Dependência de Autenticação ---
|
| 94 |
+
async def verify_aibank_key(authorization: str = Header(None)):
|
| 95 |
+
if not AIBANK_API_KEY: # Checagem se a chave do servidor está configurada
|
| 96 |
+
logger.error("CRITICAL: AIBANK_API_KEY (server-side) não está configurada nos Secrets.")
|
| 97 |
+
raise HTTPException(status_code=500, detail="Internal Server Configuration Error: Missing server API Key.")
|
| 98 |
+
|
| 99 |
+
if authorization is None:
|
| 100 |
+
logger.warning("Authorization header ausente na chamada do AIBank.")
|
| 101 |
+
raise HTTPException(status_code=401, detail="Authorization header is missing")
|
| 102 |
+
|
| 103 |
+
parts = authorization.split()
|
| 104 |
+
if len(parts) != 2 or parts[0].lower() != 'bearer':
|
| 105 |
+
logger.warning(f"Formato inválido do Authorization header: {authorization}")
|
| 106 |
+
raise HTTPException(status_code=401, detail="Authorization header must be 'Bearer <token>'")
|
| 107 |
+
|
| 108 |
+
token_from_aibank = parts[1]
|
| 109 |
+
if not hmac.compare_digest(token_from_aibank, AIBANK_API_KEY):
|
| 110 |
+
logger.warning(f"Chave de API inválida fornecida pelo AIBank. Token: {token_from_aibank[:10]}...")
|
| 111 |
+
raise HTTPException(status_code=403, detail="Invalid API Key provided by AIBank.")
|
| 112 |
+
logger.info("API Key do AIBank verificada com sucesso.")
|
| 113 |
+
return True
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
# --- Lógica de Negócio Principal (Simulada e em Background) ---
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
async def execute_investment_strategy_background(
|
| 120 |
+
rnn_tx_id: str,
|
| 121 |
+
client_id: str,
|
| 122 |
+
amount: float,
|
| 123 |
+
aibank_tx_token: str
|
| 124 |
+
):
|
| 125 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Iniciando estratégia de investimento para cliente {client_id}, valor {amount}.")
|
| 126 |
+
transactions_db[rnn_tx_id]["status"] = "processing"
|
| 127 |
+
transactions_db[rnn_tx_id]["status_details"] = "Initializing investment cycle"
|
| 128 |
+
|
| 129 |
+
final_status = "completed"
|
| 130 |
+
error_details = "" # Acumula mensagens de erro de várias etapas
|
| 131 |
+
calculated_final_amount = amount
|
| 132 |
+
|
| 133 |
+
# Inicializa a exchange ccxt usando o utilitário
|
| 134 |
+
# O logger do app.py é passado para ccxt_utils para que os logs apareçam no mesmo stream
|
| 135 |
+
exchange = await get_ccxt_exchange(logger_instance=logger) # MODIFICADO
|
| 136 |
+
|
| 137 |
+
if not exchange:
|
| 138 |
+
# get_ccxt_exchange já loga o erro. Se a exchange é crucial, podemos falhar aqui.
|
| 139 |
+
logger.warning(f"BG TASK [{rnn_tx_id}]: Falha ao inicializar a exchange. A estratégia pode não funcionar como esperado para cripto.")
|
| 140 |
+
# Se as chaves CCXT foram fornecidas no ambiente mas a exchange falhou, considere isso um erro de config.
|
| 141 |
+
if os.environ.get("CCXT_API_KEY") and os.environ.get("CCXT_API_SECRET"):
|
| 142 |
+
error_details += "Failed to initialize CCXT exchange despite API keys being present; "
|
| 143 |
+
final_status = "failed_config"
|
| 144 |
+
# (PULAR PARA CALLBACK - veja a seção de tratamento de erro crítico abaixo)
|
| 145 |
+
|
| 146 |
+
# =========================================================================
|
| 147 |
+
# 1. COLETAR DADOS DE MERCADO
|
| 148 |
+
# =========================================================================
|
| 149 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Coletando dados de mercado...")
|
| 150 |
+
transactions_db[rnn_tx_id]["status_details"] = "Fetching market data"
|
| 151 |
+
market_data_results = {"crypto": {}, "stocks": {}, "other": {}}
|
| 152 |
+
critical_data_fetch_failed = False # Flag para falha crítica na coleta de dados
|
| 153 |
+
|
| 154 |
+
# --- Coleta de dados de Cripto via ccxt_utils ---
|
| 155 |
+
if exchange:
|
| 156 |
+
crypto_pairs_to_fetch = ["BTC/USDT", "ETH/USDT", "SOL/USDT"] # Mantenha configurável
|
| 157 |
+
|
| 158 |
+
crypto_data, crypto_fetch_ok, crypto_err_msg = await fetch_crypto_data(
|
| 159 |
+
exchange,
|
| 160 |
+
crypto_pairs_to_fetch,
|
| 161 |
+
logger_instance=logger
|
| 162 |
+
)
|
| 163 |
+
market_data_results["crypto"] = crypto_data
|
| 164 |
+
if not crypto_fetch_ok:
|
| 165 |
+
error_details += f"Crypto data fetch issues: {crypto_err_msg}; "
|
| 166 |
+
# Decida se a falha na coleta de cripto é crítica
|
| 167 |
+
# Se for, defina critical_data_fetch_failed = True
|
| 168 |
+
if os.environ.get("CCXT_API_KEY"): # Se esperávamos dados de cripto
|
| 169 |
+
critical_data_fetch_failed = True
|
| 170 |
+
logger.error(f"BG TASK [{rnn_tx_id}]: Falha crítica na coleta de dados de cripto.")
|
| 171 |
+
else:
|
| 172 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Instância da exchange ccxt não disponível. Pulando coleta de dados de cripto.")
|
| 173 |
+
if os.environ.get("CCXT_API_KEY"): # Se esperávamos dados de cripto mas a exchange não inicializou
|
| 174 |
+
error_details += "CCXT exchange not initialized, crypto data skipped; "
|
| 175 |
+
critical_data_fetch_failed = True
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
# --- Coleta de dados para outros tipos de ativos (ex: Ações com yfinance) ---
|
| 179 |
+
# (Sua lógica yfinance aqui, se aplicável, similarmente atualizando market_data_results["stocks"])
|
| 180 |
+
# try:
|
| 181 |
+
# import yfinance as yf # Mova para o topo do app.py se for usar
|
| 182 |
+
# # ... lógica yfinance ...
|
| 183 |
+
# except Exception as e_yf:
|
| 184 |
+
# logger.warning(f"BG TASK [{rnn_tx_id}]: Falha ao buscar dados de ações com yfinance: {e_yf}")
|
| 185 |
+
# error_details += f"YFinance data fetch failed: {str(e_yf)}; "
|
| 186 |
+
# # Decida se isso é crítico: critical_data_fetch_failed = True
|
| 187 |
+
|
| 188 |
+
market_data_results["other"]['simulated_index_level'] = random.uniform(10000, 15000) # Mantém simulação
|
| 189 |
+
|
| 190 |
+
transactions_db[rnn_tx_id]["market_data_collected"] = market_data_results
|
| 191 |
+
|
| 192 |
+
# --- PONTO DE CHECAGEM PARA FALHA CRÍTICA NA COLETA DE DADOS ---
|
| 193 |
+
if critical_data_fetch_failed:
|
| 194 |
+
final_status = "failed_market_data"
|
| 195 |
+
logger.error(f"BG TASK [{rnn_tx_id}]: Coleta de dados de mercado falhou criticamente. {error_details}")
|
| 196 |
+
# Pular para a seção de callback
|
| 197 |
+
# (A lógica de envio do callback precisa ser alcançada)
|
| 198 |
+
else:
|
| 199 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Coleta de dados de mercado concluída.")
|
| 200 |
+
transactions_db[rnn_tx_id]["status_details"] = "Processing RNN analysis"
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
# =========================================================================
|
| 207 |
+
# 2. ANÁLISE PELA RNN E TOMADA DE DECISÃO
|
| 208 |
+
# =========================================================================
|
| 209 |
+
investment_decisions: List[Dict[str, Any]] = []
|
| 210 |
+
total_usd_allocated_by_rnn = 0.0
|
| 211 |
+
loop = asyncio.get_running_loop()
|
| 212 |
+
|
| 213 |
+
if final_status == "completed":
|
| 214 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Executando análise RNN...")
|
| 215 |
+
transactions_db[rnn_tx_id]["status_details"] = "Running RNN model"
|
| 216 |
+
rnn_analysis_success = True
|
| 217 |
+
|
| 218 |
+
# CORRIGIDO: Acessando app.state.rnn_predictor
|
| 219 |
+
predictor: Optional[RNNModelPredictor] = getattr(app.state, 'rnn_predictor', None)
|
| 220 |
+
|
| 221 |
+
try:
|
| 222 |
+
crypto_data_for_rnn = market_data_results.get("crypto", {})
|
| 223 |
+
candidate_assets = [
|
| 224 |
+
asset_key for asset_key, data in crypto_data_for_rnn.items()
|
| 225 |
+
if data and not data.get("error") and data.get("ohlcv_1h") # Apenas com dados válidos
|
| 226 |
+
]
|
| 227 |
+
|
| 228 |
+
# --- Parâmetros de Gerenciamento de Risco e Alocação (AJUSTE FINO É CRUCIAL) ---
|
| 229 |
+
# Risco total do portfólio para este ciclo (ex: não usar mais que 50% do capital total em novas posições)
|
| 230 |
+
MAX_CAPITAL_DEPLOYMENT_PCT_THIS_CYCLE = 0.75 # Usar até 75% do 'amount'
|
| 231 |
+
|
| 232 |
+
# Risco por ativo individual (percentual do 'amount' TOTAL)
|
| 233 |
+
MAX_ALLOCATION_PER_ASSET_PCT_OF_TOTAL = 0.15 # Ex: máx 15% do capital total em UM ativo
|
| 234 |
+
MIN_ALLOCATION_PER_ASSET_PCT_OF_TOTAL = 0.02 # Ex: mín 2% do capital total para valer a pena
|
| 235 |
+
|
| 236 |
+
MIN_USD_PER_ORDER = 25.00 # Mínimo de USD por ordem
|
| 237 |
+
MAX_CONCURRENT_POSITIONS = 4 # Máximo de posições abertas simultaneamente
|
| 238 |
+
|
| 239 |
+
# Limiares de Confiança da RNN
|
| 240 |
+
CONFIDENCE_STRONG_BUY = 0.80 # Confiança para considerar uma alocação maior
|
| 241 |
+
CONFIDENCE_MODERATE_BUY = 0.65 # Confiança mínima para considerar uma alocação base
|
| 242 |
+
CONFIDENCE_WEAK_BUY = 0.55 # Confiança para uma alocação muito pequena ou nenhuma
|
| 243 |
+
|
| 244 |
+
allocated_capital_this_cycle = 0.0
|
| 245 |
+
|
| 246 |
+
# Para diversificação, podemos querer limitar a avaliação ou dar pesos
|
| 247 |
+
# random.shuffle(candidate_assets)
|
| 248 |
+
|
| 249 |
+
for asset_key in candidate_assets:
|
| 250 |
+
if len(investment_decisions) >= MAX_CONCURRENT_POSITIONS:
|
| 251 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Limite de {MAX_CONCURRENT_POSITIONS} posições concorrentes atingido.")
|
| 252 |
+
break
|
| 253 |
+
|
| 254 |
+
# Verifica se já usamos o capital máximo para o ciclo
|
| 255 |
+
if allocated_capital_this_cycle >= amount * MAX_CAPITAL_DEPLOYMENT_PCT_THIS_CYCLE:
|
| 256 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Limite de capital para o ciclo ({MAX_CAPITAL_DEPLOYMENT_PCT_THIS_CYCLE*100}%) atingido.")
|
| 257 |
+
break
|
| 258 |
+
|
| 259 |
+
asset_symbol = asset_key.replace("_", "/")
|
| 260 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: RNN avaliando ativo: {asset_symbol}")
|
| 261 |
+
|
| 262 |
+
signal, confidence_prob = await predictor.predict_for_asset(
|
| 263 |
+
crypto_data_for_rnn[asset_key],
|
| 264 |
+
loop=loop
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
if signal == 1 and confidence_prob is not None: # Sinal de COMPRA e confiança válida
|
| 268 |
+
target_usd_allocation = 0.0
|
| 269 |
+
|
| 270 |
+
if confidence_prob >= CONFIDENCE_STRONG_BUY:
|
| 271 |
+
# Alocação maior para sinais fortes
|
| 272 |
+
# Ex: entre 60% e 100% da alocação máxima permitida por ativo
|
| 273 |
+
alloc_factor = 0.6 + 0.4 * ((confidence_prob - CONFIDENCE_STRONG_BUY) / (1.0 - CONFIDENCE_STRONG_BUY + 1e-6))
|
| 274 |
+
target_usd_allocation = (amount * MAX_ALLOCATION_PER_ASSET_PCT_OF_TOTAL) * alloc_factor
|
| 275 |
+
reason = f"RNN STRONG BUY signal (Conf: {confidence_prob:.3f})"
|
| 276 |
+
elif confidence_prob >= CONFIDENCE_MODERATE_BUY:
|
| 277 |
+
# Alocação base para sinais moderados
|
| 278 |
+
# Ex: entre 30% e 60% da alocação máxima permitida por ativo
|
| 279 |
+
alloc_factor = 0.3 + 0.3 * ((confidence_prob - CONFIDENCE_MODERATE_BUY) / (CONFIDENCE_STRONG_BUY - CONFIDENCE_MODERATE_BUY + 1e-6))
|
| 280 |
+
target_usd_allocation = (amount * MAX_ALLOCATION_PER_ASSET_PCT_OF_TOTAL) * alloc_factor
|
| 281 |
+
reason = f"RNN MODERATE BUY signal (Conf: {confidence_prob:.3f})"
|
| 282 |
+
elif confidence_prob >= CONFIDENCE_WEAK_BUY:
|
| 283 |
+
# Alocação pequena para sinais fracos (ou nenhuma)
|
| 284 |
+
alloc_factor = 0.1 + 0.2 * ((confidence_prob - CONFIDENCE_WEAK_BUY) / (CONFIDENCE_MODERATE_BUY - CONFIDENCE_WEAK_BUY + 1e-6))
|
| 285 |
+
target_usd_allocation = (amount * MAX_ALLOCATION_PER_ASSET_PCT_OF_TOTAL) * alloc_factor
|
| 286 |
+
reason = f"RNN WEAK BUY signal (Conf: {confidence_prob:.3f})"
|
| 287 |
+
else:
|
| 288 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Sinal COMPRA para {asset_symbol} mas confiança ({confidence_prob:.3f}) abaixo do limiar WEAK_BUY ({CONFIDENCE_WEAK_BUY}). Pulando.")
|
| 289 |
+
continue
|
| 290 |
+
|
| 291 |
+
# Garantir que a alocação não seja menor que a mínima permitida (percentual do total)
|
| 292 |
+
target_usd_allocation = max(target_usd_allocation, amount * MIN_ALLOCATION_PER_ASSET_PCT_OF_TOTAL)
|
| 293 |
+
|
| 294 |
+
# Garantir que não exceda o capital restante disponível neste CICLO
|
| 295 |
+
capital_left_for_this_cycle = (amount * MAX_CAPITAL_DEPLOYMENT_PCT_THIS_CYCLE) - allocated_capital_this_cycle
|
| 296 |
+
actual_usd_allocation = min(target_usd_allocation, capital_left_for_this_cycle)
|
| 297 |
+
|
| 298 |
+
# Garantir que a ordem mínima em USD seja respeitada
|
| 299 |
+
if actual_usd_allocation < MIN_USD_PER_ORDER:
|
| 300 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Alocação final ({actual_usd_allocation:.2f}) para {asset_symbol} abaixo do mínimo de ordem ({MIN_USD_PER_ORDER}). Pulando.")
|
| 301 |
+
continue
|
| 302 |
+
|
| 303 |
+
# Adicionar à lista de decisões
|
| 304 |
+
investment_decisions.append({
|
| 305 |
+
"asset_id": asset_symbol, "type": "CRYPTO", "action": "BUY",
|
| 306 |
+
"target_usd_amount": round(actual_usd_allocation, 2),
|
| 307 |
+
"rnn_confidence": round(confidence_prob, 4),
|
| 308 |
+
"reasoning": reason
|
| 309 |
+
})
|
| 310 |
+
allocated_capital_this_cycle += round(actual_usd_allocation, 2)
|
| 311 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Decisão: COMPRAR {actual_usd_allocation:.2f} USD de {asset_symbol}. {reason}")
|
| 312 |
+
|
| 313 |
+
# ... (restante da lógica para signal 0 ou None) ...
|
| 314 |
+
except Exception as e: # Captura exceções da lógica da RNN
|
| 315 |
+
logger.error(f"BG TASK [{rnn_tx_id}]: Erro CRÍTICO durante análise/predição RNN: {str(e)}", exc_info=True)
|
| 316 |
+
rnn_analysis_success = False # Marca que a análise RNN falhou
|
| 317 |
+
error_details += f"Critical RNN analysis/prediction error: {str(e)}; "
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
total_usd_allocated_by_rnn = allocated_capital_this_cycle
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
if not predictor or not predictor.model: # Verifica se o preditor e o modelo interno existem
|
| 326 |
+
logger.warning(f"BG TASK [{rnn_tx_id}]: Instância do preditor RNN não disponível ou modelo interno não carregado. Pulando análise RNN.")
|
| 327 |
+
rnn_analysis_success = False
|
| 328 |
+
error_details += "RNN model/predictor not available for prediction; "
|
| 329 |
+
else:
|
| 330 |
+
try:
|
| 331 |
+
# ... (lógica de iteração sobre `candidate_assets` e chamada a `predictor.predict_for_asset` como na resposta anterior)
|
| 332 |
+
# ... (lógica de alocação de capital como na resposta anterior)
|
| 333 |
+
# Garantir que toda essa lógica está dentro deste bloco 'else'
|
| 334 |
+
crypto_data_for_rnn = market_data_results.get("crypto", {})
|
| 335 |
+
candidate_assets = [
|
| 336 |
+
asset_key for asset_key, data in crypto_data_for_rnn.items()
|
| 337 |
+
if data and not data.get("error") and data.get("ohlcv_1h")
|
| 338 |
+
]
|
| 339 |
+
|
| 340 |
+
MAX_RISK_PER_ASSET_PCT = 0.05
|
| 341 |
+
MIN_USD_PER_ORDER = 20.00
|
| 342 |
+
MAX_CONCURRENT_POSITIONS = 5
|
| 343 |
+
CONFIDENCE_THRESHOLD_FOR_MAX_ALLOC = 0.85
|
| 344 |
+
CONFIDENCE_THRESHOLD_FOR_MIN_ALLOC = 0.60
|
| 345 |
+
BASE_ALLOCATION_PCT_OF_TOTAL_CAPITAL = 0.10
|
| 346 |
+
|
| 347 |
+
allocated_capital_this_cycle = 0.0
|
| 348 |
+
|
| 349 |
+
for asset_key in candidate_assets:
|
| 350 |
+
if len(investment_decisions) >= MAX_CONCURRENT_POSITIONS:
|
| 351 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Limite de posições concorrentes ({MAX_CONCURRENT_POSITIONS}) atingido.")
|
| 352 |
+
break
|
| 353 |
+
if allocated_capital_this_cycle >= amount * 0.90:
|
| 354 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Limite de capital do ciclo atingido.")
|
| 355 |
+
break
|
| 356 |
+
|
| 357 |
+
asset_symbol = asset_key.replace("_", "/")
|
| 358 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: RNN avaliando ativo: {asset_symbol}")
|
| 359 |
+
|
| 360 |
+
signal, confidence_prob = await predictor.predict_for_asset(
|
| 361 |
+
crypto_data_for_rnn[asset_key],
|
| 362 |
+
loop=loop
|
| 363 |
+
# window_size e expected_features serão os defaults de rnn_predictor.py
|
| 364 |
+
# ou podem ser passados explicitamente se você quiser variar por ativo
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
if signal == 1:
|
| 368 |
+
if confidence_prob is None or confidence_prob < CONFIDENCE_THRESHOLD_FOR_MIN_ALLOC:
|
| 369 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Sinal COMPRA para {asset_symbol} mas confiança ({confidence_prob}) abaixo do mínimo {CONFIDENCE_THRESHOLD_FOR_MIN_ALLOC}. Pulando.")
|
| 370 |
+
continue
|
| 371 |
+
|
| 372 |
+
confidence_factor = 0.5
|
| 373 |
+
if confidence_prob >= CONFIDENCE_THRESHOLD_FOR_MAX_ALLOC:
|
| 374 |
+
confidence_factor = 1.0
|
| 375 |
+
elif confidence_prob > CONFIDENCE_THRESHOLD_FOR_MIN_ALLOC:
|
| 376 |
+
confidence_factor = 0.5 + 0.5 * (
|
| 377 |
+
(confidence_prob - CONFIDENCE_THRESHOLD_FOR_MIN_ALLOC) /
|
| 378 |
+
(CONFIDENCE_THRESHOLD_FOR_MAX_ALLOC - CONFIDENCE_THRESHOLD_FOR_MIN_ALLOC)
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
potential_usd_allocation = amount * BASE_ALLOCATION_PCT_OF_TOTAL_CAPITAL * confidence_factor
|
| 382 |
+
potential_usd_allocation = min(potential_usd_allocation, amount * MAX_RISK_PER_ASSET_PCT)
|
| 383 |
+
remaining_capital_for_cycle = amount - allocated_capital_this_cycle # Recalcula a cada iteração
|
| 384 |
+
actual_usd_allocation = min(potential_usd_allocation, remaining_capital_for_cycle)
|
| 385 |
+
|
| 386 |
+
if actual_usd_allocation < MIN_USD_PER_ORDER:
|
| 387 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Alocação calculada ({actual_usd_allocation:.2f}) para {asset_symbol} abaixo do mínimo ({MIN_USD_PER_ORDER}). Pulando.")
|
| 388 |
+
continue
|
| 389 |
+
|
| 390 |
+
investment_decisions.append({
|
| 391 |
+
"asset_id": asset_symbol, "type": "CRYPTO", "action": "BUY",
|
| 392 |
+
"target_usd_amount": round(actual_usd_allocation, 2),
|
| 393 |
+
"rnn_confidence": round(confidence_prob, 4) if confidence_prob is not None else None,
|
| 394 |
+
"reasoning": f"RNN signal BUY for {asset_symbol} with confidence {confidence_prob:.2f}"
|
| 395 |
+
})
|
| 396 |
+
allocated_capital_this_cycle += round(actual_usd_allocation, 2)
|
| 397 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Decisão: COMPRAR {actual_usd_allocation:.2f} USD de {asset_symbol} (Conf: {confidence_prob:.2f})")
|
| 398 |
+
|
| 399 |
+
elif signal == 0:
|
| 400 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: RNN sinal NÃO COMPRAR para {asset_symbol} (Conf: {confidence_prob:.2f if confidence_prob is not None else 'N/A'})")
|
| 401 |
+
else:
|
| 402 |
+
logger.warning(f"BG TASK [{rnn_tx_id}]: RNN não gerou sinal para {asset_symbol}.")
|
| 403 |
+
|
| 404 |
+
if not investment_decisions:
|
| 405 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: RNN não gerou decisões de COMPRA válidas após avaliação e alocação.")
|
| 406 |
+
|
| 407 |
+
except Exception as e: # Captura exceções da lógica da RNN
|
| 408 |
+
logger.error(f"BG TASK [{rnn_tx_id}]: Erro CRÍTICO durante análise/predição RNN: {str(e)}", exc_info=True)
|
| 409 |
+
rnn_analysis_success = False # Marca que a análise RNN falhou
|
| 410 |
+
error_details += f"Critical RNN analysis/prediction error: {str(e)}; "
|
| 411 |
+
|
| 412 |
+
if not rnn_analysis_success: # Se a flag foi setada para False
|
| 413 |
+
final_status = "failed_rnn_analysis"
|
| 414 |
+
|
| 415 |
+
transactions_db[rnn_tx_id]["rnn_decisions"] = investment_decisions
|
| 416 |
+
|
| 417 |
+
total_usd_allocated_by_rnn = allocated_capital_this_cycle
|
| 418 |
+
transactions_db[rnn_tx_id]["status_details"] = "Preparing to execute orders"
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
# =========================================================================
|
| 430 |
+
# 3. EXECUÇÃO DE ORDENS (Só executa se a RNN não falhou e gerou ordens)
|
| 431 |
+
# =========================================================================
|
| 432 |
+
executed_trades_info: List[Dict[str, Any]] = []
|
| 433 |
+
current_portfolio_value = 0.0 # Valor dos ativos comprados, baseado no custo
|
| 434 |
+
cash_remaining_after_execution = amount # Começa com todo o montante
|
| 435 |
+
|
| 436 |
+
if final_status == "completed" and investment_decisions and exchange:
|
| 437 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Executando {len(investment_decisions)} ordens...")
|
| 438 |
+
transactions_db[rnn_tx_id]["status_details"] = "Executing investment orders"
|
| 439 |
+
order_execution_overall_success = True
|
| 440 |
+
|
| 441 |
+
# Placeholder para LÓGICA REAL DE EXECUÇÃO DE ORDENS (CREATE_ORDER_PLACEHOLDER)
|
| 442 |
+
# Esta seção precisa ser preenchida com:
|
| 443 |
+
# 1. Iterar sobre `investment_decisions`.
|
| 444 |
+
# 2. Para cada decisão de "BUY":
|
| 445 |
+
# a. Determinar o símbolo correto na exchange (ex: "BTC/USDT").
|
| 446 |
+
# b. Obter o preço atual (ticker) para calcular a quantidade de ativo a comprar.
|
| 447 |
+
# `amount_of_asset = target_usd_amount / current_price_of_asset`
|
| 448 |
+
# c. Considerar saldo disponível na exchange (se estiver gerenciando isso).
|
| 449 |
+
# d. Criar a ordem via `await exchange.create_market_buy_order(symbol, amount_of_asset)`
|
| 450 |
+
# ou `create_limit_buy_order(symbol, amount_of_asset, limit_price)`.
|
| 451 |
+
# Para ordens limite, a RNN precisaria fornecer o `limit_price`.
|
| 452 |
+
# e. Tratar respostas da exchange (sucesso, falha, ID da ordem).
|
| 453 |
+
# `ccxt.InsufficientFunds`, `ccxt.InvalidOrder`, etc.
|
| 454 |
+
# f. Armazenar detalhes da ordem em `executed_trades_info`:
|
| 455 |
+
# { "asset_id": ..., "order_id_exchange": ..., "type": "market/limit", "side": "buy",
|
| 456 |
+
# "requested_usd_amount": ..., "asset_quantity_ordered": ...,
|
| 457 |
+
# "status_from_exchange": ..., "filled_quantity": ..., "average_fill_price": ...,
|
| 458 |
+
# "cost_in_usd": ..., "fees_paid": ..., "timestamp": ... }
|
| 459 |
+
# g. Atualizar `current_portfolio_value` com o `cost_in_usd` da ordem preenchida.
|
| 460 |
+
# h. Deduzir `cost_in_usd` de `cash_remaining_after_execution`.
|
| 461 |
+
# 3. Para decisões de "SELL" (se sua RNN gerar):
|
| 462 |
+
# a. Verificar se você possui o ativo (requer gerenciamento de portfólio).
|
| 463 |
+
# b. Criar ordem de venda.
|
| 464 |
+
# c. Atualizar `current_portfolio_value` e `cash_remaining_after_execution`.
|
| 465 |
+
|
| 466 |
+
# Simulação atual:
|
| 467 |
+
for decision in investment_decisions:
|
| 468 |
+
if decision.get("action") == "BUY" and decision.get("type") == "CRYPTO":
|
| 469 |
+
asset_symbol = decision["asset_id"]
|
| 470 |
+
usd_to_spend = decision["target_usd_amount"]
|
| 471 |
+
|
| 472 |
+
# Simular pequena chance de falha na ordem
|
| 473 |
+
if random.random() < 0.05:
|
| 474 |
+
logger.warning(f"BG TASK [{rnn_tx_id}]: Falha simulada ao executar ordem para {asset_symbol}.")
|
| 475 |
+
executed_trades_info.append({
|
| 476 |
+
"asset_id": asset_symbol, "status": "failed_simulated",
|
| 477 |
+
"requested_usd_amount": usd_to_spend, "error": "Simulated exchange rejection"
|
| 478 |
+
})
|
| 479 |
+
order_execution_overall_success = False # Marca que pelo menos uma falhou
|
| 480 |
+
continue # Pula para a próxima decisão
|
| 481 |
+
|
| 482 |
+
# Simular slippage e custo
|
| 483 |
+
simulated_cost = usd_to_spend * random.uniform(0.995, 1.005) # +/- 0.5% slippage
|
| 484 |
+
|
| 485 |
+
# Garantir que não estamos gastando mais do que o caixa restante
|
| 486 |
+
if simulated_cost > cash_remaining_after_execution:
|
| 487 |
+
simulated_cost = cash_remaining_after_execution # Gasta apenas o que tem
|
| 488 |
+
if simulated_cost < 1: # Se não há quase nada, não faz a ordem
|
| 489 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Saldo insuficiente ({cash_remaining_after_execution:.2f}) para ordem de {asset_symbol}, pulando.")
|
| 490 |
+
continue
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
if simulated_cost > 0:
|
| 494 |
+
current_portfolio_value += simulated_cost
|
| 495 |
+
cash_remaining_after_execution -= simulated_cost
|
| 496 |
+
executed_trades_info.append({
|
| 497 |
+
"asset_id": asset_symbol, "order_id_exchange": f"sim_ord_{uuid.uuid4()}",
|
| 498 |
+
"type": "market", "side": "buy",
|
| 499 |
+
"requested_usd_amount": usd_to_spend,
|
| 500 |
+
"status_from_exchange": "filled", "cost_in_usd": round(simulated_cost, 2),
|
| 501 |
+
"timestamp": datetime.utcnow().isoformat()
|
| 502 |
+
})
|
| 503 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Ordem simulada para {asset_symbol} (custo: {simulated_cost:.2f} USD) preenchida.")
|
| 504 |
+
|
| 505 |
+
await asyncio.sleep(random.uniform(1, 2) * len(investment_decisions) if investment_decisions else 1)
|
| 506 |
+
|
| 507 |
+
if not order_execution_overall_success:
|
| 508 |
+
error_details += "One or more orders failed during execution; "
|
| 509 |
+
# Decida se isso torna o status final 'failed_order_execution' ou se 'completed_with_partial_failure'
|
| 510 |
+
# final_status = "completed_with_partial_failure" # Exemplo de um novo status
|
| 511 |
+
|
| 512 |
+
elif not exchange and investment_decisions:
|
| 513 |
+
logger.warning(f"BG TASK [{rnn_tx_id}]: Decisões de investimento geradas, mas a exchange não está disponível para execução.")
|
| 514 |
+
error_details += "Exchange not available for order execution; "
|
| 515 |
+
final_status = "failed_order_execution" # Se a execução é crítica
|
| 516 |
+
cash_remaining_after_execution = amount # Nada foi gasto
|
| 517 |
+
|
| 518 |
+
transactions_db[rnn_tx_id]["executed_trades"] = executed_trades_info
|
| 519 |
+
transactions_db[rnn_tx_id]["cash_after_execution"] = round(cash_remaining_after_execution, 2)
|
| 520 |
+
transactions_db[rnn_tx_id]["portfolio_value_after_execution"] = round(current_portfolio_value, 2)
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
# =========================================================================
|
| 524 |
+
# 4. SIMULAÇÃO DO PERÍODO DE INVESTIMENTO E CÁLCULO DE LUCRO/PERDA (Só se não houve falha crítica antes)
|
| 525 |
+
# =========================================================================
|
| 526 |
+
value_of_investments_at_eod = current_portfolio_value # Começa com o valor de custo
|
| 527 |
+
|
| 528 |
+
if final_status == "completed": # Ou "completed_with_partial_failure"
|
| 529 |
+
transactions_db[rnn_tx_id]["status_details"] = "Simulating EOD valuation"
|
| 530 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Simulando valorização do portfólio no final do dia...")
|
| 531 |
+
await asyncio.sleep(random.uniform(3, 7))
|
| 532 |
+
|
| 533 |
+
if current_portfolio_value > 0:
|
| 534 |
+
# Simular mudança de valor do portfólio. A meta de 4.2% é sobre o capital INVESTIDO.
|
| 535 |
+
# O lucro/perda é aplicado ao `current_portfolio_value` (o que foi efetivamente comprado).
|
| 536 |
+
daily_return_factor = 0.042 # A meta
|
| 537 |
+
simulated_performance_factor = random.uniform(0.7, 1.3) # Variação em torno da meta (pode ser prejuízo)
|
| 538 |
+
# Para ser mais realista, o fator de performance deveria ser algo como:
|
| 539 |
+
# random.uniform(-0.05, 0.08) -> -5% a +8% de retorno diário sobre o investido (ainda alto)
|
| 540 |
+
# E não diretamente ligado à meta de 4.2%
|
| 541 |
+
|
| 542 |
+
# Ajuste para uma simulação de retorno mais plausível (ainda agressiva)
|
| 543 |
+
# Suponha que o retorno diário real possa variar de -3% a +5% sobre o investido
|
| 544 |
+
actual_daily_return_on_portfolio = random.uniform(-0.03, 0.05)
|
| 545 |
+
|
| 546 |
+
profit_or_loss_on_portfolio = current_portfolio_value * actual_daily_return_on_portfolio
|
| 547 |
+
value_of_investments_at_eod = current_portfolio_value + profit_or_loss_on_portfolio
|
| 548 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Portfólio inicial: {current_portfolio_value:.2f}, Retorno simulado: {actual_daily_return_on_portfolio*100:.2f}%, "
|
| 549 |
+
f"Lucro/Prejuízo no portfólio: {profit_or_loss_on_portfolio:.2f}, Valor EOD do portfólio: {value_of_investments_at_eod:.2f}")
|
| 550 |
+
else:
|
| 551 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Nenhum portfólio para valorizar no EOD (nada foi comprado).")
|
| 552 |
+
value_of_investments_at_eod = 0.0
|
| 553 |
+
|
| 554 |
+
# O calculated_final_amount é o valor dos investimentos liquidados + o caixa que não foi usado
|
| 555 |
+
calculated_final_amount = value_of_investments_at_eod + cash_remaining_after_execution
|
| 556 |
+
|
| 557 |
+
else: # Se houve falha antes, o valor final é o que sobrou após a falha
|
| 558 |
+
calculated_final_amount = cash_remaining_after_execution + current_portfolio_value # current_portfolio_value pode ser 0 ou parcial
|
| 559 |
+
logger.warning(f"BG TASK [{rnn_tx_id}]: Ciclo de investimento não concluído normalmente ({final_status}). Valor final baseado no estado atual.")
|
| 560 |
+
|
| 561 |
+
transactions_db[rnn_tx_id]["eod_portfolio_value_simulated"] = round(value_of_investments_at_eod, 2)
|
| 562 |
+
transactions_db[rnn_tx_id]["final_calculated_amount"] = round(calculated_final_amount, 2)
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
# =========================================================================
|
| 566 |
+
# 5. TOKENIZAÇÃO / REGISTRO DA OPERAÇÃO (Só se não houve falha crítica antes)
|
| 567 |
+
# =========================================================================
|
| 568 |
+
if final_status not in ["failed_config", "failed_market_data", "failed_rnn_analysis"]: # Prossegue se ao menos tentou executar
|
| 569 |
+
transactions_db[rnn_tx_id]["status_details"] = "Finalizing transaction log (tokenization)"
|
| 570 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Registrando (tokenizando) operação detalhadamente...")
|
| 571 |
+
# Placeholder para LÓGICA REAL DE TOKENIZAÇÃO (TOKENIZATION_PLACEHOLDER)
|
| 572 |
+
# 1. Coletar todos os dados relevantes da transação de `transactions_db[rnn_tx_id]`
|
| 573 |
+
# (market_data_collected, rnn_decisions, executed_trades, eod_portfolio_value_simulated, etc.)
|
| 574 |
+
# 2. Se for usar blockchain:
|
| 575 |
+
# a. Preparar os dados para um contrato inteligente.
|
| 576 |
+
# b. Interagir com o contrato (ex: web3.py para Ethereum).
|
| 577 |
+
# c. Armazenar o hash da transação da blockchain.
|
| 578 |
+
# 3. Se for um registro interno avançado:
|
| 579 |
+
# a. Assinar digitalmente os dados da transação.
|
| 580 |
+
# b. Armazenar em um sistema de log imutável ou banco de dados com auditoria.
|
| 581 |
+
|
| 582 |
+
# Simulação atual (hash dos dados da transação):
|
| 583 |
+
transaction_data_for_hash = {
|
| 584 |
+
"rnn_tx_id": rnn_tx_id, "client_id": client_id, "initial_amount": amount,
|
| 585 |
+
"final_amount_calculated": calculated_final_amount,
|
| 586 |
+
# Incluir resumos ou hashes dos dados coletados para não tornar o hash gigante
|
| 587 |
+
"market_data_summary_keys": list(transactions_db[rnn_tx_id].get("market_data_collected", {}).keys()),
|
| 588 |
+
"rnn_decisions_count": len(transactions_db[rnn_tx_id].get("rnn_decisions", [])),
|
| 589 |
+
"executed_trades_count": len(transactions_db[rnn_tx_id].get("executed_trades", [])),
|
| 590 |
+
"eod_portfolio_value": transactions_db[rnn_tx_id].get("eod_portfolio_value_simulated"),
|
| 591 |
+
"timestamp": datetime.utcnow().isoformat()
|
| 592 |
+
}
|
| 593 |
+
ordered_tx_data_str = json.dumps(transaction_data_for_hash, sort_keys=True)
|
| 594 |
+
proof_token_hash = hashlib.sha256(ordered_tx_data_str.encode('utf-8')).hexdigest()
|
| 595 |
+
|
| 596 |
+
transactions_db[rnn_tx_id]["proof_of_operation_token"] = proof_token_hash
|
| 597 |
+
transactions_db[rnn_tx_id]["tokenization_method"] = "internal_summary_hash_proof"
|
| 598 |
+
await asyncio.sleep(0.5) # Simula tempo de escrita/hash
|
| 599 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Operação registrada. Prova (hash): {proof_token_hash[:10]}...")
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
# =========================================================================
|
| 603 |
+
# 6. PREPARAR E ENVIAR CALLBACK PARA AIBANK
|
| 604 |
+
# =========================================================================
|
| 605 |
+
if exchange and hasattr(exchange, 'close'):
|
| 606 |
+
try:
|
| 607 |
+
await exchange.close()
|
| 608 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Conexão ccxt fechada.")
|
| 609 |
+
except Exception as e_close: # Especificar o tipo de exceção se souber
|
| 610 |
+
logger.warning(f"BG TASK [{rnn_tx_id}]: Erro ao fechar conexão ccxt: {str(e_close)}")
|
| 611 |
+
|
| 612 |
+
if not AIBANK_CALLBACK_URL or not CALLBACK_SHARED_SECRET:
|
| 613 |
+
logger.error(f"BG TASK [{rnn_tx_id}]: Configuração de callback ausente. Não é possível notificar o AIBank.")
|
| 614 |
+
transactions_db[rnn_tx_id]["callback_status"] = "config_missing_critical"
|
| 615 |
+
return
|
| 616 |
+
|
| 617 |
+
# Certifique-se que `final_status` reflete o estado real da operação
|
| 618 |
+
# Se `error_details` não estiver vazio e `final_status` ainda for "completed", ajuste-o
|
| 619 |
+
if error_details and final_status == "completed":
|
| 620 |
+
final_status = "completed_with_warnings" # Ou um status mais apropriado
|
| 621 |
+
|
| 622 |
+
callback_payload_data = InvestmentResultPayload(
|
| 623 |
+
rnn_transaction_id=rnn_tx_id, aibank_transaction_token=aibank_tx_token, client_id=client_id,
|
| 624 |
+
initial_amount=amount, final_amount=round(calculated_final_amount, 2), # Arredonda para 2 casas decimais
|
| 625 |
+
profit_loss=round(calculated_final_amount - amount, 2),
|
| 626 |
+
status=final_status, timestamp=datetime.utcnow(),
|
| 627 |
+
details=error_details if error_details else "Investment cycle processed."
|
| 628 |
+
)
|
| 629 |
+
payload_json_str = callback_payload_data.model_dump_json() # Garante que está usando a string serializada
|
| 630 |
+
|
| 631 |
+
signature = hmac.new(CALLBACK_SHARED_SECRET.encode('utf-8'), payload_json_str.encode('utf-8'), hashlib.sha256).hexdigest()
|
| 632 |
+
headers = {'Content-Type': 'application/json', 'X-RNN-Signature': signature}
|
| 633 |
+
|
| 634 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Enviando callback para AIBank ({AIBANK_CALLBACK_URL}) com status final '{final_status}'. Payload: {payload_json_str}")
|
| 635 |
+
transactions_db[rnn_tx_id]["callback_status"] = "sending"
|
| 636 |
+
try:
|
| 637 |
+
async with httpx.AsyncClient(timeout=30.0) as client: # Timeout global para o cliente
|
| 638 |
+
response = await client.post(AIBANK_CALLBACK_URL, content=payload_json_str, headers=headers)
|
| 639 |
+
response.raise_for_status()
|
| 640 |
+
logger.info(f"BG TASK [{rnn_tx_id}]: Callback para AIBank enviado com sucesso. Resposta: {response.status_code}")
|
| 641 |
+
transactions_db[rnn_tx_id]["callback_status"] = f"sent_success_{response.status_code}"
|
| 642 |
+
except httpx.RequestError as e_req:
|
| 643 |
+
logger.error(f"BG TASK [{rnn_tx_id}]: Erro de REDE ao enviar callback para AIBank: {e_req}")
|
| 644 |
+
transactions_db[rnn_tx_id]["callback_status"] = "sent_failed_network_error"
|
| 645 |
+
except httpx.HTTPStatusError as e_http:
|
| 646 |
+
logger.error(f"BG TASK [{rnn_tx_id}]: Erro HTTP do AIBank ao receber callback: {e_http.response.status_code} - {e_http.response.text[:200]}")
|
| 647 |
+
transactions_db[rnn_tx_id]["callback_status"] = f"sent_failed_http_error_{e_http.response.status_code}"
|
| 648 |
+
except Exception as e_cb_final:
|
| 649 |
+
logger.error(f"BG TASK [{rnn_tx_id}]: Erro INESPERADO ao enviar callback: {e_cb_final}", exc_info=True)
|
| 650 |
+
transactions_db[rnn_tx_id]["callback_status"] = "sent_failed_unknown_error"
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
import asyncio
|
| 654 |
+
import random
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
|
| 658 |
+
# --- Endpoints da API ---
|
| 659 |
+
@app.post("/api/invest",
|
| 660 |
+
response_model=InvestmentResponse,
|
| 661 |
+
dependencies=[Depends(verify_aibank_key)])
|
| 662 |
+
async def initiate_investment(
|
| 663 |
+
request_data: InvestmentRequest,
|
| 664 |
+
background_tasks: BackgroundTasks
|
| 665 |
+
):
|
| 666 |
+
"""
|
| 667 |
+
Endpoint para o AIBank iniciar um ciclo de investimento.
|
| 668 |
+
Responde rapidamente e executa a lógica pesada em background.
|
| 669 |
+
"""
|
| 670 |
+
logger.info(f"Requisição de investimento recebida para client_id: {request_data.client_id}, "
|
| 671 |
+
f"amount: {request_data.amount}, aibank_tx_token: {request_data.aibank_transaction_token}")
|
| 672 |
+
|
| 673 |
+
rnn_tx_id = str(uuid.uuid4())
|
| 674 |
+
|
| 675 |
+
# Armazena informações iniciais da transação DB real para ser mais robusto
|
| 676 |
+
transactions_db[rnn_tx_id] = {
|
| 677 |
+
"rnn_transaction_id": rnn_tx_id,
|
| 678 |
+
"aibank_transaction_token": request_data.aibank_transaction_token,
|
| 679 |
+
"client_id": request_data.client_id,
|
| 680 |
+
"initial_amount": request_data.amount,
|
| 681 |
+
"status": "pending_background_processing",
|
| 682 |
+
"received_at": datetime.utcnow().isoformat(),
|
| 683 |
+
"callback_status": "not_sent_yet"
|
| 684 |
+
}
|
| 685 |
+
|
| 686 |
+
# Adiciona a tarefa de longa duração ao background
|
| 687 |
+
background_tasks.add_task(
|
| 688 |
+
execute_investment_strategy_background,
|
| 689 |
+
rnn_tx_id,
|
| 690 |
+
request_data.client_id,
|
| 691 |
+
request_data.amount,
|
| 692 |
+
request_data.aibank_transaction_token
|
| 693 |
+
)
|
| 694 |
+
|
| 695 |
+
logger.info(f"Estratégia de investimento para rnn_tx_id: {rnn_tx_id} agendada para execução em background.")
|
| 696 |
+
return InvestmentResponse(
|
| 697 |
+
status="pending",
|
| 698 |
+
message="Investment request received and is being processed in the background. Await callback for results.",
|
| 699 |
+
rnn_transaction_id=rnn_tx_id
|
| 700 |
+
)
|
| 701 |
+
|
| 702 |
+
@app.get("/api/transaction_status/{rnn_tx_id}", response_class=JSONResponse)
|
| 703 |
+
async def get_transaction_status(rnn_tx_id: str):
|
| 704 |
+
""" Endpoint para verificar o status de uma transação (para debug/admin) """
|
| 705 |
+
transaction = transactions_db.get(rnn_tx_id)
|
| 706 |
+
if not transaction:
|
| 707 |
+
raise HTTPException(status_code=404, detail="Transaction not found")
|
| 708 |
+
return transaction
|
| 709 |
+
|
| 710 |
+
|
| 711 |
+
# --- Dashboard (Existente, adaptado) ---
|
| 712 |
+
# Setup para arquivos estáticos e templates
|
| 713 |
+
|
| 714 |
+
try:
|
| 715 |
+
app.mount("/static", StaticFiles(directory="rnn/static"), name="static")
|
| 716 |
+
templates = Environment(loader=FileSystemLoader("rnn/templates"))
|
| 717 |
+
except RuntimeError as e:
|
| 718 |
+
logger.warning(f"Não foi possível montar /static ou carregar templates: {e}. O dashboard pode não funcionar.")
|
| 719 |
+
templates = None # Para evitar erros se o loader falhar
|
| 720 |
+
|
| 721 |
+
@app.get("/", response_class=HTMLResponse)
|
| 722 |
+
async def index(request: Request):
|
| 723 |
+
if not templates:
|
| 724 |
+
return HTMLResponse("<html><body><h1>Dashboard indisponível</h1><p>Configuração de templates/estáticos falhou.</p></body></html>")
|
| 725 |
+
|
| 726 |
+
agora = datetime.now()
|
| 727 |
+
agentes_simulados = [
|
| 728 |
+
# dados de agentes ...
|
| 729 |
+
]
|
| 730 |
+
template = templates.get_template("index.html")
|
| 731 |
+
# Adicionar transações recentes ao contexto do template
|
| 732 |
+
recent_txs = list(transactions_db.values())[-5:] # Últimas 5 transações
|
| 733 |
+
return HTMLResponse(template.render(request=request, agentes=agentes_simulados, transactions=recent_txs))
|
| 734 |
+
|
| 735 |
+
# --- Imports para Background Task ---
|
| 736 |
+
import asyncio
|
| 737 |
+
import random
|
| 738 |
+
|
| 739 |
+
# Função de logger dummy
|
| 740 |
+
# class DummyLogger:
|
| 741 |
+
# def info(self, msg, *args, **kwargs): print(f"INFO: {msg}")
|
| 742 |
+
# def warning(self, msg, *args, **kwargs): print(f"WARNING: {msg}")
|
| 743 |
+
# def error(self, msg, *args, **kwargs): print(f"ERROR: {msg}", kwargs.get('exc_info'))
|
| 744 |
+
|
| 745 |
+
# if __name__ == "__main__": # Para teste local
|
| 746 |
+
# # logger = DummyLogger() # se não tiver get_logger()
|
| 747 |
+
# # Configuração das variáveis de ambiente para teste local
|
| 748 |
+
# os.environ["AIBANK_API_KEY"] = "test_aibank_key_from_rnn_server"
|
| 749 |
+
# os.environ["AIBANK_CALLBACK_URL"] = "http://localhost:8001/api/rnn_investment_result_callback" # URL do aibank simulado
|
| 750 |
+
# os.environ["CALLBACK_SHARED_SECRET"] = "super_secret_for_callback_signing"
|
| 751 |
+
# # import uvicorn
|
| 752 |
# # uvicorn.run(app, host="0.0.0.0", port=8000)
|
graficos_tese/figura_1.png
ADDED
|
graficos_tese/figura_2.png
ADDED
|
graficos_tese/figura_3.png
ADDED
|
graficos_tese/figura_3_1.png
ADDED
|
graficos_tese/figura_4.png
ADDED
|
ppo_deep_portfolio_tensorboard/PPO_1/events.out.tfevents.1750765461.verticalagent-X555LPB.73418.0
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7789699c28d5982a526892f3fd60ffb5200399a931f6212791cce45905096145
|
| 3 |
+
size 88
|
scripts/gerador_de_grafico.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import matplotlib.pyplot as plt
|
| 2 |
+
import seaborn as sns
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
# Criar pasta para salvar os gráficos
|
| 7 |
+
output_dir = "graficos_tese"
|
| 8 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 9 |
+
|
| 10 |
+
# ============================
|
| 11 |
+
# Figura 1 – Endividamento vs. Inadimplência
|
| 12 |
+
# ============================
|
| 13 |
+
anos = list(range(2005, 2025))
|
| 14 |
+
endividamento = [46, 49, 53, 56, 58, 59, 59.8, 61, 62.5, 64.3, 66.5, 68.1, 70, 71.4, 72.8, 74.3, 76.1, 77.9, 78.5, 78.5]
|
| 15 |
+
inadimplencia = [6.2, 6.4, 6.8, 7.1, 7.3, 7.9, 8.1, 8.4, 9.1, 9.7, 10.3, 10.9, 11.3, 11.7, 12.1, 12.3, 12.4, 12.6, 12.7, 12.7]
|
| 16 |
+
|
| 17 |
+
fig, ax1 = plt.subplots(figsize=(10, 6))
|
| 18 |
+
ax1.plot(anos, endividamento, 'b-', label='Famílias Endividadas (%)')
|
| 19 |
+
ax2 = ax1.twinx()
|
| 20 |
+
ax2.plot(anos, inadimplencia, 'r-', label='Inadimplência (%)')
|
| 21 |
+
|
| 22 |
+
ax1.set_xlabel('Ano')
|
| 23 |
+
ax1.set_ylabel('Endividamento (%)', color='blue')
|
| 24 |
+
ax2.set_ylabel('Inadimplência (%)', color='red')
|
| 25 |
+
plt.title('Figura 1 – Evolução da Inadimplência e Endividamento (2005–2024)')
|
| 26 |
+
fig.tight_layout()
|
| 27 |
+
plt.savefig(f"{output_dir}/figura_1.png")
|
| 28 |
+
plt.close()
|
| 29 |
+
|
| 30 |
+
# ============================
|
| 31 |
+
# Figura 2 – Comparativo Internacional de Spread Bancário
|
| 32 |
+
# ============================
|
| 33 |
+
spread_data = pd.DataFrame({
|
| 34 |
+
'País': ['Brasil', 'Chile', 'México', 'Índia', 'EUA'],
|
| 35 |
+
'Spread (%)': [30.2, 12.4, 9.8, 7.1, 3.5]
|
| 36 |
+
})
|
| 37 |
+
plt.figure(figsize=(8, 5))
|
| 38 |
+
sns.barplot(x='Spread (%)', y='País', data=spread_data, palette='flare')
|
| 39 |
+
plt.title('Figura 2 – Spread Bancário por País (2024)')
|
| 40 |
+
plt.tight_layout()
|
| 41 |
+
plt.savefig(f"{output_dir}/figura_2.png")
|
| 42 |
+
plt.close()
|
| 43 |
+
|
| 44 |
+
# ============================
|
| 45 |
+
# Figura 3 – Comprometimento da Renda com Dívidas
|
| 46 |
+
# ============================
|
| 47 |
+
comp_renda = [18.2, 19.4, 20.6, 21.2, 22.5, 23.1, 24.4, 25.3, 26.7, 27.9, 28.7, 29.4, 30.1, 30.2, 30.5, 30.6, 30.6, 30.6, 30.6, 30.6]
|
| 48 |
+
plt.figure(figsize=(9, 5))
|
| 49 |
+
plt.plot(anos, comp_renda, color='darkgreen', marker='o')
|
| 50 |
+
plt.title('Figura 3 – Comprometimento da Renda Familiar com Dívidas (2005–2024)')
|
| 51 |
+
plt.xlabel('Ano')
|
| 52 |
+
plt.ylabel('Comprometimento (%)')
|
| 53 |
+
plt.grid(True)
|
| 54 |
+
plt.tight_layout()
|
| 55 |
+
plt.savefig(f"{output_dir}/figura_3.png")
|
| 56 |
+
plt.close()
|
| 57 |
+
|
| 58 |
+
# ============================
|
| 59 |
+
# Figura 4 – SELIC, IPCA e Inadimplência
|
| 60 |
+
# ============================
|
| 61 |
+
df_macro = pd.DataFrame({
|
| 62 |
+
'Ano': [2010, 2015, 2020, 2022, 2024],
|
| 63 |
+
'SELIC (%)': [10.75, 14.25, 2.0, 13.75, 10.5],
|
| 64 |
+
'IPCA (%)': [5.91, 10.67, 4.52, 5.79, 5.8],
|
| 65 |
+
'Inadimplência (%)': [6.2, 8.1, 11.3, 12.1, 12.7]
|
| 66 |
+
})
|
| 67 |
+
df_macro.set_index('Ano', inplace=True)
|
| 68 |
+
df_macro.plot(marker='o', figsize=(10, 6))
|
| 69 |
+
plt.title('Figura 2 – SELIC, IPCA e Inadimplência no Brasil (2010–2024)')
|
| 70 |
+
plt.ylabel('Percentual (%)')
|
| 71 |
+
plt.grid(True)
|
| 72 |
+
plt.tight_layout()
|
| 73 |
+
plt.savefig(f"{output_dir}/figura_2.png")
|
| 74 |
+
plt.close()
|
| 75 |
+
|
| 76 |
+
# Você pode adicionar outros gráficos aqui com a mesma estrutura...
|
| 77 |
+
|
| 78 |
+
print(f"✅ Gráficos salvos com sucesso em: ./{output_dir}/")
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
import seaborn as sns
|
| 84 |
+
import matplotlib.pyplot as plt
|
| 85 |
+
import pandas as pd
|
| 86 |
+
|
| 87 |
+
data = pd.DataFrame({
|
| 88 |
+
'País': ['Brasil', 'Chile', 'México', 'Índia', 'EUA'],
|
| 89 |
+
'Spread Bancário (%)': [30.2, 12.4, 9.8, 7.1, 3.5]
|
| 90 |
+
})
|
| 91 |
+
|
| 92 |
+
plt.figure(figsize=(8, 5))
|
| 93 |
+
sns.barplot(x='Spread Bancário (%)', y='País', data=data, palette='flare')
|
| 94 |
+
plt.title('Comparativo de Spread Bancário Internacional (2024)')
|
| 95 |
+
plt.xlabel('Spread (%)')
|
| 96 |
+
plt.tight_layout()
|
| 97 |
+
plt.savefig(f"{output_dir}/figura_2.png")
|
| 98 |
+
|
| 99 |
+
plt.show()
|
| 100 |
+
plt.close()
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
#------
|
| 105 |
+
|
| 106 |
+
import matplotlib.pyplot as plt
|
| 107 |
+
import pandas as pd
|
| 108 |
+
import os
|
| 109 |
+
|
| 110 |
+
# Criar diretório para salvar
|
| 111 |
+
output_dir = "graficos_tese"
|
| 112 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 113 |
+
|
| 114 |
+
# Dados simulados com base em fontes públicas (ajuste conforme necessário)
|
| 115 |
+
anos = list(range(2005, 2024))
|
| 116 |
+
crescimento_credito = [15.2, 17.8, 20.1, 18.5, 16.3, 14.7, 13.2, 12.5, 11.1, 10.4, 9.8, 8.6, 7.9, 6.5, 5.2, 6.1, 7.4, 8.2, 9.1]
|
| 117 |
+
crescimento_pib = [3.2, 4.0, 6.1, 5.2, -0.1, 7.5, 3.9, 1.9, 3.0, 0.5, -3.5, -3.3, 1.3, 1.8, 1.1, -4.1, 4.6, 2.9, 2.3]
|
| 118 |
+
|
| 119 |
+
# Criar DataFrame
|
| 120 |
+
df = pd.DataFrame({
|
| 121 |
+
'Ano': anos,
|
| 122 |
+
'Crescimento do Crédito (%)': crescimento_credito,
|
| 123 |
+
'Crescimento do PIB (%)': crescimento_pib
|
| 124 |
+
})
|
| 125 |
+
|
| 126 |
+
# Plotar gráfico
|
| 127 |
+
plt.figure(figsize=(10, 6))
|
| 128 |
+
plt.plot(df['Ano'], df['Crescimento do Crédito (%)'], label='Crescimento do Crédito (%)', marker='o', color='blue')
|
| 129 |
+
plt.plot(df['Ano'], df['Crescimento do PIB (%)'], label='Crescimento do PIB (%)', marker='s', color='green')
|
| 130 |
+
plt.title('Figura 3.1 – Correlação entre Crescimento do Crédito e PIB Real (2005–2023)')
|
| 131 |
+
plt.xlabel('Ano')
|
| 132 |
+
plt.ylabel('Variação (%)')
|
| 133 |
+
plt.grid(True)
|
| 134 |
+
plt.legend()
|
| 135 |
+
plt.tight_layout()
|
| 136 |
+
plt.savefig(f"{output_dir}/figura_3_1.png")
|
| 137 |
+
plt.close()
|
| 138 |
+
|
| 139 |
+
print(f"✅ Figura 3.1 salva com sucesso em: ./{output_dir}/figura_3_1.png")
|
scripts/train_rl_portfolio_agent.py
CHANGED
|
@@ -65,7 +65,7 @@ model_ppo = PPO("MlpLstmPolicy", env, verbose=1, tensorboard_log="./ppo_portfoli
|
|
| 65 |
|
| 66 |
# 4. Treinar o Agente
|
| 67 |
print("Iniciando treinamento do agente PPO...")
|
| 68 |
-
model_ppo.learn(total_timesteps=
|
| 69 |
|
| 70 |
# 5. Salvar o Modelo Treinado
|
| 71 |
model_ppo.save("rl_models/ppo_deep_portfolio_agent")
|
|
|
|
| 65 |
|
| 66 |
# 4. Treinar o Agente
|
| 67 |
print("Iniciando treinamento do agente PPO...")
|
| 68 |
+
model_ppo.learn(total_timesteps=1000000, progress_bar=True) # Aumente timesteps para treino real
|
| 69 |
|
| 70 |
# 5. Salvar o Modelo Treinado
|
| 71 |
model_ppo.save("rl_models/ppo_deep_portfolio_agent")
|