Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Trading & ML Enhancements: Position Limits, Signal Validation, Agent Training, and Environments module update #43

Merged
merged 23 commits into from
Oct 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
a6e7ae2
feat: Introduce position size limits in risk manager
seekersoftec Oct 11, 2024
5686861
feat: Implement portfolio optimization strategies
seekersoftec Oct 11, 2024
0fed905
chore: Add scipy dependency for improved data processing
seekersoftec Oct 11, 2024
84ac880
feat: introduce backtesting functionality
seekersoftec Oct 12, 2024
2dca19f
feat: refactor trading logic
seekersoftec Oct 12, 2024
09269cc
feat: Introduce basic ML agent
seekersoftec Oct 12, 2024
6b2b593
feat: Make TelegramInterface asynchronous
seekersoftec Oct 12, 2024
ec23d83
feat: implement basic signal validation and queueing
seekersoftec Oct 12, 2024
302b15e
feat: Add project experiments notebook
seekersoftec Oct 12, 2024
a797040
feat: Multi-symbol signal generation
seekersoftec Oct 12, 2024
221a17e
Refactor: Remove unnecessary imports from `mt5_trader.py` and add dev…
seekersoftec Oct 12, 2024
a7ac745
feat: Add trained models
seekersoftec Oct 12, 2024
899f976
chore: Rename Project notebook to `model_experiments`
seekersoftec Oct 12, 2024
04cafdd
Fix: Update Seaborn style for consistency
seekersoftec Oct 12, 2024
c9edcdc
feat: Remove unused Agent001 and its model
seekersoftec Oct 12, 2024
572ccbf
feat: Update BasicMLAgent and integrate into ITBot
seekersoftec Oct 12, 2024
29551d9
feat: improve trading logic
seekersoftec Oct 12, 2024
a214265
feat: Add JSON serialization/deserialization to Signal Model
seekersoftec Oct 12, 2024
df2bb72
feat: Add environment URL to available environments
seekersoftec Oct 12, 2024
5fe4a44
fix: repackage the gym-mtsim library
seekersoftec Oct 12, 2024
77485f1
fix: update `gym_anytrading` environment
seekersoftec Oct 12, 2024
f823e88
feat: remove ITBAgent
seekersoftec Oct 12, 2024
8874b16
fix: update multi-agent RL finance environment
seekersoftec Oct 12, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading