1from stable_baselines3 import PPO
2import pickle
3import numpy as np
4
5# Load the trained model
6model = PPO.load("best_model.zip")
7
8# Load the data scaler
9with open("scaler.pkl", "rb") as f:
10 scaler = pickle.load(f)
11
12# Example prediction
13obs = your_observation_data # Shape: (n_features,)
14action, _states = model.predict(obs, deterministic=True)
15
16# Interpret action
17action_type = int(action[0]) # 0: Hold, 1: Buy, 2: Sell
18position_size = action[1] # 0-1: Fraction of available capital
1Algorithm: PPO (Proximal Policy Optimization)
2Policy Network: Multi-Layer Perceptron
3Action Space:
4 - Action Type: Discrete(3) [Hold, Buy, Sell]
5 - Position Size: Continuous[0,1]
6Observation Space: Technical indicators + Portfolio state
7Training Steps: 500,000
8Batch Size: 64
9Learning Rate: 0.0003
1{
2 "tickers": ["AAPL", "MSFT", "GOOGL", "AMZN", "TSLA"],
3 "period": "5y",
4 "interval": "1d",
5 "use_sp500": false,
6 "lookback_window": 60
7}
1{
2 "initial_balance": 10000,
3 "transaction_cost": 0.001,
4 "max_position_size": 1.0,
5 "reward_type": "return",
6 "risk_adjustment": true
7}
1{
2 "algorithm": "PPO",
3 "total_timesteps": 500000,
4 "learning_rate": 0.0003,
5 "batch_size": 64,
6 "n_epochs": 10,
7 "gamma": 0.99,
8 "eval_freq": 1000,
9 "n_eval_episodes": 5,
10 "save_freq": 10000,
11 "seed": 42
12}
-
Action Type (Discrete):
0: Hold position
1: Buy signal
2: Sell signal
-
Position Size (Continuous):
- Range:
[0, 1]
- Represents fraction of available capital to use
1import yfinance as yf
2import pandas as pd
3from stable_baselines3 import PPO
4
5# Load model and scaler
6model = PPO.load("best_model.zip")
7with open("scaler.pkl", "rb") as f:
8 scaler = pickle.load(f)
9
10# Get live data
11ticker = "AAPL"
12data = yf.download(ticker, period="3mo", interval="1d")
13
14# Prepare observation (implement your feature engineering)
15obs = prepare_observation(data, scaler) # Your preprocessing function
16
17# Get trading decision
18action, _states = model.predict(obs, deterministic=True)
19action_type = ["HOLD", "BUY", "SELL"][int(action[0])]
20position_size = action[1]
21
22print(f"Action: {action_type}, Size: {position_size:.2%}")
1def backtest_strategy(model, data, initial_balance=10000):
2 """
3 Backtest the trained model on historical data
4 """
5 balance = initial_balance
6 position = 0
7
8 for i in range(len(data)):
9 obs = prepare_observation(data[:i+1])
10 action, _ = model.predict(obs, deterministic=True)
11
12 # Execute trading logic
13 action_type = int(action[0])
14 position_size = action[1]
15
16 if action_type == 1: # Buy
17 shares_to_buy = (balance * position_size) // data.iloc[i]['Close']
18 position += shares_to_buy
19 balance -= shares_to_buy * data.iloc[i]['Close']
20 elif action_type == 2: # Sell
21 shares_to_sell = position * position_size
22 position -= shares_to_sell
23 balance += shares_to_sell * data.iloc[i]['Close']
24
25 return balance + position * data.iloc[-1]['Close']
1# Create custom trading environment
2from stable_baselines3.common.env_checker import check_env
3from your_trading_env import StockTradingEnv
4
5env = StockTradingEnv(
6 tickers=["AAPL", "MSFT", "GOOGL"],
7 initial_balance=10000,
8 transaction_cost=0.001
9)
10
11# Verify environment
12check_env(env)
13
14# Load and test model
15model = PPO.load("best_model.zip")
16obs = env.reset()
17action, _states = model.predict(obs)
1import asyncio
2import websocket
3
4async def live_trading_loop():
5 """
6 Example live trading implementation
7 """
8 while True:
9 # Get real-time market data
10 market_data = await get_market_data()
11
12 # Prepare observation
13 obs = prepare_observation(market_data)
14
15 # Get model prediction
16 action, _ = model.predict(obs)
17
18 # Execute trade (implement your broker API)
19 if int(action[0]) != 0: # Not hold
20 await execute_trade(action)
21
22 await asyncio.sleep(60) # Wait 1 minute
This project is licensed under the
MIT License - see the
LICENSE file for details.
1@misc{stock-trading-rl-2025,
2 title={Stock Trading RL Agent using PPO},
3 author={Adilbai},
4 year={2025},
5 url={https://huggingface.co/Adilbai/stock-trading-rl-20250704-171446}
6}