Tabular Q-learning written from scratch with NumPy — a state from the observation, an action-value table, exploration, the update rule — trained and tested on the environment.
A library hides the learning. This page shows all of it: Q-learning, one of the oldest reinforcement-learning methods, in about forty lines that use nothing but NumPy and the environment.
01The idea
Q-learning keeps a table Q[state, action]: how much reward the agent expects if it takes that action in that state and acts well afterwards. After every step it moves the table's entry toward what it just saw:
Q[s, a] ← Q[s, a] + α · ( r + γ · max Q[s′, ·] − Q[s, a] )
| Symbol | Meaning | Here |
|---|---|---|
| α | learning rate — how far each update moves | 0.1 |
| γ | discount — how much the future counts | 0.9 |
| ε | exploration — the share of random actions | 0.2, falling to 0.02 |
| r | the step's reward | pnl@1, scaled |
| s′ | the state after the step |
When an episode ends in ruin (terminated) there is no future, so the update uses r alone. When it is merely cut off (truncated) the future still counts.
02A state from the observation
A table needs a small number of states, so the program buckets the observation: the window's move (the oldest close against the last, market[0][3]) into five buckets, times the side held (account[0]: short, flat, long) — fifteen states, three actions.
03The program
Save it as q_learning.py and run it with Bentrix open and a training workbench selected. It trains on 30 episodes, then compares the learned table with flat on ten test seeds.
import time
import numpy as np
import bentrix
from bentrix.gym import TradingEnv, evaluate
from bentrix.live import Remote
b = bentrix.connect(name="my-q-learner")
bench = b.workspace.get_state(depth="benches")["selected"]
for _ in range(120):
if b.agent.resource_read(bench)["engine"] == "ready":
break
time.sleep(0.5)
env = TradingEnv(bench, interval="H1", window=8, episode="window", episode_bars=24, reward="pnl@1", local=Remote(b))
EDGES = np.array([-0.002, -0.0005, 0.0005, 0.002]) # five buckets of the window's move
def state(obs):
move = int(np.digitize(obs["market"][0][3], EDGES)) # 0..4
side = int(obs["account"][0]) + 1 # 0 short, 1 flat, 2 long
return move * 3 + side
q = np.zeros((15, 3))
alpha, gamma = 0.1, 0.9
rng = np.random.default_rng(1)
episodes = 30
obs, info = env.reset(seed=1)
for episode in range(episodes):
if episode:
obs, info = env.reset() # the next training episode of seed 1
epsilon = max(0.02, 0.2 * (1 - episode / episodes))
s, done = state(obs), False
while not done:
a = int(rng.integers(3)) if rng.random() < epsilon else int(np.argmax(q[s]))
obs, reward, terminated, truncated, info = env.step(a)
r = reward / 10.0 # money, scaled to a few units
s2 = state(obs)
target = r if terminated else r + gamma * q[s2].max()
q[s, a] += alpha * (target - q[s, a])
s, done = s2, terminated or truncated
print("the learned table (rows: states, columns: flat, long, short):")
print(np.round(q, 3))
# Test on ten seeds the training never used: the learned table against flat.
test_seeds = range(101, 111)
learned = evaluate(lambda o: int(np.argmax(q[state(o)])), env, seeds=test_seeds)
flat = evaluate(lambda o: 0, env, seeds=test_seeds)
print("learned, IQM of the log return:", round(learned["iqm"], 6), "interval", [round(x, 6) for x in learned["interval"]])
print("flat, IQM of the log return:", round(flat["iqm"], 6))
env.close()
On a test machine it took about twelve minutes: thirty training episodes and twenty test episodes, each starting with a rewind and a replay to its window.
04Reading what it learned
Each row of the table is a state. In a row where the long column is largest, the agent has learned that long paid in that state; where every value is near zero, it has learned little — usually because the state was rarely visited.
- Thirty episodes are a start. Hundreds give a steadier table; watch the test score, not the training rewards.
- States are your design. Add a bucket of the last candle's range, or the hour of the day, and the table grows — more to learn, more episodes needed. A neural network is what replaces the table when the states become too many.
- The same in any language. Nothing here is Python-specific: the table is a 15 × 3 array, and every step is one
env_stepcall. The train a policy guide shows that loop in all nine languages.