New for 2027The MonsterDesk course and run-it-yourself software. Founding prices can be reserved now.Course and run-it-yourself software.See what is on offer
MonsterDesk

Free lesson · Module 2: Your first agent · about 10 min

2.1 What an agent is: your first rule-based agent

A short video intro to the lesson. The full lesson videos come with the course in early 2027.

Every agent on the desk, however clever, answers the same four questions on every bar: should I be in, which way, how much, and when do I get out? Your first agent answers them with one rule.

The rule

From Module 1 you have a chart of SPY with its 50-hour average. The rule: be in the market when the price is above its 50-hour average, and out when it's below. One direction (long only), one size (all in or all out), exit when the rule flips.

The code

Save this as first_agent.py in your my-desk folder, next to spy_1h.csv:

import pandas as pd

bars = pd.read_csv("spy_1h.csv", index_col=0, parse_dates=True)
bars["avg50"] = bars["close"].rolling(50).mean()

def decide(close, avg50):
    """The whole agent: be in the market when the price is above its 50-hour average."""
    if pd.isna(avg50):
        return 0          # not enough history yet: stay out
    return 1 if close > avg50 else 0

bars["position"] = [decide(c, a) for c, a in zip(bars["close"], bars["avg50"])]
changes = bars[bars["position"].diff().fillna(0) != 0]
for t, row in changes.iterrows():
    print(t, "BUY " if row["position"] == 1 else "SELL", f"{row['close']:.2f}")
print(f"in the market {bars['position'].mean():.0%} of the time")

It prints every time the agent would buy or sell, and how much of the time it would be in the market.

Why a function called decide()

The agent is the decide() function, nothing else. Keeping the decision in one small function means the same code can be tested on history (next lesson) and later run live (lesson 2.5). On the desk this is a rule worth keeping: what you test must be exactly what runs.

What it doesn't know yet

  • Whether it would have made money. That's the backtest, next.
  • How much to risk, or where a stop goes. Lesson 2.3.
  • Whether it only looks good because of the data you happened to download. That's the exam, in Module 3.

Checklist

  • first_agent.py prints a list of buys and sells
  • You can say the agent's rule in one sentence
Add MonsterDesk to your home screenOpen the live desk like an app.
Follow the desk free