A golden cross happens when a stock's 50-day simple moving average (SMA) moves above its 200-day SMA. A death cross is the reverse. Traders watch both as slow trend signals. Checking them by hand across a watchlist gets old quickly, and calculating 200-day averages yourself means downloading years of candles first. This tutorial skips that step. Mboum's SMA endpoint returns the averages already calculated, and a short Python script turns them into alerts.
Prerequisites
- Python 3 and the
requestslibrary. - A Mboum API key. The free plan is enough for a short watchlist. Get one at mboum.com/pages/api.
The SMA endpoint
GET https://api.mboum.com/v1/markets/indicators/sma has weight 2. These parameters matter here:
ticker(orsymbol): one symbol per request.interval:1dgives daily candles over the last 5 years, which is plenty for a 200-day average.series_type: the price to average. Useclose.time_period: the number of candles in each average, from 1 to 500.limit: how many of the newest values to return.
curl --get "https://api.mboum.com/v1/markets/indicators/sma" \
--data-urlencode "ticker=AAPL" \
--data-urlencode "interval=1d" \
--data-urlencode "series_type=close" \
--data-urlencode "time_period=50" \
--data-urlencode "limit=30" \
--header "Authorization: Bearer YOUR_MBOUM_API_KEY"
The response has a meta object and a body list, oldest value first. Each item is a Unix timestamp in seconds and the average. This is a trimmed example:
{
"meta": {
"symbol": "AAPL",
"interval": "1d",
"indicator": "Simple Moving Average (SMA)",
"time_period": "50"
},
"body": [
{"timestamp": 1794321000, "SMA": 337.267},
{"timestamp": 1794407400, "SMA": 337.877}
]
}
How the script finds a cross
There is one call for the 50-day average and one for the 200-day average. Both use the same daily candles, so their timestamps match. The script keeps only the timestamps present in both and computes the gap, 50-day minus 200-day, for each day. A golden cross is a day where the gap goes from zero or below to above zero. A death cross is the opposite. It reports crosses from the last few candles, and it remembers what it has already reported in a small JSON file so a cron job does not repeat itself.
import json
import time
from datetime import datetime, timezone
import requests
URL = "https://api.mboum.com/v1/markets/indicators/sma"
HEADERS = {"Authorization": "Bearer YOUR_MBOUM_API_KEY"}
WATCHLIST = ["AAPL", "MSFT", "NVDA", "TSLA", "AMD"]
LOOKBACK = 5 # report crosses from the last 5 daily candles
LIMIT = 30 # SMA values requested per call
SEEN_FILE = "seen_crosses.json"
def fetch_sma(symbol, period):
params = {
"ticker": symbol,
"interval": "1d",
"series_type": "close",
"time_period": period,
"limit": LIMIT,
}
resp = requests.get(URL, headers=HEADERS, params=params, timeout=30)
resp.raise_for_status()
data = resp.json()
body = data.get("body")
if data.get("success") is False or not body:
raise ValueError(data.get("message") or "No data returned")
return {row["timestamp"]: row["SMA"] for row in body}
def check(symbol):
fast = fetch_sma(symbol, 50)
slow = fetch_sma(symbol, 200)
stamps = sorted(set(fast) & set(slow))
gaps = [(t, fast[t] - slow[t]) for t in stamps]
crosses = []
for (_, before), (t, after) in zip(gaps, gaps[1:]):
if before <= 0 < after:
crosses.append((t, "GOLDEN CROSS"))
elif before >= 0 > after:
crosses.append((t, "DEATH CROSS"))
recent = set(stamps[-LOOKBACK:])
crosses = [c for c in crosses if c[0] in recent]
last = stamps[-1]
return fast[last], slow[last], crosses
def load_seen():
try:
with open(SEEN_FILE) as f:
return set(json.load(f))
except FileNotFoundError:
return set()
def main():
seen = load_seen()
for symbol in WATCHLIST:
try:
sma50, sma200, crosses = check(symbol)
except (requests.RequestException, ValueError) as exc:
print(f"{symbol:<6} skipped: {exc}")
continue
gap = (sma50 - sma200) / sma200 * 100
print(f"{symbol:<6} 50D {sma50:>9.2f} 200D {sma200:>9.2f} gap {gap:+6.1f}%")
for stamp, kind in crosses:
day = datetime.fromtimestamp(stamp, timezone.utc).strftime("%Y-%m-%d")
key = f"{symbol}:{day}:{kind}"
if key not in seen:
print(f" ALERT {kind} on {day}")
seen.add(key)
time.sleep(0.3)
with open(SEEN_FILE, "w") as f:
json.dump(sorted(seen), f)
if __name__ == "__main__":
main()
Replace YOUR_MBOUM_API_KEY and edit WATCHLIST. Each line shows the latest 50-day and 200-day values and how far apart they are. This line comes from a live response for AAPL:
AAPL 50D 337.88 200D 300.27 gap +12.5%
A symbol with a fresh cross gets an extra line. This one uses a made-up symbol:
XYZ 50D 101.50 200D 100.00 gap +1.5%
ALERT GOLDEN CROSS on 2026-11-09
Run it every trading day
Schedule it after the US close. This cron entry runs at 5:30 PM on weekdays in the server's time zone, so adjust it if your server is not on US Eastern time:
30 17 * * 1-5 cd /path/to/project && python3 golden_cross.py
To send the alert somewhere, replace the print call under ALERT with a request to your own webhook or an email function.
Best practices
- Count the cost. Each symbol takes two calls at weight 2, so 4 requests per symbol per run. Five symbols once a day is about 20 requests a run, or roughly 400 to 460 a month. Keep the list short on a small plan.
- Check for failures. A bad ticker can return HTTP 200 with
"success": falseand a message, and a bad parameter returns HTTP 422. The script treats both as a skipped symbol. - Run after the close. While the market is open, the newest daily value may include a candle that is still forming, and a cross can appear and disappear within the day.
- Use a window, not a single day.
LOOKBACKcatches a cross even if one run is missed, and the seen file stops repeat alerts.
Next steps
Add a second filter before you act on an alert, such as the volume checks in our Screener API guide. Moving averages lag price, and crosses often reverse in sideways markets. For parameters and the other indicators, see the API documentation, and get a free key at mboum.com/pages/api.
The data is for information only. It is not investment advice.