MDPs: a state, an action, a reward and the value of what follows
On this page
Reinforcement learning: learning from reward, not from labels drew the loop: an agentThe learner and decision maker: the part that chooses actions. sees a stateA signal telling the agent how the environment is at a given moment; the input its policy and value estimates use., 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., receives a rewardThe single number the environment sends the agent at each step; the agent aims to maximise the total over the long run. and a new state, and tries to collect as much reward as it can over the long run. That is the picture. The Markov decision processThe reinforcement learning setup of agent, states, actions and rewards, written down with well defined transition probabilities., MDP for short, is the picture made precise enough to compute with, and almost every idea in the rest of this series, the Q-tableA table with one entry for each state-action pair, holding the learner's current estimate of that pair's Q value., the update rule, the model, is defined on top of it. This post goes through its parts one at a time, with the same ten days of SPY from January 2023 as the worked example, and ends with the one equation that the whole field leans on.
The state has to carry the past
Sutton and Barto write the loop as a sequence: state, action, reward, state, action, reward. In a finite MDP the next state and the reward depend only on the current state and action. The probabilityHow often an event happens if you could repeat a trial without end: the share of trials where it happens. of landing in a given next state with a given reward is a function of four things, where you are, what you did, where you land, what you got, and nothing earlier in the history enters it. That is the Markov propertyA state has it when it holds everything about past interaction that makes a difference for the future..
The book is careful about where this restriction bites: “this is best viewed a restriction not on the decision process, but on the state. The state must include information about all aspects of the past agent–environmentEverything outside the agent that it interacts with. interaction that make a difference for the future.” So the property is not something a market has or lacks. It is something a state representation has or lacks. If the state is “today’s five-day return”, then two mornings with the same five-day return are the same state, and if the agent is long on one and in cash on the other, its best action differs but the state cannot say so. The fix is to put the holding in the state. If what matters for the future is a trendThe direction prices are moving: up with rising peaks and troughs, down with falling ones, level in a trading range. that five days cannot see, the fix is a longer window. A state that leaves out something the future depends on breaks the assumption every later method rests on, and the methods will still run; they will simply learn the wrong thing. Murphy’s name for the honest version of this situation is a partially observed MDP: the agent sees an observation, not the state, and has to decide from history.
The Markov property is a demand on your state, not a fact about the world. Ask of each state label: if two mornings share this label, do they really call for the same action?
Transitions can be random
The same action in the same state does not have to lead to the same place. Sutton and Barto’s dynamics function gives a probability for each possible next state and reward, and only in the special deterministic case is one of those probabilities 1. The trading case is firmly in the random camp: “move to long” in a given state is followed by a gain on some days and a loss on others, and this state does not tell you which. This matters for how the learner treats one experience. A single transitionOne step of the agent's interaction with its environment: the state, the action, the reward and the next state. is one draw from a distribution, not the truth about the action, which is why most methods in this series move its estimates a fraction of the way towards new evidence rather than all the way.
Reward is the goal; return is the score
The reward is one number per step. Sutton and Barto’s reward hypothesis is that all of what we mean by goals can be thought of as “the maximization of the expected valueThe probability-weighted average of a quantity over all the values it can take. of the cumulative sum of a received scalar signal (called reward)” (section 3.2), and their warning is the one from Reinforcement learning: the reward says what you want, not how to get it. Reward a chess agent for capturing pieces and it may capture pieces while losing games.
The return is what the agent actually maximises: the rewards still to come, added up. For an episodeOne natural run of interaction, such as one play of a game, ending in a terminal state before a reset. that ends at step T it is the plain sum (their equation 3.7). For a task that never ends the plain sum can be infinite, so each later reward is multiplied by a discount factorA setting that decides how much rewards further in the future are worth now, compared with a reward received right away. between 0 and 1, raised to the power of how many steps away it is (equation 3.8):
G, the return; γ, the discount factorR, the rewards observed after time t
A reward k steps ahead is worth of what it would be worth today. With a reward seven days away counts for less than half; with that takes 69 days. At the agent is myopic and cares only about the next reward; as approaches 1 it becomes farsighted. And the sum stays finite: a reward of +1 forever, discounted at 0.9, adds up to exactly 10, because the weights 1, 0.9, 0.81, 0.729 and so on sum to 1 over 1 minus 0.9.
Table 1 has the ten rewards of the January 2023 episode (long SPY from 2023-01-03) with the return from each day computed three ways:
| Day | Reward that day | Return to go, γ = 1 | γ = 0.9 | γ = 0.5 |
|---|---|---|---|---|
| 1 | −0.42% | +3.98% | +2.34% | +0.01% |
| 2 | +0.77% | +4.40% | +3.07% | +0.86% |
| 3 | −1.14% | +3.63% | +2.55% | +0.17% |
| 4 | +2.29% | +4.77% | +4.10% | +2.63% |
| 5 | −0.06% | +2.48% | +2.01% | +0.67% |
| 6 | +0.70% | +2.53% | +2.30% | +1.46% |
| 7 | +1.26% | +1.83% | +1.77% | +1.52% |
| 8 | +0.36% | +0.57% | +0.56% | +0.51% |
| 9 | +0.39% | +0.20% | +0.22% | +0.30% |
| 10 | −0.18% | −0.18% | −0.18% | −0.18% |
The day-1 decision to buy is worth if every later day counts in full, at a discount of 0.9, and at 0.5, where the rewards beyond the first few days barely register. Same ten numbers, three verdicts; Figure 1 draws the weights and the three columns. The discount factor is a statement about horizon: how far ahead the agent is asked to look when it judges today’s choice. A trading agent discounted at 0.5 is being told to care about this week; one at 0.99 is being told to care about this quarter.
Table 1 has a pattern that is the key to everything later. Read it from the bottom. The return from day 10 is day 10’s reward alone. The return from day 9 is day 9’s reward plus γ times the return from day 10. Each row is the reward now plus the discounted row below (equation 3.9):
G, the return; γ, the discount factorR, the reward observed next
Check it on the top row at : . A return can be computed without ever writing out the whole sum, one step at a time from the end.
Value: the return you expect, not the one you got
The ten returns above are what happened once. An agent choosing on the morning of 2023-01-03 did not know them. What it can hope to know is what usually follows a state like this one, and that is a value.
Sutton and Barto define the state valueThe expected return from starting in a state and following a given policy after that. under a policyThe agent's way of behaving: a mapping from the states it sees to the actions it takes in them., written , as the expected return when starting in state s and following policy π from then on (equation 3.12). It answers “how good is it to be here, given how I behave?”. The action valueThe expected return from taking a given action in a state and following a given policy after that., written , is the expected return when starting in s, taking action a first, and then following π (equation 3.13). It answers “how good is it to do this here?”, and it is the quantity a Q-table stores. Both are averages over everything the random transitions and the policy’s own randomness might produce, which is why a single observed return like the +3.98% above is one sample of a value, not the value.
The book also says how such values can be estimated with nothing but experience: follow the policy, and for each state keep a running average of the actual returns that followed it. As the state is visited more and more, the average converges to the state’s value. That is the whole idea behind the next three posts, with one refinement, which the recursion above makes possible.
Bellman: value now equals reward now plus value next
Because a return obeys , the expected return does too. The value of a state is the expected reward for leaving it plus the discounted value of wherever you land, averaged over the actions the policy might take and the places the environment might send you. That is the Bellman equationAn equation linking the value of a state to the values of the states that can follow it. for (Sutton and Barto’s equation 3.14), and in words it is the sentence in this section’s heading. Its power is that it ties every state’s value to its neighbours’ values, so an estimate of one can be improved from estimates of the others without waiting for an episode to finish.
An optimal policyA policy that is better than or equal to every other policy; there is always at least one. is one whose value is at least as high as every other policy’s in every state (section 3.6); there is always at least one, and all of them share the same optimal value functions, and . For these the Bellman equation takes a special form with no policy in it: the value of a state under the best policy is the best action’s reward plus the discounted value of the state it leads to, where “best” means the action with the highest value (equations 3.19 and 3.20). The recipe for acting is then one line long. In each state, look up the action values and take the largest. The hard part, and the subject of Q-learningA method that learns each action's value in each state, aiming straight at the best values whatever policy the agent is following.: one update rule, repeated, is filling in those values from experience.
Notation in other books
Murphy (section 34.5.1) writes the MDP as a tuple of a state set, an action set, a transition model, a reward model and a distribution for the first state, and writes one step as the transition (s, a, r, s′). His reward index is one behind Sutton and Barto’s: he writes the reward for the action at time t as r_t, they write it as R_{t+1}, to stress that the reward and the next state arrive together. Mitchell (section 13.2) writes the transition and reward functions as δ and r and, like Murphy, assumes they are deterministic in his first treatment. Control theory calls the environment the plant, the agent the controller, and a reward a cost with the sign flipped.
Check yourself
An agent's state is only "today's five-day return". It is long on one morning and in cash on another with the same return. What goes wrong?
The two mornings are the same state, but the best action differs, so the state breaks the Markov property. The property is a demand on the state, not a fact about the market. The methods will still run; they will simply learn the wrong thing. The fix is to put the holding in the state.
The day-1 return of the January 2023 episode is +3.98% at a discount of 1, +2.34% at 0.9 and +0.01% at 0.5. What does the discount factor decide?
The horizon: how far ahead the agent looks when it judges today’s choice. At 0.5 the rewards beyond the first few days barely count, so the agent cares about this week; at 0.99 it cares about this quarter. Same ten rewards, three verdicts.
Why is the +3.98% that followed the day-1 decision not the value of that state?
Because transitions are random, and +3.98% is what happened once. The value is the expected return from the state, an average over everything the transitions and the policy might produce. A single observed return is one sample of the value, which is why most methods move their estimates only a fraction of the way towards each new experience.
Traps
Table 2 lists the usual misreadings.
| People think | Actually |
|---|---|
| The Markov property is about the market | it is about the state label; a label that omits the holding or the trend breaks it |
| A good single outcome means a good action | one transition is one draw; the value is the average over many |
| The discount factor is a technicality | it sets the horizon the agent is judged on; 0.5 is this week, 0.99 is this quarter |
| Reward and return are the same thing | reward is one step’s number; return is the discounted sum of all the steps to come |
| The value of a state is its reward | a state can pay nothing now and be valuable because of where it leads |
The code
The snippet reproduces the three return columns of Table 1 from the end backwards. Its variables are in Table 3:
| Variable | Holds |
|---|---|
rewards | the ten daily returns of SPY from 2023-01-03, one reward per day of the episode |
to_go(gamma) | the discounted return from each day, built from the last day backwards |
import numpy as np
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"))
rewards = r.iloc[start:start + 10].values
def to_go(gamma):
g = np.zeros(len(rewards) + 1) # g[10] = 0: nothing comes after the last day
for t in range(len(rewards) - 1, -1, -1): # walk backwards from the last day
g[t] = rewards[t] + gamma * g[t + 1] # return now = reward now + gamma * return next
return g[:-1]
for gamma in (1.0, 0.9, 0.5):
print(gamma, " ".join(f"{100*x:+.2f}" for x in to_go(gamma)))
It prints three rows of ten numbers: the γ = 1 row starts +3.98, the γ = 0.9 row +2.34, the
γ = 0.5 row +0.01, matching Table 1. range(9, -1, -1) is Python’s way to count down from 9 to
0; the loop is the recursion from the text, run once.
The script behind the real numbers
The tables and the chart come from
examples/mdp-state-action-reward-value/discounting.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 mdp-state-action-reward-value/discounting.py.
Summary
Table 4 is the post in one line per idea.
| Idea | In one line | On the January 2023 episode |
|---|---|---|
| Markov property | the state carries everything about the past that matters | put the holding in the state |
| Random transitions | one experience is one draw from a distribution | the same action, in different states, earns +2.29% one day and −1.14% another |
| Reward versus return | one step’s number versus the discounted sum to come | day-1 reward −0.42%, return +3.98% |
| Discount factor | sets the horizon the choice is judged on | +3.98% at 1, +2.34% at 0.9, +0.01% at 0.5 |
| Recursion | return now = reward now + return next | |
| Value | the expected return from a state or an action | the +3.98% is one sample of it |
| Bellman | value now = reward now + discounted value next; optimal = take the best action | the equation the Q-table learns |
References
- Sutton and Barto, Reinforcement Learning: An Introduction, 2nd edition (MIT Press, 2018). Section 3.1 for the agent–environment interface, the dynamics function and the Markov property as a restriction on the state; section 3.2 for the reward hypothesis; section 3.3 for episodicA task whose interaction breaks into separate episodes, each ending in a terminal state. and continuing tasksA task whose interaction does not break into episodes but goes on without limit., the return (equations 3.7 and 3.8), the discount rate and the recursion (equation 3.9); section 3.5 for state and action values (equations 3.12 to 3.14) and estimating them by averaging returns; section 3.6 for optimal policies and the Bellman optimality equations (3.19 and 3.20).
- Kevin P. Murphy, Probabilistic Machine Learning: Advanced Topics (MIT Press, 2023). Section 34.5.1 for the MDP as a tuple and the transition notation; section 34.5.2 for partially observed MDPs; section 35.1 for the trajectoryThe sequence of states, actions and rewards that the agent and environment produce together, step after step. and the discounted cumulative reward.
- Tom M. Mitchell, Machine Learning (McGraw-Hill, 1997). Section 13.2 for the learning task as an MDP with transition and reward functions unknown to the agent.