MDPs: a state, an action, a reward and the value of what follows

Machine Learning Series 2

On this page
  1. The state has to carry the past
  2. Transitions can be random
  3. Reward is the goal; return is the score
  4. Value: the return you expect, not the one you got
  5. Bellman: value now equals reward now plus value next
  6. Traps
  7. The code
  8. Summary
  9. References

The previous post drew the loop: an agent sees a state, picks an action, receives a reward 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 process, MDP for short, is the picture made precise enough to compute with, and almost every idea in the rest of this series, the Q-table, 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 probability 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 property.

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–environment 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 trend 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 nothing in the state could have told you which. This matters for how the learner treats one experience. A single transition is one draw from a distribution, not the truth about the action, which is why every method in this series moves 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 everything we mean by a goal can be written as “maximise the expected sum of a received scalar signal”, and their warning is the one from the previous post: the reward says what you want, not how to get it. Reward a chess agent for capturing pieces and it will capture pieces while losing games.

The return is what the agent actually maximises: the rewards still to come, added up. For an episode 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 factor γ\key{\gamma} 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

Gt=Rt+1+γ Rt+2+γ2 Rt+3+⋯=∑k=0∞γk Rt+k+1\key{G_t} = \good{R_{t+1}} + \key{\gamma}\,\good{R_{t+2}} + \key{\gamma}^{2}\,\good{R_{t+3}} + \cdots = \sum_{k=0}^{\infty} \key{\gamma}^{k}\,\good{R_{t+k+1}}

A reward k steps ahead is worth γk\key{\gamma}^k of what it would be worth today. With γ=0.9\key{\gamma} = \key{0.9} a reward seven days away counts for less than half; with γ=0.99\key{\gamma} = \key{0.99} that takes 69 days. At γ=0\key{\gamma} = 0 the agent is myopic and cares only about the next reward; as γ\key{\gamma} 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.

Here are the ten rewards of the January 2023 episode (long SPY from 2023-01-03) with the return from each day computed three ways:

DayReward that dayReturn 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 3.98%\key{3.98\%} if every later day counts in full, 2.34%\key{2.34\%} at a discount of 0.9, and 0.01%\key{0.01\%} at 0.5, where the rewards beyond the first few days barely register. Same ten numbers, three verdicts. 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.

{"panels":[{"x0":46.52,"x1":565.2,"y0":29.16,"y1":223.28,"title":"1. How much a reward k days away counts today","xlabel":"Days ahead the reward arrives","ylabel":"Weight the reward gets (1 = full)","xlog":false},{"x0":46.52,"x1":565.2,"y0":311.96,"y1":506.08,"title":"2. The same ten rewards, summed with three discount factors","xlabel":"Day of the episode (trading days from 2023-01-03)","ylabel":"Discounted reward still to come (% of the position)","xlog":false}],"series":[{"panel":0,"label":"discount factor 1.0","color":"var(--chart-grey, #a3a19c)","x":[0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0,13.0,14.0,15.0,16.0,17.0,18.0,19.0,20.0],"y":[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0],"sx":[70.1,93.67,117.25,140.83,164.4,187.98,211.56,235.13,258.71,282.28,305.86,329.44,353.01,376.59,400.17,423.74,447.32,470.89,494.47,518.05,541.62],"sy":[37.98,37.98,37.98,37.98,37.98,37.98,37.98,37.98,37.98,37.98,37.98,37.98,37.98,37.98,37.98,37.98,37.98,37.98,37.98,37.98,37.98]},{"panel":0,"label":"discount factor 0.9","color":"var(--chart-maroon, #b6262c)","x":[0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0,13.0,14.0,15.0,16.0,17.0,18.0,19.0,20.0],"y":[1.0,0.9,0.81,0.729,0.6561,0.59049,0.531441,0.478297,0.430467,0.38742,0.348678,0.313811,0.28243,0.254187,0.228768,0.205891,0.185302,0.166772,0.150095,0.135085,0.121577],"sx":[70.1,93.67,117.25,140.83,164.4,187.98,211.56,235.13,258.71,282.28,305.86,329.44,353.01,376.59,400.17,423.74,447.32,470.89,494.47,518.05,541.62],"sy":[37.98,55.63,71.51,85.81,98.67,110.25,120.67,130.05,138.49,146.08,152.92,159.08,164.61,169.6,174.08,178.12,181.75,185.02,187.97,190.62,193.0]},{"panel":0,"label":"discount factor 0.5","color":"var(--chart-blue, #3b6ea5)","x":[0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0,13.0,14.0,15.0,16.0,17.0,18.0,19.0,20.0],"y":[1.0,0.5,0.25,0.125,0.0625,0.03125,0.015625,0.0078125,0.00390625,0.00195312,0.000976562,0.000488281,0.000244141,0.00012207,6.10352e-05,3.05176e-05,1.52588e-05,7.62939e-06,3.8147e-06,1.90735e-06,9.53674e-07],"sx":[70.1,93.67,117.25,140.83,164.4,187.98,211.56,235.13,258.71,282.28,305.86,329.44,353.01,376.59,400.17,423.74,447.32,470.89,494.47,518.05,541.62],"sy":[37.98,126.22,170.34,192.4,203.42,208.94,211.7,213.08,213.76,214.11,214.28,214.37,214.41,214.43,214.44,214.45,214.45,214.45,214.45,214.45,214.45]}]} 2026-10-21T04:13:06.223905 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/ 0.0 2.5 5.0 7.5 10.0 12.5 15.0 17.5 20.0 Days ahead the reward arrives 0.0 0.2 0.4 0.6 0.8 1.0 Weight the reward gets (1 = full) 1. How much a reward k days away counts today discount factor 1.0 discount factor 0.9 discount factor 0.5 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 Discounted reward still to come (% of the position) 2. The same ten rewards, summed with three discount factors discount factor 1.0 discount factor 0.9 discount factor 0.5

The table 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

Gt=Rt+1+γ Gt+1\key{G_t} = \good{R_{t+1}} + \key{\gamma}\,\key{G_{t+1}}

Check it on the top row at γ=0.9\key{\gamma} = \key{0.9}: −0.42%+0.9×3.07%=2.34%-0.42\% + 0.9 \times 3.07\% = 2.34\%. 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 value under a policy, written vπ(s)\key{v_\pi(s)}, 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 value, written qπ(s,a)\key{q_\pi(s, a)}, 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 Gt=Rt+1+γ Gt+1\key{G_t} = \good{R_{t+1}} + \key{\gamma}\,\key{G_{t+1}}, 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 equation for vπ\key{v_\pi} (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 policy 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, v∗\key{v_*} and q∗\key{q_*}. 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-learning: 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.

Traps

People thinkActually
The Markov property is about the marketit is about the state label; a label that omits the holding or the trend breaks it
A good single outcome means a good actionone transition is one draw; the value is the average over many
The discount factor is a technicalityit sets the horizon the agent is judged on; 0.5 is this week, 0.99 is this quarter
Reward and return are the same thingreward is one step’s number; return is the discounted sum of all the steps to come
The value of a state is its rewarda state can pay nothing now and be valuable because of where it leads

The code

The snippet reproduces the three return columns of the table from the end backwards. Variables:

VariableHolds
rewardsthe 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 the table. 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

IdeaIn one lineOn the January 2023 episode
Markov propertythe state carries everything about the past that mattersput the holding in the state
Random transitionsone experience is one draw from a distributionthe same “long” earns +2.29% one day and −1.14% another
Reward versus returnone step’s number versus the discounted sum to comeday-1 reward −0.42%, return +3.98%
Discount factorsets the horizon the choice is judged on+3.98% at 1, +2.34% at 0.9, +0.01% at 0.5
Recursionreturn now = reward now + γ × return next−0.42 + 0.9 × 3.07 = 2.34
Valuethe expected return from a state or an actionthe +3.98% is one sample of it
Bellmanvalue now = reward now + discounted value next; optimal = take the best actionthe 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 episodic and continuing tasks, 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 trajectory 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.