Reinforcement learning: learning from reward, not from labels

On this page
  1. The same ten days, two questions
  2. Five words, mapped to a trade
  3. What a reinforcement learner is given, and what it is not
  4. Delayed reward: who gets the credit?
  5. Episodes end; the market does not
  6. When this is the right tool, and when it is not
  7. Check yourself
  8. The code
  9. Summary
  10. References

The first series taught one shape of learning: a table of examples, each with its featuresAn input variable a model uses to make its prediction; also called a predictor or an independent variable. and the right answer, and a model that learns to predict the answer for a new row. Every post in it, from linear regressionA simple method that predicts a numeric answer by assuming a straight-line relationship between the inputs and the answer. to boostingCombining many trees grown one after another, each using what the earlier trees got wrong., used that shape. This series starts with a different one. There is no right answer in the data at all. There is a situation, a choice, and afterwards a number that says how the choice turned out. That is reinforcement learningLearning what to do in each situation to collect the most numerical reward, by trying actions rather than being told which are right., and the first job is to see clearly what changed, because the data looks the same.

The same ten days, two questions

Take SPY’s daily prices for the first ten trading days of 2023. A supervised learner sees them as rows. Each row holds the last five daily returnsThe percentage change in price from one day to the next: today's price divided by yesterday's, minus one. as features and the next day’s return as the labelThe outputs a model learns to predict; also called the target or the response. (the right answer the model should predict). Table 1 has the first three rows:

Table 1. Three days of SPY as supervised rows, January 2023
DateFeatures: the five returns beforeLabel: that day’s return
2023-01-03+0.58%, −0.39%, −1.24%, +1.80%, −0.26%−0.42%
2023-01-04−0.39%, −1.24%, +1.80%, −0.26%, −0.42%+0.77%
2023-01-05−1.24%, +1.80%, −0.26%, −0.42%, +0.77%−1.14%

The question those rows ask is “what will tomorrow’s return be?”. The right answer sits in the last column, the model is scored on how close it gets, and the rows do not affect each other: predicting 2023-01-04 badly does not change the row for 2023-01-05.

A reinforcement learner sees the same ten days as one episodeOne natural run of interaction, such as one play of a game, ending in a terminal state before a reset.. On the first morning it is in some situation (the stateA signal telling the agent how the environment is at a given moment; the input its policy and value estimates use.: say, those same five past returns, plus the fact that it holds nothing). It picks an actionOne of the set of things the agent can do; at each step it senses the state, chooses an action and performs it.: buy SPY, or stay in cash. The day passes and it receives a rewardThe single number the environment sends the agent at each step; the agent aims to maximise the total over the long run.: the day’s return on whatever it holds. Then it is in a new state, and chooses again. Nobody tells it whether buying was the right answer. It only ever sees the number.

action: move to long, cash or short

reward: the day's gain or loss, one number

next state: new prices, new holding

Agent: holds a policy, a rule from state to action

Environment: the market and the account

Sutton and Barto draw exactly this loop (their figure 3.1) and define the five words by it. The agentThe learner and decision maker: the part that chooses actions. is the learner and decision maker. The environmentEverything outside the agent that it interacts with. is everything outside it, which responds to each action with a reward and a new state. The sequence the two produce together is state, action, reward, state, action, reward, and so on, and the agent’s one goal is to make the sum of the rewards as large as it can over the long run, not the next one.

The question changed, not the data. Supervised: given this row, what is the answer? Reinforcement: given this situation, what should I do, knowing that what I do changes the next situation and that the result arrives later as a number?

Five words, mapped to a trade

The words are easy to say and easy to mix up, so Table 2 puts each one on the trading case, with the mistake that usually goes with it.

Table 2. The five words on the trading case, with the usual confusion
WordOn the trading caseThe usual confusion
Statewhat the agent knows this morning: recent returns, an indicator or two, and what it already holdsan observation is not a state until it holds what the decision needs; the same five returns mean a different choice to an agent that is long and one that is in cash
Actionthe choice: move to long, to cash, or to short; or “hold what you have”an order is the action; a forecast (“SPY will rise”) is not, a forecast is an input
Rewardone number after the day: the change in the account’s valueprofit is one choice of reward, not the only one; a reward can also charge for costs or for taking risk
Policythe rule the agent follows: a mapping from each state to an actiona policy is what the agent learns; a hand-written rule like “buy when the fast average crosses the slow one” is also a policy, just a fixed one
Episodea stretch of days with a start and an end, after which things resetthe market does not reset; a training episode is a boundary the designer draws

Two of these deserve a second look. The reward defines the goal (Sutton and Barto, section 3.2): it is the environment’s one-number verdict on what just happened, and the agent will do whatever earns most of it. Choose “today’s price change” and the agent learns to predict direction; choose “today’s change in account value after commissionsThe fee a broker charges for a trade; one part of a trade's transaction cost.” and it also learns that trading often is expensive. The learner optimises the reward you wrote down, not the goal you had in mind. The policyThe agent's way of behaving: a mapping from the states it sees to the actions it takes in them. is the thing being learned. Sutton and Barto define it as a mapping from states to the probabilityHow often an event happens if you could repeat a trial without end: the share of trials where it happens. of taking each action (section 3.5), which covers both the deterministic kind (in this state, always buy) and the stochastic kind (in this state, buy 80% of the time). Everything else in the system, including the value estimates that later posts build, exists only to improve the policy.

What a reinforcement learner is given, and what it is not

Sutton and Barto’s section 1.1 sets out the contrast with supervised learningLearning from examples where every input comes with a known answer, so a model can learn to predict the answer for new cases., and Mitchell’s section 13.1 lists what makes the reinforcement setting harder. Table 3 puts them side by side:

Table 3. Supervised against reinforcement learning
ItemSupervised learningReinforcement learning
Givenexamples, each with the correct answera reward, one number, after each action
Learnsa function from features to the answera policy, from state to action
Where the data comes froma fixed dataset, collected before learningthe agent’s own actions; a different policy sees different data
When the feedback arrivesimmediately, per examplelater, and spread over several actions
Do today’s choices change tomorrow’s data?noyes: the action changes the next state
Has to explore?noyes: to find a better action it must sometimes try one it believes is worse

The “given” row is the heart of it. Supervised learning works when a knowledgeable supervisor can hand over correct, representative examples of the right behaviour. Sutton and Barto’s point is that in interactive problems this is often impossible: nobody can list the right trade for every market situation, and the situations where learning would help most are the ones nobody has labelled. So the agent has to learn from its own experience, which is what the reward signal is for.

The last two rows are consequences of the first. Because the action changes the next state, the agent partly chooses its own training dataThe observed examples a method learns from: they are used to teach it how to make its estimate., which is why explorationChoosing a non-greedy action so you can improve your estimate of its value. becomes a problem that supervised learning never has. Mitchell calls out two more: the state the agent sees may be only part of the real situation (a camera cannot see behind the robot; five returns cannot see the news), and the reward for an action may arrive much later than the action itself. That last one is where the arithmetic gets interesting.

Delayed reward: who gets the credit?

Suppose the agent went long SPY on 2023-01-03 and held for ten days. Table 4 is what it received, day by day, from the shared price file:

Table 4. Daily rewards of the January 2023 SPY episode and the reward still to come
DayDateReward that dayReward still to come from this day to day 10
12023-01-03−0.42%+3.98%
22023-01-04+0.77%+4.40%
32023-01-05−1.14%+3.63%
42023-01-06+2.29%+4.77%
52023-01-09−0.06%+2.48%
62023-01-10+0.70%+2.53%
72023-01-11+1.26%+1.83%
82023-01-12+0.36%+0.57%
92023-01-13+0.39%+0.20%
102023-01-17−0.18%−0.18%

The agent made a decision every morning: buy on day 1, then “hold” on days 2 to 10. Which decisions were good? The reward of a day is a bad judge. Day 3’s decision to hold was followed by the worst day of the ten, a loss of 1.14%\bad{1.14\%}, yet from that day to the end the rewards added up to 3.63%\good{3.63\%}. Judged by what it led to, holding on day 3 was fine; judged by its own day, it looks like a mistake. This is Mitchell’s temporal credit assignmentWorking out which of the actions in a sequence deserve credit for the rewards that came later. problem: the outcome arrives spread over many steps, and the learner has to work out which of the earlier actions deserve the credit or the blame.

Sutton and Barto’s answer is to judge each action by the whole sequence of rewards that follows it, which they call the return (equation 3.7, for an episode that ends at step T):

G, the return: what the decision at time t is answerable forR, the rewards observed afterwards

Gt=Rt+1+Rt+2+⋯+RT\key{G_t} = \good{R_{t+1}} + \good{R_{t+2}} + \cdots + \good{R_T}

That is the last column of Table 4. The day-1 decision to buy is answerable for all ten days, G1=3.98%\key{G_1} = \good{3.98\%}. The day-6 decision is answerable for the last five, G6=2.53%\key{G_6} = \good{2.53\%}. The word “return” here is the reinforcement-learning word, the sum of future rewards; it is not the finance word for a price change, even though in this example each reward happens to be a daily price return.

{"panels":[{"x0":45.8,"x1":565.2,"y0":29.16,"y1":223.28,"title":"1. Ten daily rewards and their running total","xlabel":"Day of the episode (trading days from 2023-01-03)","ylabel":"Reward (% of the position)","xlog":false},{"x0":45.8,"x1":565.2,"y0":311.96,"y1":506.08,"title":"2. What the decision made on each day is answerable for","xlabel":"Day of the episode (trading days from 2023-01-03)","ylabel":"Reward from that day to the end (% of the position)","xlog":false}],"series":[{"panel":0,"label":"running total since day 1","color":"var(--chart-blue, #3b6ea5)","kind":"line","x":[1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0],"y":[-0.42098,0.351033,-0.790302,1.50291,1.44621,2.1475,3.4123,3.77638,4.16431,3.98112],"sx":[84.17,133.35,182.54,231.72,280.91,330.09,379.28,428.46,477.65,526.84],"sy":[190.49,164.82,202.78,126.5,128.39,105.06,62.99,50.88,37.98,44.07]}]} 2026-10-31T01:56:05.431524 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/ 1 2 3 4 5 6 7 8 9 10 Day of the episode (trading days from 2023-01-03) −1 0 1 2 3 4 Reward (% of the position) 1. Ten daily rewards and their running total running total since day 1 reward that day (long SPY) 1 2 3 4 5 6 7 8 9 10 Day of the episode (trading days from 2023-01-03) 0 1 2 3 4 5 Reward from that day to the end (% of the position) 2. What the decision made on each day is answerable for reward still to come from that day to day 10
Figure 1. Daily rewards of the January 2023 episode and the reward still to come each day

The second panel of Figure 1 is the picture to keep. Early decisions carry the weight of everything after them, and the last decision carries only its own day. Later posts in this series discount the later rewards so that a reward far away counts for less than one tomorrow, and estimate these sums without waiting for the episode to end. For now the point is simpler: in reinforcement learning the thing a decision is judged by is a sum over the future, and the learner has to build that judgement from rewards that arrive one at a time.

Episodes end; the market does not

The ten days above were an episode because I said so. Sutton and Barto (section 3.3) separate two kinds of task. An episodicA task whose interaction breaks into separate episodes, each ending in a terminal state. task breaks naturally into pieces with a terminal stateThe special state that ends an episode, followed by a reset to a starting state. and a reset: a game of chess ends, a trip through a maze ends at the exit, and the next game starts fresh regardless of how the last one went. A continuing task has no natural end: a process controller runs as long as the plant does.

Trading is the second kind dressed up as the first. A market-making system runs whenever the exchange is open, and a portfolio carries its positions overnight, so there is no terminal state unless the designer draws one. Cutting a long history into year-long training episodes is useful, because it gives the learner many starts and many ends to learn from, but the cut is artificial: the holding at the end of one episode would have been the holding at the start of the next, and the agent is not told that. The post on states and rewards comes back to what the holding position does to the state. The word to carry forward is that an episode boundary is a design decision, and like the reward, it shapes what gets learned.

When this is the right tool, and when it is not

Reinforcement learning sounds more advanced than regressionA prediction problem whose answer is a number; when the answer is a category it is classification instead., and a research director who has read about it may want it for that reason alone. That is the wrong reason. Three questions tell you whether the problem is really the sequential kind:

Does the action change the next situation?a position held today is the position you start from tomorrow
Yes the problem is sequential, and the reward for today's choice includes what it makes possible tomorrow. A one-step predictor cannot see that.
No each decision stands alone, and a supervised model that predicts the outcome plus a rule that acts on it is simpler, cheaper to train and easier to check.
Can anyone write down the right answer for each situation?a label that a supervisor could supply
Yes use it. A dataset with correct labels is the strongest signal there is, and reinforcement learning throws it away in exchange for a weaker one.
No but you can score the outcome afterwards, which is exactly the reinforcement setting: a reward is a score, not an answer.
Can the learner afford to explore?trying an action it believes is worse, in order to learn
Yes in a simulator, or on paper trades, where a bad action costs nothing real.
No with live capital every exploratory trade is a real loss, so the learning has to happen in a model of the market first, and the model becomes the thing to worry about.

Sutton and Barto’s own framing of the boundary is that supervised learning is adequate for learning from a supervisor and inadequate for learning from interaction. Predicting tomorrow’s return is the first kind of problem. Deciding whether to enter, keep, reverse or exit a position, when each choice changes what the next choice costs, is the second. Many trading problems that look like the second are in fact the first with a position rule bolted on, and that version should be tried before the agent is built.

Check yourself

The same ten days of SPY can feed a supervised learner or a reinforcement learner. What is different?

The question, not the data. The supervised learner gets the right answer for each row (the next day’s return) and learns to predict it. The reinforcement learner gets only a reward after each action, and its action changes the next state, so it has to work out for itself which actions earned the result.

On day 3 of the January 2023 episode, holding SPY lost 1.14%. Why was holding still a fine decision?

Because a decision is judged by the return, the sum of all the rewards that follow it, not by its own day. From day 3 to day 10 the rewards added up to +3.63%. Working out which earlier actions deserve the credit or the blame is the temporal credit assignment problem.

When should you build a supervised model with a position rule instead of a reinforcement learning agent?

When the action does not change the next situation, or when someone can write down the right answer for each situation. A dataset with correct labels is the strongest signal there is, and a supervised model is simpler, cheaper to train and easier to check. Many trading problems that look sequential are really a prediction with a position rule added, and that version should be tried first.

The code

The snippet reproduces Table 4. Its variables are in Table 5:

Table 5. Variables in the snippet
VariableHolds
rSPY’s daily returns, one per trading day
epthe ten rewards of the episode: one daily return each for a position held long
to_gofor each day, the sum of that day’s reward and every reward after it, to day 10
import pandas as pd

url = "https://raw.githubusercontent.com/ankurtrapasiya/examples/main/data/prices.csv"
px = pd.read_csv(url, index_col="date", parse_dates=True)["SPY"]
r = (px / px.shift(1) - 1).dropna()

start = r.index.get_loc(pd.Timestamp("2023-01-03"))
ep = r.iloc[start:start + 10]            # reward each day = the day's return on a long position
to_go = ep[::-1].cumsum()[::-1]          # add up from the end: reward still to come after each day

for day, (date, reward) in enumerate(ep.items(), start=1):
    print(f"day {day:>2} {date.date()}  reward {100*reward:+.2f}%  still to come {100*to_go[date]:+.2f}%")
print(f"total {100*ep.sum():+.2f}%")

It prints the ten rows of Table 4 and a total of +3.98%. The [::-1] idiom reverses a sequence, so ep[::-1].cumsum()[::-1] adds up from the last day backwards and flips the result back into date order.

The script behind the real numbers

The tables and the chart come from examples/reinforcement-learning-reward-not-labels/episode.py, which runs on the blog’s five tickers. To run it yourself, clone the examples repo: its README has a three-command Docker setup, or run uv run reinforcement-learning-reward-not-labels/episode.py.

Summary

Table 6 is the post in one line per idea.

Table 6. Summary, one line per idea
IdeaIn one line
Supervised versus reinforcementthe right answer per example, versus one number after each action
State, action, rewardwhat the agent knows, what it chooses, the environment’s verdict
Policythe mapping from state to action; the thing that is learned
Delayed rewarda decision is judged by the sum of the rewards that follow it, not by its own day
Episodesa terminal state and a reset; in trading, a boundary the designer draws
When to use itwhen the action changes the next situation, nobody can supply the right answer, and exploring is affordable, at least in a simulator

References

  • Sutton and Barto, Reinforcement Learning: An Introduction, 2nd edition (MIT Press, 2018). Section 1.1 for the definition of reinforcement learning, the two distinguishing features (trial-and-error search and delayed reward) and the contrast with supervised and unsupervisedLearning from data that has inputs but no known answer for any example, so there is nothing to predict, only structure to find. learning; section 1.3 for policy, reward signal, value functionWhat is good in the long run: for each state, the total reward the agent can expect to collect from there on. and model; section 3.1 and figure 3.1 for the agent–environment loop; section 3.2 for the reward as the definition of the goal; section 3.3 for episodic and continuing tasksA task whose interaction does not break into episodes but goes on without limit. and the return, equation 3.7; section 3.5 for the policy as a mapping from states to action probabilities.
  • Tom M. Mitchell, Machine Learning (McGraw-Hill, 1997). Section 13.1 for the learning task, the control policy, and the four things that set reinforcement learning apart from function approximation: delayed reward and temporal credit assignment, exploration, partially observable states and life-long learning.
  • Kevin P. Murphy, Probabilistic Machine Learning: Advanced Topics (MIT Press, 2023). Section 35.1 for the trajectoryThe sequence of states, actions and rewards that the agent and environment produce together, step after step. of states, actions and rewards, and the split between model-freeDescribes methods that learn by trial and error alone, without a model of the environment. and model-basedDescribes methods that use a model of the environment and planning. methods that later posts use.
Tagged machine-learning, reinforcement-learning, trading← Home