Index breadth: how much of the S&P 500 or Nasdaq-100 is taking part
Pulls a year and a half of daily closes for every member of the chosen index once a day, then shows the share of members above their 50- and 200-day averages, new 52-week highs and lows, the day's advancers, and the five best and worst members. Members come from the platform's dated index list, and the panel says which date.
Pulls a year and a half of daily closes for every member of the chosen index once a day, then shows the share of members above their 50- and 200-day averages, new 52-week highs and lows, the day's advancers, and the five best and worst members. Members come from the platform's dated index list, and the panel says which date.
Shows: a plugin (plugin.toml + main.py + lib/), App, Enum input, universe() / universe_info(), historical(..., adjust="split") per member, @on.schedule, ui.row / ui.metric / ui.chart / ui.table / ui.text, vendored helpers imported as from lib.breadth import ....
"""Index breadth from daily closes, as pure functions
No platform calls: kept apart from main.py so it can be tested with plain lists and reused by
another plugin. `series` everywhere is {symbol: [(day, close), ...]} with the
days in order, oldest first.
"""
def sma(values, n):
return None if n < 1 or len(values) < n else sum(values[-n:]) / n
def above_average(closes, n):
"""True / False for the last close against its n-day average; None with
fewer than n closes (a member too new to say, never counted as below)."""
avg = sma(closes, n)
return None if avg is None else closes[-1] > avg
def at_extreme(closes, n):
""""high" when the last close is the highest of the last n, "low" when
the lowest, else None (None too with fewer than n closes)."""
if len(closes) < n:
return None
window = closes[-n:]
if closes[-1] >= max(window):
return "high"
if closes[-1] <= min(window):
return "low"
return None
def day_change(closes):
"""The last close's change from the one before, in percent, or None."""
if len(closes) < 2 or not closes[-2]:
return None
return (closes[-1] - closes[-2]) / closes[-2] * 100
def pct(part, whole):
return None if not whole else part / whole * 100
def snapshot(series, short=50, long=200, extreme=252):
"""Today's breadth over every member that has the history to say."""
closes = {s: [c for _, c in rows] for s, rows in series.items() if rows}
above_s = [v for v in (above_average(c, short) for c in closes.values()) if v is not None]
above_l = [v for v in (above_average(c, long) for c in closes.values()) if v is not None]
ext = [at_extreme(c, extreme) for c in closes.values()]
changes = {s: day_change(c) for s, c in closes.items()}
moved = [v for v in changes.values() if v is not None]
return {"members": len(series), "with_data": len(closes),
"above_short": pct(sum(above_s), len(above_s)),
"above_long": pct(sum(above_l), len(above_l)),
"new_highs": ext.count("high"), "new_lows": ext.count("low"),
"advancing": pct(sum(1 for v in moved if v > 0), len(moved)),
"changes": changes}
def above_history(series, n, days):
"""For each of the last `days` dates any member traded: the percent of
members (with n days of history by then) closing above their n-day
average. A list of (day, percent) pairs, oldest first."""
dates = sorted({d for rows in series.values() for d, _ in rows})[-days:]
out = []
for day in dates:
ups = total = 0
for rows in series.values():
closes = [c for d, c in rows if d <= day]
v = above_average(closes, n) if closes and rows[len(closes) - 1][0] == day else None
if v is not None:
total += 1
ups += v
out.append((day, pct(ups, total)))
return out
def leaders(changes, k=5):
"""The k best and k worst day changes: ([(symbol, pct)], [(symbol, pct)])."""
known = sorted(((s, v) for s, v in changes.items() if v is not None), key=lambda x: x[1])
return known[::-1][:k], known[:k]"""Index breadth: how much of the S&P 500 or Nasdaq-100 is taking part
Pulls a year and a half of daily closes for every member of the chosen index
once a day, then shows the share of members above their 50- and 200-day
averages, new 52-week highs and lows, the day's advancers, and the five best
and worst members. Members come from the platform's dated index list, and the
panel says which date.
Shows: a plugin (plugin.toml + main.py + lib/), App, Enum input, universe() / universe_info(), historical(..., adjust="split") per member, @on.schedule, ui.row / ui.metric / ui.chart / ui.table / ui.text, vendored helpers imported as `from lib.breadth import ...`.
"""
from datetime import date, datetime, timedelta, timezone
import while25
from while25 import App, on, ui
from while25.inputs import Enum
from lib.breadth import above_history, leaders, snapshot
ui.panel("index_breadth", label="Index Breadth")
ui.layout(
ui.text("source", "Members"),
ui.row(ui.metric("above_50", "Above 50-day"), ui.metric("above_200", "Above 200-day"),
ui.metric("advancing", "Advancing"), ui.metric("highs", "52-week highs"),
ui.metric("lows", "52-week lows")),
ui.chart("history", "% above 50-day, last 60 sessions"),
ui.row(ui.table("best", "Best today"), ui.table("worst", "Worst today")),
)
def closes_by_day(rows):
"""[(day, close)] from vendor rows, oldest first."""
return [(datetime.fromtimestamp(int(r["time"]) / 1000, timezone.utc).date(), r["close"])
for r in rows]
def fmt(v):
return None if v is None else round(v, 1)
class IndexBreadth(App):
id = "index_breadth"
label = "Index Breadth"
version = "1.0.0"
inputs = [Enum("index", choices=["sp500", "ndx100"], default="sp500")]
def on_start(self, ctx):
# Instance state, not module-level: a module is restarted without the
# file being re-imported, so anything at module scope would carry over.
self.loaded_on = None
@on.schedule(every="30m")
def refresh(self, ctx):
if self.loaded_on == date.today():
return
index = while25.params["index"]
info = while25.universe_info(index)
members = while25.universe(index)
start = (date.today() - timedelta(days=550)).isoformat()
series, failed = {}, []
for i, m in enumerate(members, 1):
if not while25.alive():
return # stopped mid-pull
try:
rows = while25.historical(m["canonical_id"], "1D", start=start, adjust="split")
series[m["symbol"]] = closes_by_day(rows)
except while25.While25Error as e:
failed.append(f"{m['symbol']} ({e.code})")
if i % 50 == 0:
while25.ui.push("source", f"{info['name']}: loading {i} of {len(members)}")
snap = snapshot(series)
best, worst = leaders(snap["changes"])
note = f"; no history for {len(failed)}: {', '.join(failed[:5])}" if failed else ""
while25.ui.push("source", f"{info['name']}, {info['count']} members as of "
f"{info['as_of']} ({info['source']}){note}")
while25.ui.push("above_50", fmt(snap["above_short"]))
while25.ui.push("above_200", fmt(snap["above_long"]))
while25.ui.push("advancing", fmt(snap["advancing"]))
while25.ui.push("highs", snap["new_highs"])
while25.ui.push("lows", snap["new_lows"])
while25.ui.push("history", [fmt(v) for _, v in above_history(series, 50, 60)])
while25.ui.push("best", [{"symbol": s, "change %": fmt(v)} for s, v in best])
while25.ui.push("worst", [{"symbol": s, "change %": fmt(v)} for s, v in worst])
self.loaded_on = date.today()# A plugin is a folder with this file. Copy the folder, rename it, and install
# it from the platform's plugin panel. The folder name must equal `name`.
name = "index-breadth" # lowercase, becomes the folder under plugins/
version = "1.0.0" # required: an unversioned plugin cannot be upgraded
entrypoint = "main.py" # run on install, and whenever you re-run it
label = "Index Breadth"
description = "S&P 500 or Nasdaq-100 breadth: members above their averages, new highs and lows, leaders and laggards."
# Libraries beyond the core set. The platform checks these BEFORE installing and
# refuses with the names it could not satisfy, so a user never sees ImportError.
requires = []Account desk as an HTML page
The same desk as blocks_dashboard.py, written as one HTML page on the platform's brand classes. Use `ui.html` when the arrangement needs markup of your own; the page has no script permission, so every value is computed here.
Quote recorder: a long-running loop that writes a CSV
Samples the quotes of a few ETFs once a second during regular hours and appends them to a CSV in the workspace, one file per day, with a small panel that shows how many rows it has written. A `run()` loop is the escape hatch for work the decorators do not cover; it checks `alive()` every pass so it stops the moment it is asked to.