Ben Stuart All case studies

StockProphet

A reinforcement learning trading agent that can autonomously trade on the stock market for you.

My final project for the Le Wagon data science and AI bootcamp, built in two weeks in a team of three. It combines a recurrent neural network that forecasts prices, FinBERT news sentiment and a reinforcement learning agent (PPO) that manages a portfolio of three stocks and cash. I designed the product and built the PPO agent and the demo app.

2 weeks
3 people
PPO agent, Streamlit app and product design

You have some money aside. What do you do with it?

The first thing most people think about is investing it, and one of the main places people invest is the stock market. But the stock market is a complex topic. Most people put their money in a tracker fund (an ETF) or ask someone else to invest for them.

It is hard to do well yourself. The market is really noisy: prices change a lot, and many people don’t follow the news regularly, so they don’t know whether stocks are doing well. A fixed strategy that invests in only one company is not very interesting either, and there is too much data for a person to process. We wanted an AI that can take better decisions than people normally would.

  • Markets are noisy

    Prices change fast and unpredictably.

  • Fixed strategies break

    Simple rules can’t adapt to new regimes.

  • Too much data

    Humans can’t process indicators and news in real time.

That is how we came to StockProphet: a reinforcement learning trading agent that can autonomously trade on the stock market for you. It learns from the prices of a stock and from the news headlines about it, predicts the next day, and then buys or sells. Its job is to optimise your portfolio by investing your cash across several stocks.


An agent that learns, predicts, trades and manages.

Our goal was an intelligent trading agent, and we judge it against one benchmark: the “buy and hold” strategy, where you buy the stocks and keep them for a year. Beating it is the headline goal, because it is the test of whether trading adds anything: if an agent cannot do better than simply holding, there is no reason to trade at all.

The headline goal

Outperform benchmark

Beat the “buy and hold” strategy.

To get there, the agent has to do four things. It has to learn: absorb patterns from the price history of a stock and from the sentiment of the news headlines about it. With that, it predicts the price of the day after, and then trades: it executes buy or sell orders on its own. Its main job is to manage the portfolio, investing your cash across several stocks and optimising the allocation over time. What it manages feeds back into what it learns, so the four abilities form a loop.

  1. 1

    Learn

    Absorb patterns from price history and sentiment.

  2. 2

    Predict

    Forecast short-term market movements.

  3. 3

    Trade

    Execute buy and sell orders autonomously.

  4. 4

    Manage

    Optimise portfolio allocation over time.

Each ability maps to something we built. Learning and predicting come from the data pipeline and the forecasting model, and trading and managing come from the reinforcement learning agent and its simulated market. The next question is which kind of learning suits each job.

The solution: deep learning and reinforcement learning

We use two kinds of learning together. Deep learning extracts complex patterns from time series and financial indicators, and makes predictions. Reinforcement learning learns a dynamic policy optimised for long-term reward (profit and loss), and makes the trades automatically.

Market chaos

Prices + news + noise. Human limits, so we need AI.

Learning system

Deep learning

Extracts patterns, makes predictions.

Reinforcement learning

Learns a dynamic policy, makes automatic trades.

Better decisions

Learned, steady trading.

* Illustrative sketch; the data is invented.

That split of the work is the design of the whole system. The next section follows the pipeline in order: the data, the forecaster, the trading environment, the agent, and the demo that replays it.


From raw data to an agent you can watch.

The system is a pipeline. We prepare the data, train a model that forecasts, train a trading agent that uses the forecast, and replay the agent on data it has never seen. Below, every piece says what goes in, what happens, and what comes out, in pipeline order. The full architecture is at the end of this section.

Data pipeline

In Daily prices and news headlinesOut One table of features per trading day

Before fitting any model, we prepare the data. For each stock we download daily prices, calculate indicators, add the news sentiment and the calendar features, and combine everything into one feature table. The agent sees the news as one sentiment number for each day.

  • Market data

    Sourced via yfinance

    OHLCV (open, high, low, close, volume) on a daily timeframe.

  • Technical indicators

    Engineered features for signal detection

    SMA, EMA, RSI, MACD, volatility measures and more.

  • Calendar and macro features

    Our own additions

    Day of week, month and quarter, whether the day is next to a US holiday, and the days to and since the inflation (CPI) and jobs (NFP) reports.

  • News sentiment

    FinBERT sentiment scoring

    Articles are classified (positive = +1, neutral = 0, negative = −1) and summed per day to give a daily sentiment value.

The indicators are standard measures of trend, momentum and volatility. The calendar features give the agent a sense of time, including the days since and until the next inflation and jobs reports. The forecaster adds its own features too: the expected return, its spread and the probability of a rise.

We also tuned which features to give the agent, because each feature adds noise and training time. I built a two-stage tool. Statistical screening scores every feature, then the agent itself is trained on shortlists, with several random seeds, and the subsets are compared by Sharpe ratio (return per unit of risk). Starting from 26 candidates on Apple, it kept five.

26 candidates, 5 kept

Ranked and tested
  • Forecast conviction
  • Trading volume
  • Days since last inflation report
  • Next to a holiday
  • Days since last jobs report

The tests were short and noisy, so we treat this as a working method and a check on what the agent uses.

Learn more: how the features were scored and pruned

Statistical screening combined five measures into one score, weighted as shown. A separate backward-elimination routine then removed redundant features (correlation above 0.95), then weak ones, then dropped features one at a time as long as the Sharpe ratio fell by less than 5%.

Composite score

Stage 1
Correlation with next-day return+0.3
Mutual information with direction+0.3
Random forest importance+0.3
Variance+0.1
Redundancy with other features−0.2

The weights favour features that relate to the next day’s move and penalise features that duplicate others.

RNN model

In A stock’s last 50 daysOut Predicted next-day return, saved as a feature

The first model is a recurrent neural network (RNN), a type of network built for sequences. Ours is made of two stacked LSTM layers (a layer type that remembers patterns across many steps), followed by two dense layers. It reads a sliding window of the last 50 days and predicts the next day’s return. This is very useful for the second model, which uses the forecast to decide how to trade.

Time series: dependencies across multiple past days. It answers “what is likely to happen”.

Sliding window: the last 50 days

Predicted next-day return

* Illustrative price series. The real input is each stock's last 50 trading days.

The code also has a probabilistic version that forecasts uncertainty over one and five days: the expected return, its spread and the probability of a rise. Adding these forecasts and the sentiment to what the agent sees is what we call state enrichment: the agent sees more than raw prices.

Reinforcement learning: the environment

In Features, forecasts and four daily actionsOut A new state and a reward

Reinforcement learning is like a game: you start in a specific state, choose an action, and every time you play you learn from the reward. We built the game ourselves, as a custom gym environment (a simulated market). The key design choice is how the agent acts. Each day it reassigns capital across four options at once: three stocks and cash.

PPO agent

Chooses the actions.

4 actions in [−1, 1]

Action →

← State

← Reward

profit ÷ volatility

Environment rules

  • $10,000 to start
  • Transaction fee
  • Short borrow
  • Bankruptcy ends the run

Each day the agent outputs four numbers between −1 and 1: one for each of Apple, Microsoft and Google, and one for cash. The environment scales them into a split of the whole portfolio, trades to reach that split, charges fees on the net trade, and then moves to the next day’s prices and pays the reward.

Portfolio split

Sums to 100%
Microsoft
Google
Apple
Cash
* Allocations are illustrative, shaped like the demo app's screenshots.

This design gives the agent control over cash as well as the stocks, so it can step out of the market, and negative weights let it bet against a stock. Because the reward divides profit by volatility, it is paid for steady gains. Next is the agent that makes these decisions.

Learn more: one day, step by step
  1. 1

    Observe

    Prices, indicators, sentiment and the RNN forecasts for all three stocks, plus how the portfolio is currently split.

  2. 2

    Decide

    The PPO agent outputs four numbers between −1 and 1: one each for Apple, Microsoft and Google, and one for cash.

  3. 3

    Normalise

    The four numbers are scaled so their absolute values add up to 1. That is the target split of the whole portfolio. A negative weight is a short.

  4. 4

    Rebalance

    The environment converts each weight into a number of shares, using the portfolio value before trading. Fees apply to the net trade, and shorts pay a daily borrowing cost.

  5. 5

    Reward

    The next day’s prices arrive. The agent is rewarded with profit divided by volatility, to reduce gambling. If the portfolio falls to zero, the run ends.

PPO agent

In The state: features, forecasts, current splitOut Four portfolio weights

The agent uses proximal policy optimisation (PPO), a reinforcement learning algorithm. It tries an action, evaluates the result, and updates itself. It differs from a normal agent because it limits how much each update can change its behaviour. That keeps learning stable and reliable.

One update

Normal agents leap. PPO clips the step to a trust region.

* Illustrative sketch of the idea; the values are invented.

The difference compounds over many updates. A normal agent can break what it has already learned and collapse, while PPO’s limited steps give steady improvement without catastrophic failures.

Learning over time

Limited change per update: steady improvement.

* Illustrative sketch of the idea; the curves are invented.

We used the recurrent version, with an LSTM inside the policy so the agent can remember the recent days. The final reward is profit divided by volatility, to reduce gambling. Training a recurrent PPO agent is heavy, so I ran the training on Google Colab.

System architecture

To wrap up the pipeline: we ingest the data and transform it, use the first model to make predictions and add them to the dataset, and use the news to get an overall sentiment for each day. We pass all of that to the reinforcement learning model, which lives in an environment with fixed rules and decides on an action each day. The environment gives feedback in the form of the reward, and that is how the agent learns.

Financial indicatorsNews sentiment
1

Data pipeline

Fetch prices and newsProcess sentimentEngineer features
yfinanceFinBERT
2

RNN pre-training

Train forecasterSave predictions as features
RNN with LSTM layers
3

RL training

Gym environmentPPO agent loopSave policy
Reinforcement learning (PPO)
4

Streamlit app

Load agentInteractive user simulation
Streamlit
BuyHoldSell
Data flows down the page. The loop on stage 3 is the agent learning from its own results.

Everything before the demo happens offline. The data and the forecaster are prepared once, the agent trains in the simulated market and saves its policy, and the app only loads that saved agent. That is why the replay can run on data the agent has never seen.

Streamlit demo

In The saved agent and data it has never seenOut An interactive replay of its trading

Once the agent is trained and doing a good job, we give it the opportunity to perform on data it has not seen, from 2024 to 2025, and replay it in a Streamlit app. You pick the stocks, start on day zero with $10,000 in cash, then move a slider or press play to watch it trade day by day: portfolio value, return, win rate, current allocation and the day’s trades. These are screenshots of the app itself.

The StockProphet demo app on day zero: $10,000 in cash, the full portfolio value curve for the replay, and an allocation chart showing 100% cash.
Day zero: all cash. The curve shows the whole replay, which ends near $14,000.

As the replay advances, the agent starts to allocate. By 11 March 2025, day 189 of 286, it is spread across all three stocks and cash, with Microsoft the largest holding, and the portfolio is close to where it started (+0.56%, win rate 54.3%). The table lists that day’s trades: it raised its weight in Apple, Microsoft and cash, and cut Google.

The StockProphet demo app mid-replay on 11 March 2025, day 189 of 286: portfolio value $10,055.80, return +0.56%, win rate 54.3%, and the day's trades for each stock.
Day 189 of 286 (the red dot on the curve), 11 March 2025.

Because you can move to any day, the replay makes the agent’s decisions inspectable: you see what it held and traded each day. That is what we mean by interpretable results. The result of the full replay comes next.


A 38% return on unseen data, in our simulation.

The agent finished 38% up in the environment we built. Buying the same three stocks equally, one third each, would have returned about 20%. The path was bumpy: the portfolio dipped below its starting value more than once, including a sharp drop in spring 2025, before recovering.

It was quite tough. We had many models that immediately lost all the money: they were very efficient at spending it within the first three days. Intense collaboration in the team got us to something that worked.

Return on $10,000

Unseen data
Buy and hold
≈ 20%
StockProphet
38%
Same three stocks, same period: about 286 trading days between mid-2024 and mid-2025 that the agent had never seen.

The 20% comparison is an equal split of the three stocks, bought on day zero and held. That is the benchmark we set as the headline goal. The limitations below explain how far the 38% can be trusted.


How we kept the process honest.

We worked to the discipline you would want in a production system, within two weeks. The data is validated as it is built. It is split by time, with scaling fitted on the training data only. The features are tuned: statistical screening first, then the agent itself is trained on shortlists with several random seeds, and a feature stays only if it helps. The validation set chooses the model. The agent is then evaluated on data it never saw, with trading costs included, and judged against a benchmark on risk as well as return. Finally, the whole thing is repeatable: containerised, configured through files, cached, and saved together with its trained model.

  1. 1

    Validate the data

    Guards against
    Bad data going in silently

  2. 2

    Split by time, scale on training only

    Guards against
    Leakage from the future

  3. 3

    Tune the features

    Guards against
    Features that add noise and cost

  4. 4

    Train with a validation set

    Guards against
    Choosing a model because it fit the test

  5. 5

    Evaluate on unseen data

    Guards against
    Flattering the result

  6. 6

    Make it repeatable

    Guards against
    A result nobody can rerun

Production would add more: automated tests on every change, pinned dependencies, several seeds and test windows, monitoring, and paper trading. The limitations below say where we fell short.


Limitations

The result should be read with the following limitations in mind.

  1. One run, one test period. A single trained agent was evaluated once, over about 286 trading days. We report no confidence interval, repeated random seeds or multiple test windows, so we cannot separate skill from luck.

  2. A small universe. The portfolio held three large technology stocks. The result may not generalise to other sectors, asset classes or market regimes.

  3. A simplified environment. There were no extra fees on some trades and no days of insufficient liquidity, and trades were filled at the price the agent had just seen, so execution was assumed to be perfect. Real trading would add slippage and partial fills.

  4. A single benchmark. The headline comparison is against an equal-weight buy and hold. We did not test other baselines, such as a rule-based strategy or an index fund.

  5. Sensitivity to design choices. Many early models lost all their money within the first days of a run. This suggests that outcomes depend strongly on reward design and hyperparameters. A later feature-selection experiment on one stock gave mixed results across feature sets and seeds.

  6. Forecasts seen in training. The forecaster was trained on data that included the agent’s training period, so the agent learned from forecasts that were more accurate than the ones it received on unseen data.

  7. Repeatability gaps. Our tests ran as separate scripts and dependencies were not pinned, so a rebuild could differ from the original.

  8. No live validation. The agent was never connected to a broker. Paper trading was left as future work.


What we built, what we learned, and what comes next.

What we built. An end-to-end reinforcement learning trading pipeline, with a custom environment and interpretable results.

Key learning. State enrichment (sentiment and the RNN forecast) is powerful, but reward shaping is critical for stability.

Next steps

First, we would deploy the agent on the cloud, so it can train on more powerful machines for much longer. Then we would optimise the reward mechanism, so the agent reacts better to the different scenarios it meets. Three stocks is not very accurate: when the stock market is not performing well, you want to counterbalance with gold, bonds and other asset classes, so we would widen the portfolio, and look for new data, possibly intraday. Finally, we would plug the agent into a live API for paper trading, so a broker replaces our environment as the source of rewards.

  1. Deploy on cloud

    Allows much longer learning time.

  2. Optimise reward mechanisms

    Improve the reward to encourage more sophisticated trading.

  3. Increase portfolio space

    Enable a much larger range of tickers and multiple asset classes.

  4. Live API

    Connect to a paper trading broker for real-time testing.

Of these, paper trading would matter most. It would test the agent against real execution, which addresses the two biggest limitations above: the simplified environment and the lack of live validation.


What I owned, and what I learned.

In a team of three, I owned three things end to end. The first was the whole PPO agent: the training setup, which ran on Google Colab because the model is heavy, the reward, a recurrent policy with memory, and a late fix for a failure where the agent’s action noise exploded and it took the same action every day. The second was the Streamlit app, the interactive replay of the agent’s trading. The third was the design of the product: an agent that reassigns capital across four options every day, with a replay that lets a person watch it decide. I also built the feature selection tool.

My teammates built the RNN forecaster, the data pipeline and the news sentiment scoring. To make the pieces run together, I brought the open-source gym-anytrading environment into the repository, merged our separate environments into one, and reorganised the code into a self-contained package. Here are the skills this project taught me and the tools I used.

  • Reinforcement learning

    Reward design, a recurrent policy, stability fixes, training on Colab.

    Stable-Baselines3sb3-contribGymnasiumTensorBoardGoogle Colab
  • Simulation and environment design

    Daily reassignment across four options, trading costs, a risk-adjusted reward.

    Gymnasiumgym-anytradingNumPypandas
  • Product design

    An agent that manages a portfolio, and a replay to judge it.

    StreamlitPlotly
  • Deep learning and language models

    The RNN forecast and FinBERT sentiment as inputs to the agent.

    TensorFlow / KerasHugging Face TransformersFinBERT
  • Data and feature engineering

    A validated pipeline, training-only scaling, two-stage feature selection.

    yfinancepandasscikit-learnpyarrow
  • Engineering and teamwork

    A self-contained package, issue-linked branches and pull requests.

    Git and GitHubDocker

Taken together, the project covered the whole path from product framing to a working demo: the data, a forecasting model, a custom environment, a reinforcement learning agent, and an app a person can use to judge it.