-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTakashiKotegaModel.py
166 lines (141 loc) · 6.34 KB
/
TakashiKotegaModel.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# TakashiKotegaModel.py
# Version: 1.0.0
# Author: David C Cavalcante <[email protected]>
# Homepage: https://www.linkedin.com/in/hellodav/
# Standard library imports
import os
import logging
# Third-party imports
import joblib
import numpy as np
import pandas as pd
from sklearn.ensemble import IsolationForest
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from ta.momentum import RSIIndicator
from ta.volatility import AverageTrueRange
class KotegawaTradingModel:
# NÍVEL 3: FUNÇÃO UTILITÁRIA
# Justificativa: Função de inicialização que configura o ambiente e parâmetros
# mas não afeta diretamente a lógica de trading
def __init__(self):
# Definição dos períodos
self.kairi_period = int(os.getenv("KAIRI_PERIOD", "25"))
self.rsi_period = int(os.getenv("RSI_PERIOD", "14"))
self.atr_period = int(os.getenv("ATR_PERIOD", "14"))
self.convergence_factor = float(os.getenv("CONVERGENCE_FACTOR", "0.75"))
# Configuração do modelo ML
self.model_dir = "models"
if not os.path.exists(self.model_dir):
os.makedirs(self.model_dir)
self.scaler = StandardScaler()
self.model_path = f"{self.model_dir}/kotegawa_model.joblib"
self.scaler_path = f"{self.model_dir}/kotegawa_scaler.joblib"
# Carrega modelo e scaler existentes ou cria novos
if os.path.exists(self.model_path) and os.path.exists(self.scaler_path):
self.ml_model = joblib.load(self.model_path)
self.scaler = joblib.load(self.scaler_path)
else:
self.ml_model = IsolationForest(
contamination=0.1, n_estimators=200, max_samples="auto", random_state=42
)
# O scaler será ajustado na primeira chamada
# Configuração de logging
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
self.logger = logging.getLogger("KotegawaTradingModel")
# Armazena últimos sinais para logging
self.last_signals = {}
# Flag para controlar o primeiro ajuste
self.is_fitted = False
# NÍVEL 2: FUNÇÃO AUXILIAR
# Justificativa: Suporta o detector de volatilidade e mantém o modelo atualizado
def train_model(self, features_df):
"""Treina o modelo com novos dados"""
try:
if not self.is_fitted:
# Primeiro ajuste do scaler
self.scaler.fit(features_df)
self.is_fitted = True
joblib.dump(self.scaler, self.scaler_path)
# Normaliza os dados
scaled_features = self.scaler.transform(features_df)
# Treina o modelo
self.ml_model.fit(scaled_features)
# Salva o modelo
joblib.dump(self.ml_model, self.model_path)
self.logger.info("Modelo atualizado com sucesso")
except Exception as e:
self.logger.error(f"Erro ao treinar modelo: {str(e)}")
# NÍVEL 1: FUNÇÃO PRINCIPAL/CRÍTICA
# Justificativa: Implementa a lógica core de detecção de regimes de volatilidade
# e influencia diretamente as decisões de trading
def detect_volatility_regimes(self, high, low, close):
features = pd.DataFrame(
{
"returns": np.log(close / close.shift(1)),
"range": high - low,
"atr": AverageTrueRange(
high, low, close, self.atr_period
).average_true_range(),
"kairi": self.calculate_adaptive_kairi(close),
"rsi": RSIIndicator(close, self.rsi_period).rsi(),
}
).dropna()
# Se for a primeira execução ou a cada 100 candles
if not self.is_fitted or len(features) > 100:
self.train_model(features)
# Faz previsões usando transform apenas se o scaler estiver ajustado
if self.is_fitted:
scaled_features = self.scaler.transform(features)
return self.ml_model.predict(scaled_features)
else:
# Retorna um valor padrão se ainda não estiver ajustado
return np.zeros(len(features))
# NÍVEL 2: FUNÇÃO AUXILIAR
# Justificativa: Fornece um indicador técnico importante que suporta
# a análise principal com métricas de divergência de preço
def calculate_adaptive_kairi(self, close_prices):
# Implementação ZLEMA (Zero Lag EMA)
ema1 = close_prices.ewm(span=self.kairi_period).mean()
ema2 = ema1.ewm(span=self.kairi_period).mean()
lag = ema1 - ema2
zlema = ema1 + lag
return ((close_prices - zlema) / zlema) * 100
# NÍVEL 1: FUNÇÃO PRINCIPAL/CRÍTICA
# Justificativa: Função principal que integra todos os componentes,
# gera sinais de trading e determina níveis de gestão de risco
def analyze(self, df):
close = df["close"]
analysis = {}
# Indicadores principais
analysis["kairi"] = self.calculate_adaptive_kairi(close).iloc[-1]
analysis["rsi"] = RSIIndicator(close, self.rsi_period).rsi().iloc[-1]
analysis["atr"] = (
AverageTrueRange(df["high"], df["low"], close, self.atr_period)
.average_true_range()
.iloc[-1]
)
# Machine Learning
volatility_regime = self.detect_volatility_regimes(df["high"], df["low"], close)
analysis["high_volatility"] = volatility_regime[-1] == -1
# Sinais adaptativos e agressivos
if analysis["high_volatility"]:
analysis["entry_long"] = analysis["kairi"] < -20 and analysis["rsi"] < 35
analysis["entry_short"] = analysis["kairi"] > 20 and analysis["rsi"] > 65
else:
analysis["entry_long"] = analysis["kairi"] < -15 and analysis["rsi"] < 40
analysis["entry_short"] = analysis["kairi"] > 15 and analysis["rsi"] > 60
# Gestão de risco dinâmica
analysis["stop_loss"] = close.iloc[-1] - (
analysis["atr"] * (3 if analysis["high_volatility"] else 1.5)
)
analysis["take_profit"] = close.iloc[-1] + (
analysis["atr"] * (4 if analysis["high_volatility"] else 3)
)
# Armazena para logging
self.last_signals = analysis
return analysis