Downloads · 30 days
6
19% of all-time downloads
LordTyrel/stock-trading-rl-agent
stock-trading-rl-agent is a reinforcement learning model from LordTyrel. Use it for the reinforcement learning task on the model card, and read the license before you ship it in a product. It is set up for stable-baselines3. The card lists the license as mit.
Downloads · 30 days
6
19% of all-time downloads
All-time downloads
31
Public
Repo size
153 MB
Likes
5
Public
Click a slice to open those files.
.zip4.9 MB · 65%
From the Hugging Face model README
A state-of-the-art reinforcement learning agent for algorithmic stock trading using Proximal Policy Optimization (PPO)
🔥 Quick Start • 📊 Performance • 💡 Usage • 🛠️ Technical Details
</div>This model represents a sophisticated reinforcement learning trading agent trained using the Proximal Policy Optimization (PPO) algorithm. The agent learns to make optimal trading decisions across multiple stocks by analyzing technical indicators, market patterns, and portfolio states.
pip install stable-baselines3 yfinance pandas numpy scikit-learn
from stable_baselines3 import PPO
import pickle
import numpy as np
# Load the trained model
model = PPO.load("best_model.zip")
# Load the data scaler
with open("scaler.pkl", "rb") as f:
scaler = pickle.load(f)
# Example prediction
obs = your_observation_data # Shape: (n_features,)
action, _states = model.predict(obs, deterministic=True)
# Interpret action
action_type = int(action[0]) # 0: Hold, 1: Buy, 2: Sell
position_size = action[1] # 0-1: Fraction of available capital
| Stock | Total Return | Sharpe Ratio | Max Drawdown | Win Rate | Status |
|---|---|---|---|---|---|
| MSFT | 7,243.44% | 0.56 | 164.60% | 52.11% | 🏆 Best Overall |
| AMZN | 162.87% | 0.74 | 187.11% | 6.72% | 🏆 Best Risk-Adj. |
| TSLA | 109.91% | -0.22 | 145.29% | 44.76% | ⚡ Volatile |
| AAPL | -74.02% | 0.65 | 157.07% | 7.01% | ⚠️ Underperform |
| GOOGL | 0.00% | 0.00 | 0.00% | 0.00% | 🔄 No Activity |
Algorithm: PPO (Proximal Policy Optimization)
Policy Network: Multi-Layer Perceptron
Action Space:
- Action Type: Discrete(3) [Hold, Buy, Sell]
- Position Size: Continuous[0,1]
Observation Space: Technical indicators + Portfolio state
Training Steps: 500,000
Batch Size: 64
Learning Rate: 0.0003
{
"tickers": ["AAPL", "MSFT", "GOOGL", "AMZN", "TSLA"],
"period": "5y",
"interval": "1d",
"use_sp500": false,
"lookback_window": 60
}
{
"initial_balance": 10000,
"transaction_cost": 0.001,
"max_position_size": 1.0,
"reward_type": "return",
"risk_adjustment": true
}
{
"algorithm": "PPO",
"total_timesteps": 500000,
"learning_rate": 0.0003,
"batch_size": 64,
"n_epochs": 10,
"gamma": 0.99,
"eval_freq": 1000,
"n_eval_episodes": 5,
"save_freq": 10000,
"seed": 42
}
The agent observes the following features for each stock:
The agent outputs a 2-dimensional action:
Action Type (Discrete):
0: Hold position1: Buy signal2: Sell signalPosition Size (Continuous):
[0, 1]import yfinance as yf
import pandas as pd
from stable_baselines3 import PPO
# Load model and scaler
model = PPO.load("best_model.zip")
with open("scaler.pkl", "rb") as f:
scaler = pickle.load(f)
# Get live data
ticker = "AAPL"
data = yf.download(ticker, period="3mo", interval="1d")
# Prepare observation (implement your feature engineering)
obs = prepare_observation(data, scaler) # Your preprocessing function
# Get trading decision
action, _states = model.predict(obs, deterministic=True)
action_type = ["HOLD", "BUY", "SELL"][int(action[0])]
position_size = action[1]
print(f"Action: {action_type}, Size: {position_size:.2%}")
def backtest_strategy(model, data, initial_balance=10000):
"""
Backtest the trained model on historical data
"""
balance = initial_balance
position = 0
for i in range(len(data)):
obs = prepare_observation(data[:i+1])
action, _ = model.predict(obs, deterministic=True)
# Execute trading logic
action_type = int(action[0])
position_size = action[1]
if action_type == 1: # Buy
shares_to_buy = (balance * position_size) // data.iloc[i]['Close']
position += shares_to_buy
balance -= shares_to_buy * data.iloc[i]['Close']
elif action_type == 2: # Sell
shares_to_sell = position * position_size
position -= shares_to_sell
balance += shares_to_sell * data.iloc[i]['Close']
return balance + position * data.iloc[-1]['Close']
| File | Description | Size |
|---|---|---|
best_model.zip | 🏆 Best performing model checkpoint | ~2.5MB |
final_model.zip | 🎯 Final trained model | ~2.5MB |
scaler.pkl | 🔧 Data preprocessing scaler | ~50KB |
config.json | ⚙️ Complete training configuration | ~5KB |
evaluation_results.json | 📊 Detailed evaluation metrics | ~10KB |
training_summary.json | 📈 Training statistics | ~8KB |
The model showed consistent improvement during training:
🚨 Risk Warning: This model is for educational and research purposes only. Past performance does not guarantee future results. Cryptocurrency and stock trading involves substantial risk of loss.
📊 Data Limitations: The model was trained on historical data from 2019-2024. Market conditions may change, affecting model performance.
🔧 Technical Limitations: The model requires proper preprocessing and feature engineering to work effectively in live trading environments.
# Create custom trading environment
from stable_baselines3.common.env_checker import check_env
from your_trading_env import StockTradingEnv
env = StockTradingEnv(
tickers=["AAPL", "MSFT", "GOOGL"],
initial_balance=10000,
transaction_cost=0.001
)
# Verify environment
check_env(env)
# Load and test model
model = PPO.load("best_model.zip")
obs = env.reset()
action, _states = model.predict(obs)
import asyncio
import websocket
async def live_trading_loop():
"""
Example live trading implementation
"""
while True:
# Get real-time market data
market_data = await get_market_data()
# Prepare observation
obs = prepare_observation(market_data)
# Get model prediction
action, _ = model.predict(obs)
# Execute trade (implement your broker API)
if int(action[0]) != 0: # Not hold
await execute_trade(action)
await asyncio.sleep(60) # Wait 1 minute
We welcome contributions! Please feel free to:
This project is licensed under the MIT License - see the LICENSE file for details.
If you use this model in your research, please cite:
@misc{stock-trading-rl-2025,
title={Stock Trading RL Agent using PPO},
author={Adilbai},
year={2025},
url={https://huggingface.co/Adilbai/stock-trading-rl-20250704-171446}
}
🚀 Ready to revolutionize your trading strategy?
</div>