Skip to content

Commit

Permalink
Merge pull request #43 from fortesenselabs/feature/environments
Browse files Browse the repository at this point in the history
Trading & ML Enhancements: Position Limits, Signal Validation, Agent Training, and Environments module update
  • Loading branch information
seekersoftec authored Oct 12, 2024
2 parents 915b207 + 8874b16 commit 761a7f9
Show file tree
Hide file tree
Showing 65 changed files with 38,906 additions and 7,652 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -279,4 +279,5 @@ research/*
add_stage.sh
catalog/
*.session*
*trades.db
*trades.db
current_open_positions.csv
3 changes: 3 additions & 0 deletions packages/itbot/agents/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
from .agent import *
from .basic_ml_agent import *

# ITBAgent => https://github.com/asavinov/intelligent-trading-bot
72 changes: 59 additions & 13 deletions packages/itbot/agents/agent.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import asyncio
from abc import ABC, abstractmethod
from typing import List, Optional
import os
import joblib
from typing import Dict, List, Optional

import pandas as pd
from packages.itbot.itbot import Signal
import threading
import logging
Expand All @@ -13,31 +17,73 @@ class Agent(ABC):
The agent continuously waits for data and sends signals asynchronously as an event-driven program.
"""

def __init__(self, logger: Optional[Logger] = None):
def __init__(
self,
selected_symbols: List[str] = ["EURUSD", "BTCUSD", "XAUUSD"],
logger: Optional[Logger] = None,
):
"""Initialize the trading bot with logging and a list of trading symbols.
Args:
selected_symbols (List[str]): List of symbols to trade. Default is ["EURUSD", "BTCUSD","XAUUSD"].
logger (Optional[Logger]): An optional logger instance. If not provided, a default logger will be created.
"""
# Set up logging
self.logger = logger or Logger(name="it_bot", log_level=logging.DEBUG, filename="ITBot.log")
self.logger = logger or Logger(name="it_bot", level=logging.DEBUG, filename="ITBot.log")

self.model = None
# Initialize the signal queue for asynchronous handling
self.signals_queue = asyncio.Queue()
self.loop = None

@abstractmethod
def load_model(self, model_path: str) -> None:
# Initialize the event loop
self.loop = asyncio.get_event_loop() # Use the current event loop

# Store the selected symbols for trading
self.selected_symbols = selected_symbols
self.models = {
symbol: None for symbol in self.selected_symbols
} # Initialize models for symbols

# Log the initialized symbols
self.logger.debug(f"Initialized with symbols: {self.selected_symbols}")

def load_models(self, model_path: str) -> None:
"""
Load the trained model from the specified path.
Load the trained models from the specified path.
Args:
model_path (str): The file path of the trained model.
model_path (str): The directory path where the trained models are stored.
Raises:
ValueError: If the provided path is not a directory or if the model file is not found.
"""
pass
# Check if the provided path is a valid directory
if not os.path.isdir(model_path):
raise ValueError(f"The provided path '{model_path}' is not a valid directory.")

# Load models for each symbol from the specified directory
for symbol in self.selected_symbols:
model_file = os.path.join(
model_path, f"{symbol}_voting.joblib"
) # Adjust the file naming as needed

# Check if the model file exists
if os.path.isfile(model_file):
try:
self.models[symbol] = joblib.load(model_file)
self.logger.info(f"Model for {symbol} loaded successfully from {model_file}.")
except Exception as e:
self.logger.error(f"Error loading model for {symbol}: {e}")
else:
self.logger.warning(f"No model file found for {symbol} at {model_file}.")

@abstractmethod
async def generate_signals(self, data: dict) -> List[Signal]:
async def generate_signals(self, symbol: str, data: pd.DataFrame) -> List[Signal]:
"""
Asynchronously generate trading signals using the loaded model and input data.
Generate trading signals using the loaded model and input data.
Args:
data (dict): The data for the agent to make decisions.
symbol (str): The trading symbol for which signals are being generated.
data (pd.DataFrame): The input data used by the agent to make trading decisions.
Returns:
List[Signal]: A list of trading signals generated by the model.
Expand Down
86 changes: 0 additions & 86 deletions packages/itbot/agents/agent_001.py

This file was deleted.

Loading

0 comments on commit 761a7f9

Please sign in to comment.