11 Claude skills for day trading: scan thousands of charts, track breaking news, time every entry and exit, and replay every outcome before you risk a dollar.
The Trader skill v2: 11 day-trading skills
Jake Schincariol3d0f4ef6986f
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonnew file mode 100644index 0000000..9721e05--- /dev/null+++ b/.claude-plugin/marketplace.json@@ -0,0 +1,18 @@+{+ "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",+ "name": "day-trader-skill",+ "description": "The Day Trader skill pack for Claude: the Trader skill v2",+ "owner": {+ "name": "Jake Schincariol",+ "url": "https://opusjake.ai"+ },+ "plugins": [+ {+ "name": "day-trader-skill",+ "description": "Eleven Claude skills for day trading: a chart scanner, a news monitor, an entry timer, an exit planner, a time machine that replays 10,000 sessions, a risk manager, a budget manager, an order executor (paper by default, never without your yes), price alerts, an earnings analyst and a Pelosi tracker.",+ "source": "./",+ "category": "productivity",+ "homepage": "https://github.com/Jakeschincariol/day-trader-skill"+ }+ ]+}diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonnew file mode 100644index 0000000..c25d6fe--- /dev/null+++ b/.claude-plugin/plugin.json@@ -0,0 +1,22 @@+{+ "name": "day-trader-skill",+ "description": "11 Claude skills for day trading: scan thousands of charts, track breaking news, time every entry and exit, and replay every outcome before you risk a dollar.",+ "version": "2.0.0",+ "author": {+ "name": "Jake Schincariol",+ "url": "https://opusjake.ai"+ },+ "homepage": "https://github.com/Jakeschincariol/day-trader-skill",+ "repository": "https://github.com/Jakeschincariol/day-trader-skill",+ "license": "MIT",+ "keywords": [+ "claude-code",+ "claude-skills",+ "day-trading",+ "stock-market",+ "backtesting",+ "opening-range-breakout",+ "paper-trading"+ ],+ "skills": "./"+}diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..ac31f09--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Jake Schincariol++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..74984ac--- /dev/null+++ b/README.md@@ -0,0 +1,216 @@+# The Day Trader skill++11 Claude skills for day trading: scan thousands of charts, track breaking news, time every entry and exit, and replay every outcome before you risk a dollar.++Free, MIT, no signup, no API key. The tools are plain Python that read free+public data: Yahoo Finance charts, Nasdaq Trader's symbol lists, SEC EDGAR+and the House Clerk.++One scans thousands of charts for setups. Another tracks breaking news on+every stock you watch. One watches a setup bar by bar and tells you the moment+to get in, and another sets your stop and your target before you do. And the+craziest one is the Time Machine: before you risk a dollar, it replays the+rest of the session 10,000 times from the stock's own recent bars, plus every+past day the same setup fired, and tells you the honest odds.++And no trade goes through until you say yes. Nothing in this pack can place+an order on its own. Paper trading is the default.++> **Looking for the original Trader skill?** Copy an investor's 13F, the+> stock screener, tax lots and rebalancing live in+> [github.com/Jakeschincariol/trader-skill](https://github.com/Jakeschincariol/trader-skill).+> This repo is its day-trading sequel: the Trader skill v2.++## Install++Paste this into Claude:++```+https://github.com/Jakeschincariol/day-trader-skill++install skill+```++Or as a plugin, in Claude Code:++```+/plugin marketplace add Jakeschincariol/day-trader-skill+/plugin install day-trader-skill@day-trader-skill+```++Claude Code namespaces plugin skills, so installed as a plugin they show up as+`/day-trader-skill:trader-scanner` and so on. Copy the folders instead if you want+plain `/trader-scanner`:++```bash+git clone https://github.com/Jakeschincariol/day-trader-skill.git+cp -r day-trader-skill/trader-* ~/.claude/skills/+```++Project-local instead of global: copy the same folders into your repo's+`.claude/skills/`. No Claude Code at all? Paste any single `SKILL.md` at the+top of a chat and it runs as a mode. You lose the Python tools, but the method+works.++The tools need Python 3.8 or newer. Nothing to pip install. The SEC tools+(news filings, the analyst) ask you to identify yourself: put your name and+email in `trader/config.json` (`"sec_user_agent": "Your Name [email protected]"`)+or in the `SEC_USER_AGENT` environment variable.++## The eleven++| command | job | what it does |+| --- | --- | --- |+| `/trader-scanner` | Chart Scanner | Scans thousands of charts for setups: opening-range breakouts, flags, oversold bounces. |+| `/trader-news` | News Monitor | Tracks breaking news on every stock you watch and flags what moves it. |+| `/trader-entry` | Entry Timer | Watches a setup bar by bar and tells you the moment to get in. |+| `/trader-exit` | Exit Planner | Sets your stop and your target before you enter, so you know when to get out. |+| `/trader-timemachine` | Time Machine | Replays every possible outcome of a trade before you risk a dollar: 10,000 simulated sessions plus every past time the setup fired. |+| `/trader-risk` | Risk Manager | Checks every trade against your limits and stops anything over them. |+| `/trader-budget` | Budget Manager | Sizes every position to your budget and your max loss per trade. |+| `/trader-broker` | Order Executor | Sends approved orders to your broker, paper trading by default, never without your yes. |+| `/trader-alerts` | Price Alerts | Rings when a price, a stop or the opening bell hits. |+| `/trader-analyst` | Earnings Analyst | Reads earnings reports and sums up what changed. |+| `/trader-pelosi` | Pelosi Tracker | Reads Congress's stock-trade disclosures the minute they are filed. |++## How to use it++Everything lands in a `trader/` folder in your project, and each skill reads+what the last one wrote:++```+scanner -> news -> entry -> exit -> timemachine -> budget -> risk -> broker (one trade)+alerts: stop, target, flat by the close (while it is open)+news / analyst / pelosi (on a schedule)+```++An example, the trade in the reel: Tesla, Monday October 19 2026, real data.++1. **`/trader-scanner`** at 10:15 AM ET: of the 231 charts in the reel's+ scan, 42 had closed above their 15-minute opening range. TSLA is one: range 354.47 to 362.18,+ the 10:10 candle closed at 364.18, 0.55 % over the top.+2. **`/trader-news`**: the morning's TSLA headlines, in New York time+ ("Tesla-SpaceX Merger Mania Strikes Wall Street Ahead of Earnings", 8:04,+ tagged earnings and deal). Tesla reports this week: a day trade is out+ before the close, so it is not exposed to the report.+3. **`/trader-entry`** watched TSLA bar by bar. At 10:12 it said waiting (the+ 10:10 bar was still forming). At 10:15 it said triggered: the first+ 5-minute close above the range, 364.18.+4. **`/trader-exit`** set the plan before the entry: stop at the range's+ midpoint, 358.32, so 5.86 a share at risk; target one times that risk,+ 370.04; flat by 3:55 PM either way.+5. **`/trader-timemachine`** replayed the rest of the day 10,000 times, each+ 5-minute candle drawn from TSLA's own candles at that time of day over the+ previous 59 sessions (seed 19, so anyone can repeat it): target first+ 29.4 %, stop first 25.5 %, still open at the close 45.1 %. It also re-ran+ the same rule on those 59 real sessions: it fired 33 times, 13 hit the+ target, 15 the stop, 5 neither. Its verdict: close to a coin flip. That is+ the point of looking before you risk a dollar.+6. **`/trader-budget`** with a $5,000 account and a $50 max loss per trade:+ 50 / 5.86 = 8 shares ($2,913.44). If the stop fills at 358.32, the loss is+ $46.88. It writes one bracket order: buy 8 TSLA, stop-loss 358.32,+ take-profit 370.04.+7. **`/trader-risk`** checks it against your limits: the max loss, the daily+ loss limit, trades per day, reward to risk, the entry window, position+ size and cash. PASS or BLOCK, with the reason.+8. **`/trader-broker`** shows you the ticket in plain words. You type yes for+ that exact order. Claude calls your brokerage connector (Alpaca's MCP+ server, paper account by default), and Claude's own "Allow once / Deny"+ card asks you one more time.+9. **`/trader-alerts`** rings on the stop, the target and at 3:55 PM to+ flatten whatever is still open.++## The tools++All standard-library Python. The data tools read public endpoints and are+polite about it.++```bash+python3 trader-scanner/scan.py universe # ~5,900 US stocks, Nasdaq Trader+python3 trader-scanner/scan.py daily # pre-market setups, whole universe+python3 trader-scanner/scan.py orb --at 10:15 # opening-range breakouts so far+python3 trader-news/news.py --tickers TSLA --hours 12 # headlines, 8-Ks, today's move+python3 trader-entry/entry.py check TSLA --setup orb # waiting / triggered / expired+python3 trader-entry/entry.py watch TSLA --every 30 # bar by bar until it triggers+python3 trader-exit/exit.py plan --stop or-mid --target 1R --write # -> trader/plan.json+python3 trader-timemachine/timemachine.py run --write # 10,000 replays + the history+python3 trader-budget/size.py --write # -> trader/orders.json+python3 trader-risk/check.py # PASS / BLOCK per order+python3 trader-broker/ticket.py show # the tickets, READY or not+python3 trader-alerts/alerts.py add --from-plan # stop, target, flat by close+python3 trader-alerts/alerts.py check # rings what hit, once+python3 trader-analyst/facts.py TSLA # quarters, growth, EPS+python3 trader-pelosi/ptr.py index --member pelosi # her PTRs this year+```++```bash+python3 -m unittest discover -s tests -v+```++The tests run offline, on fixtures cut from real data: TSLA's 5-minute bars+for the 60 days to October 19 2026, the 10:15 AM opening-range scan, Yahoo's+TSLA headlines that morning, the House Clerk's 2026 index, real PTR text and+real XBRL facts. They reproduce every number in the example above.++## Fine print++**Not financial advice.** This is software that reads public data and does+arithmetic. It does not know your situation and it cannot see the future.+Most people who day trade lose money. You can lose money. Decide for+yourself, and talk to a licensed professional if you need advice.++**No trade goes through until you say yes.** Only `/trader-broker` can lead to+an order, and only after `/trader-risk` passes that exact order and you type+yes for it in the chat. Set your brokerage tool to "Needs approval" in Claude+(Customize, Connectors, tool permissions), never "Always allow", so Claude's+own "Allow once / Deny" card is a second check. No options, margin, short+selling or leverage unless you turn them on.++**Paper first.** `"paper": true` is the default in `config.example.json`, and+Alpaca's MCP server defaults to its paper account. Keys live in environment+variables, never in the chat.++**The Time Machine is a simulation, not a prediction.** It is built from the+stock's own last 60 days of 5-minute bars. The future can do things those 60+days never did: an earnings report, a halt, a headline. Treat its odds as a+reality check, never as a promise.++**A stop is a plan, not a guarantee.** In a fast market or across a gap, a+stop order can fill well past its price. The max loss shown is the loss at+the stop price.++**The data is free and unofficial.** Yahoo Finance's chart endpoint is not an+official API: it can lag, change or rate-limit you. The scanner and the entry+timer read 1-minute or 5-minute bars, not every tick. Check anything that+matters against your broker before you act on it.++**Day-trading rules.** FINRA removed the $25,000 pattern-day-trader minimum+on June 4, 2026 (Regulatory Notice 26-10), and brokers may phase the change+in until October 20, 2027, so yours may still apply the old rule. If it does,+set `"pdt_guard": true` and `/trader-risk` counts your day trades.++**Congress's trades are public, not inside information.** Members must disclose+trades over $1,000 within 45 days (the STOCK Act). The Pelosi skill reads those+public filings the minute they post.++**Taxes.** Day-trading gains are short-term gains, and frequent trading makes+wash sales likely. Nothing here is tax advice.++## Files++```+trader-scanner/ SKILL.md, scan.py+trader-news/ SKILL.md, news.py+trader-entry/ SKILL.md, entry.py+trader-exit/ SKILL.md, exit.py+trader-timemachine/ SKILL.md, timemachine.py+trader-risk/ SKILL.md, check.py+trader-budget/ SKILL.md, size.py, config.example.json, targets.example.json+trader-broker/ SKILL.md, ticket.py, claude_desktop_config.example.json+trader-alerts/ SKILL.md, alerts.py, alerts.example.json+trader-analyst/ SKILL.md, facts.py, metrics.example.json+trader-pelosi/ SKILL.md, ptr.py+tests/ unittest suite + offline fixtures+```++MIT. Made by [Jake Schincariol](https://opusjake.ai).diff --git a/tests/_load.py b/tests/_load.pynew file mode 100644index 0000000..e5dd294--- /dev/null+++ b/tests/_load.py@@ -0,0 +1,15 @@+"""Load a script from a skill folder (the folder names have hyphens)."""++import importlib.util+import os++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+FIX = os.path.join(ROOT, "tests", "fixtures")+++def load(folder, name):+ path = os.path.join(ROOT, folder, name + ".py")+ spec = importlib.util.spec_from_file_location("trader_" + name, path)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return moddiff --git a/tests/fixtures/trader-alerts/stooq-AAPL.csv b/tests/fixtures/trader-alerts/stooq-AAPL.csvnew file mode 100644index 0000000..83e5293--- /dev/null+++ b/tests/fixtures/trader-alerts/stooq-AAPL.csv@@ -0,0 +1,2 @@+Symbol,Date,Time,Open,High,Low,Close,Volume+AAPL.US,2026-10-13,22:00:09,344.67,348.15,340.74,341.27,38946900diff --git a/tests/fixtures/trader-alerts/stooq-ZZZZ.csv b/tests/fixtures/trader-alerts/stooq-ZZZZ.csvnew file mode 100644index 0000000..84ce25f--- /dev/null+++ b/tests/fixtures/trader-alerts/stooq-ZZZZ.csv@@ -0,0 +1,2 @@+Symbol,Date,Time,Open,High,Low,Close,Volume+ZZZZ.US,N/D,N/D,N/D,N/D,N/D,N/D,N/Ddiff --git a/tests/fixtures/trader-alerts/yahoo-AAPL.json b/tests/fixtures/trader-alerts/yahoo-AAPL.jsonnew file mode 100644index 0000000..cf8d4c3--- /dev/null+++ b/tests/fixtures/trader-alerts/yahoo-AAPL.json@@ -0,0 +1 @@+{"chart":{"result":[{"meta":{"currency":"USD","symbol":"AAPL","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":345479400,"regularMarketTime":1791921601,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":341.27,"regularMarketChangePercent":0.088,"fulldayPrice":341.03,"fulldayChange":-0.62,"fulldayChangePercent":-0.182,"fiftyTwoWeekHigh":348.15,"fiftyTwoWeekLow":243.42,"regularMarketDayHigh":348.15,"regularMarketDayLow":340.74,"regularMarketVolume":38897865,"longName":"Apple Inc.","shortName":"Apple Inc.","chartPreviousClose":340.97,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","start":1791878400,"end":1791898200,"gmtoffset":-14400},"regular":{"timezone":"EDT","start":1791898200,"end":1791921600,"gmtoffset":-14400},"post":{"timezone":"EDT","start":1791921600,"end":1791936000,"gmtoffset":-14400}},"dataGranularity":"1d","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1791898200],"indicators":{"quote":[{"low":[340.739990234375],"open":[344.6700134277344],"volume":[38946900],"high":[348.1499938964844],"close":[341.2699890136719]}],"adjclose":[{"adjclose":[341.2699890136719]}]}}],"error":null}}\ No newline at end of filediff --git a/tests/fixtures/trader-alerts/yahoo-AXP.json b/tests/fixtures/trader-alerts/yahoo-AXP.jsonnew file mode 100644index 0000000..277b9f5--- /dev/null+++ b/tests/fixtures/trader-alerts/yahoo-AXP.json@@ -0,0 +1 @@+{"chart":{"result":[{"meta":{"currency":"USD","symbol":"AXP","exchangeName":"NYQ","fullExchangeName":"NYSE","instrumentType":"EQUITY","firstTradeDate":76253400,"regularMarketTime":1791921746,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":309.84,"regularMarketChangePercent":-0.542,"fulldayPrice":309.7,"fulldayChange":-1.472,"fulldayChangePercent":-0.473,"fiftyTwoWeekHigh":387.49,"fiftyTwoWeekLow":290.97,"regularMarketDayHigh":314.0,"regularMarketDayLow":308.075,"regularMarketVolume":3156184,"longName":"American Express Company","shortName":"American Express Company","chartPreviousClose":311.53,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","start":1791878400,"end":1791898200,"gmtoffset":-14400},"regular":{"timezone":"EDT","start":1791898200,"end":1791921600,"gmtoffset":-14400},"post":{"timezone":"EDT","start":1791921600,"end":1791936000,"gmtoffset":-14400}},"dataGranularity":"1d","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1791898200],"indicators":{"quote":[{"low":[308.0799865722656],"high":[314.0],"volume":[3155900],"open":[313.8599853515625],"close":[309.8399963378906]}],"adjclose":[{"adjclose":[309.8399963378906]}]}}],"error":null}}\ No newline at end of filediff --git a/tests/fixtures/trader-alerts/yahoo-BAC.json b/tests/fixtures/trader-alerts/yahoo-BAC.jsonnew file mode 100644index 0000000..02de549--- /dev/null+++ b/tests/fixtures/trader-alerts/yahoo-BAC.json@@ -0,0 +1 @@+{"chart":{"result":[{"meta":{"currency":"USD","symbol":"BAC","exchangeName":"NYQ","fullExchangeName":"NYSE","instrumentType":"EQUITY","firstTradeDate":99153000,"regularMarketTime":1791921602,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":53.96,"regularMarketChangePercent":-1.136,"fulldayPrice":53.18,"fulldayChange":-1.843,"fulldayChangePercent":-3.376,"fiftyTwoWeekHigh":65.23,"fiftyTwoWeekLow":46.12,"regularMarketDayHigh":54.85,"regularMarketDayLow":53.64,"regularMarketVolume":44988032,"longName":"Bank of America Corporation","shortName":"Bank of America Corporation","chartPreviousClose":54.58,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","start":1791878400,"end":1791898200,"gmtoffset":-14400},"regular":{"timezone":"EDT","start":1791898200,"end":1791921600,"gmtoffset":-14400},"post":{"timezone":"EDT","start":1791921600,"end":1791936000,"gmtoffset":-14400}},"dataGranularity":"1d","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1791898200],"indicators":{"quote":[{"close":[53.959999084472656],"volume":[44949900],"open":[54.439998626708984],"high":[54.849998474121094],"low":[53.63999938964844]}],"adjclose":[{"adjclose":[53.959999084472656]}]}}],"error":null}}\ No newline at end of filediff --git a/tests/fixtures/trader-alerts/yahoo-GOOGL.json b/tests/fixtures/trader-alerts/yahoo-GOOGL.jsonnew file mode 100644index 0000000..acfb7d6--- /dev/null+++ b/tests/fixtures/trader-alerts/yahoo-GOOGL.json@@ -0,0 +1 @@+{"chart":{"result":[{"meta":{"currency":"USD","symbol":"GOOGL","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":1092922200,"regularMarketTime":1791921601,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":353.78,"regularMarketChangePercent":0.301,"fulldayPrice":354.77,"fulldayChange":1.492,"fulldayChangePercent":0.423,"fiftyTwoWeekHigh":408.61,"fiftyTwoWeekLow":244.15,"regularMarketDayHigh":358.58,"regularMarketDayLow":351.6,"regularMarketVolume":22270289,"longName":"Alphabet Inc.","shortName":"Alphabet Inc.","chartPreviousClose":352.72,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","start":1791878400,"end":1791898200,"gmtoffset":-14400},"regular":{"timezone":"EDT","start":1791898200,"end":1791921600,"gmtoffset":-14400},"post":{"timezone":"EDT","start":1791921600,"end":1791936000,"gmtoffset":-14400}},"dataGranularity":"1d","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1791898200],"indicators":{"quote":[{"volume":[23148200],"close":[353.7799987792969],"high":[358.5799865722656],"low":[351.6000061035156],"open":[356.2300109863281]}],"adjclose":[{"adjclose":[353.7799987792969]}]}}],"error":null}}\ No newline at end of filediff --git a/tests/fixtures/trader-alerts/yahoo-KO.json b/tests/fixtures/trader-alerts/yahoo-KO.jsonnew file mode 100644index 0000000..ef681f9--- /dev/null+++ b/tests/fixtures/trader-alerts/yahoo-KO.json@@ -0,0 +1 @@+{"chart":{"result":[{"meta":{"currency":"USD","symbol":"KO","exchangeName":"NYQ","fullExchangeName":"NYSE","instrumentType":"EQUITY","firstTradeDate":-252322200,"regularMarketTime":1791921602,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":90.11,"regularMarketChangePercent":0.356,"fulldayPrice":89.85,"fulldayChange":0.23,"fulldayChangePercent":0.256,"fiftyTwoWeekHigh":92.49,"fiftyTwoWeekLow":66.92,"regularMarketDayHigh":90.56,"regularMarketDayLow":89.67,"regularMarketVolume":15313783,"longName":"The Coca-Cola Company","shortName":"Coca-Cola Company (The)","chartPreviousClose":89.79,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1791898200,"start":1791878400,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1791921600,"start":1791898200,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1791936000,"start":1791921600,"gmtoffset":-14400}},"dataGranularity":"1d","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1791898200],"indicators":{"quote":[{"close":[90.11000061035156],"volume":[15313000],"high":[90.55999755859375],"open":[90.55999755859375],"low":[89.66999816894531]}],"adjclose":[{"adjclose":[90.11000061035156]}]}}],"error":null}}\ No newline at end of filediff --git a/tests/fixtures/trader-alerts/yahoo-TSLA.json b/tests/fixtures/trader-alerts/yahoo-TSLA.jsonnew file mode 100644index 0000000..d6b7e3a--- /dev/null+++ b/tests/fixtures/trader-alerts/yahoo-TSLA.json@@ -0,0 +1 @@+{"chart":{"result":[{"meta":{"currency":"USD","symbol":"TSLA","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":1277818200,"regularMarketTime":1792421533,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":366.475,"regularMarketChangePercent":3.314,"fulldayPrice":366.475,"fulldayChange":11.755,"fulldayChangePercent":3.314,"fiftyTwoWeekHigh":498.83,"fiftyTwoWeekLow":297.38,"regularMarketDayHigh":367.57,"regularMarketDayLow":354.47,"regularMarketVolume":15051423,"longName":"Tesla, Inc.","shortName":"Tesla, Inc.","chartPreviousClose":354.72,"previousClose":354.72,"scale":3,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","start":1792396800,"end":1792416600,"gmtoffset":-14400},"regular":{"timezone":"EDT","start":1792416600,"end":1792440000,"gmtoffset":-14400},"post":{"timezone":"EDT","start":1792440000,"end":1792454400,"gmtoffset":-14400}},"tradingPeriods":[[{"timezone":"EDT","start":1792416600,"end":1792440000,"gmtoffset":-14400}]],"dataGranularity":"5m","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1792416600,1792416900,1792417200,1792417500,1792417800,1792418100,1792418400,1792418700,1792419000,1792419300,1792419600,1792419900,1792420200,1792420500,1792420800,1792421100,1792421400,1792421533],"indicators":{"quote":[{"close":[359.17999267578125,358.2699890136719,360.385009765625,361.45001220703125,361.06939697265625,361.92498779296875,361.468505859375,361.67999267578125,364.1759948730469,365.0450134277344,365.75,365.8500061035156,365.75,365.69500732421875,366.1050109863281,365.7300109863281,366.7449951171875,366.4750061035156],"high":[362.17999267578125,360.0249938964844,361.2200012207031,361.510009765625,362.9200134277344,362.8999938964844,362.1787109375,361.8799133300781,364.3900146484375,365.17999267578125,365.8800048828125,366.739990234375,366.2099914550781,366.489990234375,366.7795104980469,367.5987854003906,366.87890625,366.4750061035156],"low":[354.4700012207031,356.3699951171875,357.8900146484375,359.3800048828125,359.4599914550781,360.8599853515625,360.0201110839844,360.4200134277344,361.3699951171875,363.0,364.3999938964844,365.3999938964844,365.30999755859375,365.1099853515625,365.6285095214844,365.7200012207031,365.3999938964844,366.4750061035156],"open":[357.4849853515625,359.20001220703125,358.1524963378906,360.3699951171875,361.4465026855469,361.010009765625,361.92498779296875,361.4949951171875,361.67999267578125,364.2149963378906,365.0450134277344,365.739990234375,365.8900146484375,365.739990234375,365.7182922363281,366.2099914550781,365.7149963378906,366.4750061035156],"volume":[3080684,964899,931253,794838,1207272,805723,617820,558955,1000057,982318,739146,748942,13232032,512101,594767,713677,228811,0]}]}}],"error":null}}\ No newline at end of filediff --git a/tests/fixtures/trader-alerts/yahoo-ZZZZ.json b/tests/fixtures/trader-alerts/yahoo-ZZZZ.jsonnew file mode 100644index 0000000..ce6c8da--- /dev/null+++ b/tests/fixtures/trader-alerts/yahoo-ZZZZ.json@@ -0,0 +1 @@+{"chart":{"result":null,"error":{"code":"Not Found","description":"No data found, symbol may be delisted"}}}diff --git a/tests/fixtures/trader-analyst/000032019326000018/index.json b/tests/fixtures/trader-analyst/000032019326000018/index.jsonnew file mode 100644index 0000000..53fd9d1--- /dev/null+++ b/tests/fixtures/trader-analyst/000032019326000018/index.json@@ -0,0 +1 @@+{"directory":{"item":[{"last-modified": "2026-07-30 16:30:28","name":"0000320193-26-000018-index-headers.html","type":"text.gif","size":""},{"last-modified": "2026-07-30 16:30:28","name":"0000320193-26-000018-index.html","type":"text.gif","size":""},{"last-modified": "2026-07-30 16:30:28","name":"0000320193-26-000018.txt","type":"text.gif","size":""},{"last-modified": "2026-07-30 16:30:28","name":"0000320193-26-000018-xbrl.zip","type":"compressed.gif","size":"24417"},{"last-modified": "2026-07-30 16:30:28","name":"a8-kex991q3202606272026.htm","type":"text.gif","size":"173484"},{"last-modified": "2026-07-30 16:30:28","name":"aapl-20260730.htm","type":"text.gif","size":"38350"},{"last-modified": "2026-07-30 16:30:28","name":"aapl-20260730.xsd","type":"text.gif","size":"3650"},{"last-modified": "2026-07-30 16:30:28","name":"aapl-20260730_def.xml","type":"text.gif","size":"18144"},{"last-modified": "2026-07-30 16:30:28","name":"aapl-20260730_g1.jpg","type":"image2.gif","size":"1264"},{"last-modified": "2026-07-30 16:30:28","name":"aapl-20260730_htm.xml","type":"text.gif","size":"7714"},{"last-modified": "2026-07-30 16:30:28","name":"aapl-20260730_lab.xml","type":"text.gif","size":"34050"},{"last-modified": "2026-07-30 16:30:28","name":"aapl-20260730_pre.xml","type":"text.gif","size":"19171"},{"last-modified": "2026-07-30 16:30:28","name":"FilingSummary.xml","type":"text.gif","size":"1748"},{"last-modified": "2026-07-30 16:30:28","name":"MetaLinks.json","type":"text.gif","size":"23754"},{"last-modified": "2026-07-30 16:30:28","name":"R1.htm","type":"text.gif","size":"55284"},{"last-modified": "2026-07-30 16:30:28","name":"report.css","type":"text.gif","size":"2767"},{"last-modified": "2026-07-30 16:30:28","name":"Show.js","type":"text.gif","size":"1085"}],"name":"\/Archives\/edgar\/data\/320193\/000032019326000018","parent-dir":"\/Archives\/edgar\/data\/320193"}}\ No newline at end of filediff --git a/tests/fixtures/trader-analyst/company_tickers.json b/tests/fixtures/trader-analyst/company_tickers.jsonnew file mode 100644index 0000000..de0bd14--- /dev/null+++ b/tests/fixtures/trader-analyst/company_tickers.json@@ -0,0 +1,17 @@+{+"1": {+"cik_str": 320193,+"ticker": "AAPL",+"title": "Apple Inc."+},+"28": {+"cik_str": 21344,+"ticker": "KO",+"title": "COCA COLA CO"+},+"29": {+"cik_str": 70858,+"ticker": "BAC",+"title": "BANK OF AMERICA CORP /DE/"+}+}\ No newline at end of filediff --git a/tests/fixtures/trader-analyst/companyfacts-CIK0000021344.json b/tests/fixtures/trader-analyst/companyfacts-CIK0000021344.jsonnew file mode 100644index 0000000..4a54920--- /dev/null+++ b/tests/fixtures/trader-analyst/companyfacts-CIK0000021344.json@@ -0,0 +1 @@+{"cik":21344,"entityName":"COCA COLA CO","facts":{"us-gaap":{"Revenues":{"label":"Revenues","units":{"USD":[{"start":"2025-01-01","end":"2025-03-28","val":11129000000,"accn":"0000021344-25-000029","fy":2025,"fp":"Q1","form":"10-Q","filed":"2025-05-01"},{"start":"2025-01-01","end":"2025-03-28","val":11129000000,"accn":"0001628280-26-028802","fy":2026,"fp":"Q1","form":"10-Q","filed":"2026-04-30","frame":"CY2025Q1"},{"start":"2025-01-01","end":"2025-06-27","val":23664000000,"accn":"0000021344-25-000061","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-07-24"},{"start":"2025-03-29","end":"2025-06-27","val":12535000000,"accn":"0000021344-25-000061","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-07-24","frame":"CY2025Q2"},{"start":"2025-01-01","end":"2025-09-26","val":36119000000,"accn":"0001628280-25-046054","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-10-23"},{"start":"2025-06-28","end":"2025-09-26","val":12455000000,"accn":"0001628280-25-046054","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-10-23","frame":"CY2025Q3"},{"start":"2025-01-01","end":"2025-12-31","val":47941000000,"accn":"0001628280-26-010047","fy":2025,"fp":"FY","form":"10-K","filed":"2026-02-20","frame":"CY2025"},{"start":"2026-01-01","end":"2026-04-03","val":12472000000,"accn":"0001628280-26-028802","fy":2026,"fp":"Q1","form":"10-Q","filed":"2026-04-30","frame":"CY2026Q1"}]}},"GrossProfit":{"label":"Gross Profit","units":{"USD":[{"start":"2025-01-01","end":"2025-03-28","val":6966000000,"accn":"0000021344-25-000029","fy":2025,"fp":"Q1","form":"10-Q","filed":"2025-05-01"},{"start":"2025-01-01","end":"2025-03-28","val":6966000000,"accn":"0001628280-26-028802","fy":2026,"fp":"Q1","form":"10-Q","filed":"2026-04-30","frame":"CY2025Q1"},{"start":"2025-01-01","end":"2025-06-27","val":14787000000,"accn":"0000021344-25-000061","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-07-24"},{"start":"2025-03-29","end":"2025-06-27","val":7821000000,"accn":"0000021344-25-000061","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-07-24","frame":"CY2025Q2"},{"start":"2025-01-01","end":"2025-09-26","val":22445000000,"accn":"0001628280-25-046054","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-10-23"},{"start":"2025-06-28","end":"2025-09-26","val":7658000000,"accn":"0001628280-25-046054","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-10-23","frame":"CY2025Q3"},{"start":"2025-01-01","end":"2025-12-31","val":29544000000,"accn":"0001628280-26-010047","fy":2025,"fp":"FY","form":"10-K","filed":"2026-02-20","frame":"CY2025"},{"start":"2026-01-01","end":"2026-04-03","val":7852000000,"accn":"0001628280-26-028802","fy":2026,"fp":"Q1","form":"10-Q","filed":"2026-04-30","frame":"CY2026Q1"}]}},"OperatingIncomeLoss":{"label":"Operating Income (Loss)","units":{"USD":[{"start":"2025-01-01","end":"2025-03-28","val":3659000000,"accn":"0000021344-25-000029","fy":2025,"fp":"Q1","form":"10-Q","filed":"2025-05-01"},{"start":"2025-01-01","end":"2025-03-28","val":3659000000,"accn":"0001628280-26-028802","fy":2026,"fp":"Q1","form":"10-Q","filed":"2026-04-30","frame":"CY2025Q1"},{"start":"2025-01-01","end":"2025-06-27","val":7939000000,"accn":"0000021344-25-000061","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-07-24"},{"start":"2025-03-29","end":"2025-06-27","val":4280000000,"accn":"0000021344-25-000061","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-07-24","frame":"CY2025Q2"},{"start":"2025-01-01","end":"2025-09-26","val":11921000000,"accn":"0001628280-25-046054","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-10-23"},{"start":"2025-06-28","end":"2025-09-26","val":3982000000,"accn":"0001628280-25-046054","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-10-23","frame":"CY2025Q3"},{"start":"2025-01-01","end":"2025-12-31","val":13762000000,"accn":"0001628280-26-010047","fy":2025,"fp":"FY","form":"10-K","filed":"2026-02-20","frame":"CY2025"},{"start":"2026-01-01","end":"2026-04-03","val":4359000000,"accn":"0001628280-26-028802","fy":2026,"fp":"Q1","form":"10-Q","filed":"2026-04-30","frame":"CY2026Q1"}]}},"NetIncomeLoss":{"label":"Net Income (Loss) Attributable to Parent","units":{"USD":[{"start":"2025-01-01","end":"2025-03-28","val":3330000000,"accn":"0000021344-25-000029","fy":2025,"fp":"Q1","form":"10-Q","filed":"2025-05-01"},{"start":"2025-01-01","end":"2025-03-28","val":3330000000,"accn":"0001628280-26-028802","fy":2026,"fp":"Q1","form":"10-Q","filed":"2026-04-30","frame":"CY2025Q1"},{"start":"2025-01-01","end":"2025-06-27","val":7140000000,"accn":"0000021344-25-000061","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-07-24"},{"start":"2025-03-29","end":"2025-06-27","val":3810000000,"accn":"0000021344-25-000061","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-07-24","frame":"CY2025Q2"},{"start":"2025-01-01","end":"2025-09-26","val":10836000000,"accn":"0001628280-25-046054","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-10-23"},{"start":"2025-06-28","end":"2025-09-26","val":3696000000,"accn":"0001628280-25-046054","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-10-23","frame":"CY2025Q3"},{"start":"2025-01-01","end":"2025-12-31","val":13107000000,"accn":"0001628280-26-010047","fy":2025,"fp":"FY","form":"10-K","filed":"2026-02-20","frame":"CY2025"},{"start":"2026-01-01","end":"2026-04-03","val":3924000000,"accn":"0001628280-26-028802","fy":2026,"fp":"Q1","form":"10-Q","filed":"2026-04-30","frame":"CY2026Q1"}]}},"EarningsPerShareDiluted":{"label":"Earnings Per Share, Diluted","units":{"USD/shares":[{"start":"2025-01-01","end":"2025-03-28","val":0.77,"accn":"0000021344-25-000029","fy":2025,"fp":"Q1","form":"10-Q","filed":"2025-05-01"},{"start":"2025-01-01","end":"2025-03-28","val":0.77,"accn":"0001628280-26-028802","fy":2026,"fp":"Q1","form":"10-Q","filed":"2026-04-30","frame":"CY2025Q1"},{"start":"2025-01-01","end":"2025-06-27","val":1.65,"accn":"0000021344-25-000061","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-07-24"},{"start":"2025-03-29","end":"2025-06-27","val":0.88,"accn":"0000021344-25-000061","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-07-24","frame":"CY2025Q2"},{"start":"2025-01-01","end":"2025-09-26","val":2.51,"accn":"0001628280-25-046054","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-10-23"},{"start":"2025-06-28","end":"2025-09-26","val":0.86,"accn":"0001628280-25-046054","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-10-23","frame":"CY2025Q3"},{"start":"2025-01-01","end":"2025-12-31","val":3.04,"accn":"0001628280-26-010047","fy":2025,"fp":"FY","form":"10-K","filed":"2026-02-20","frame":"CY2025"},{"start":"2026-01-01","end":"2026-04-03","val":0.91,"accn":"0001628280-26-028802","fy":2026,"fp":"Q1","form":"10-Q","filed":"2026-04-30","frame":"CY2026Q1"}]}}}}}\ No newline at end of filediff --git a/tests/fixtures/trader-analyst/companyfacts-CIK0000320193.json b/tests/fixtures/trader-analyst/companyfacts-CIK0000320193.jsonnew file mode 100644index 0000000..18ea7c8--- /dev/null+++ b/tests/fixtures/trader-analyst/companyfacts-CIK0000320193.json@@ -0,0 +1 @@+{"cik":320193,"entityName":"Apple Inc.","facts":{"us-gaap":{"RevenueFromContractWithCustomerExcludingAssessedTax":{"label":"Revenue from Contract with Customer, Excluding Assessed Tax","units":{"USD":[{"start":"2023-10-01","end":"2023-12-30","val":119575000000,"accn":"0000320193-24-000006","fy":2024,"fp":"Q1","form":"10-Q","filed":"2024-02-02"},{"start":"2023-10-01","end":"2023-12-30","val":119575000000,"accn":"0000320193-25-000008","fy":2025,"fp":"Q1","form":"10-Q","filed":"2025-01-31","frame":"CY2023Q4"},{"start":"2023-10-01","end":"2024-03-30","val":210328000000,"accn":"0000320193-24-000069","fy":2024,"fp":"Q2","form":"10-Q","filed":"2024-05-03"},{"start":"2023-10-01","end":"2024-03-30","val":210328000000,"accn":"0000320193-25-000057","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-05-02"},{"start":"2023-12-31","end":"2024-03-30","val":90753000000,"accn":"0000320193-24-000069","fy":2024,"fp":"Q2","form":"10-Q","filed":"2024-05-03"},{"start":"2023-12-31","end":"2024-03-30","val":90753000000,"accn":"0000320193-25-000057","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-05-02","frame":"CY2024Q1"},{"start":"2023-10-01","end":"2024-06-29","val":296105000000,"accn":"0000320193-24-000081","fy":2024,"fp":"Q3","form":"10-Q","filed":"2024-08-02"},{"start":"2023-10-01","end":"2024-06-29","val":296105000000,"accn":"0000320193-25-000073","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-08-01"},{"start":"2024-03-31","end":"2024-06-29","val":85777000000,"accn":"0000320193-24-000081","fy":2024,"fp":"Q3","form":"10-Q","filed":"2024-08-02"},{"start":"2024-03-31","end":"2024-06-29","val":85777000000,"accn":"0000320193-25-000073","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-08-01","frame":"CY2024Q2"},{"start":"2023-10-01","end":"2024-09-28","val":391035000000,"accn":"0000320193-24-000123","fy":2024,"fp":"FY","form":"10-K","filed":"2024-11-01"},{"start":"2023-10-01","end":"2024-09-28","val":391035000000,"accn":"0000320193-25-000079","fy":2025,"fp":"FY","form":"10-K","filed":"2025-10-31","frame":"CY2024"},{"start":"2024-09-29","end":"2024-12-28","val":124300000000,"accn":"0000320193-25-000008","fy":2025,"fp":"Q1","form":"10-Q","filed":"2025-01-31"},{"start":"2024-09-29","end":"2024-12-28","val":124300000000,"accn":"0000320193-26-000006","fy":2026,"fp":"Q1","form":"10-Q","filed":"2026-01-30","frame":"CY2024Q4"},{"start":"2024-09-29","end":"2025-03-29","val":219659000000,"accn":"0000320193-25-000057","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-05-02"},{"start":"2024-09-29","end":"2025-03-29","val":219659000000,"accn":"0000320193-26-000013","fy":2026,"fp":"Q2","form":"10-Q","filed":"2026-05-01"},{"start":"2024-12-29","end":"2025-03-29","val":95359000000,"accn":"0000320193-25-000057","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-05-02"},{"start":"2024-12-29","end":"2025-03-29","val":95359000000,"accn":"0000320193-26-000013","fy":2026,"fp":"Q2","form":"10-Q","filed":"2026-05-01","frame":"CY2025Q1"},{"start":"2024-09-29","end":"2025-06-28","val":313695000000,"accn":"0000320193-25-000073","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-08-01"},{"start":"2024-09-29","end":"2025-06-28","val":313695000000,"accn":"0000320193-26-000020","fy":2026,"fp":"Q3","form":"10-Q","filed":"2026-07-31"},{"start":"2025-03-30","end":"2025-06-28","val":94036000000,"accn":"0000320193-25-000073","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-08-01"},{"start":"2025-03-30","end":"2025-06-28","val":94036000000,"accn":"0000320193-26-000020","fy":2026,"fp":"Q3","form":"10-Q","filed":"2026-07-31","frame":"CY2025Q2"},{"start":"2024-09-29","end":"2025-09-27","val":416161000000,"accn":"0000320193-25-000079","fy":2025,"fp":"FY","form":"10-K","filed":"2025-10-31","frame":"CY2025"},{"start":"2025-09-28","end":"2025-12-27","val":143756000000,"accn":"0000320193-26-000006","fy":2026,"fp":"Q1","form":"10-Q","filed":"2026-01-30","frame":"CY2025Q4"},{"start":"2025-09-28","end":"2026-03-28","val":254940000000,"accn":"0000320193-26-000013","fy":2026,"fp":"Q2","form":"10-Q","filed":"2026-05-01"},{"start":"2025-12-28","end":"2026-03-28","val":111184000000,"accn":"0000320193-26-000013","fy":2026,"fp":"Q2","form":"10-Q","filed":"2026-05-01","frame":"CY2026Q1"},{"start":"2025-09-28","end":"2026-06-27","val":364357000000,"accn":"0000320193-26-000020","fy":2026,"fp":"Q3","form":"10-Q","filed":"2026-07-31"},{"start":"2026-03-29","end":"2026-06-27","val":109417000000,"accn":"0000320193-26-000020","fy":2026,"fp":"Q3","form":"10-Q","filed":"2026-07-31","frame":"CY2026Q2"}]}},"CostOfGoodsAndServicesSold":{"label":"Cost of Goods and Services Sold","units":{"USD":[{"start":"2023-10-01","end":"2023-12-30","val":64720000000,"accn":"0000320193-24-000006","fy":2024,"fp":"Q1","form":"10-Q","filed":"2024-02-02"},{"start":"2023-10-01","end":"2023-12-30","val":64720000000,"accn":"0000320193-25-000008","fy":2025,"fp":"Q1","form":"10-Q","filed":"2025-01-31","frame":"CY2023Q4"},{"start":"2023-10-01","end":"2024-03-30","val":113202000000,"accn":"0000320193-24-000069","fy":2024,"fp":"Q2","form":"10-Q","filed":"2024-05-03"},{"start":"2023-10-01","end":"2024-03-30","val":113202000000,"accn":"0000320193-25-000057","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-05-02"},{"start":"2023-12-31","end":"2024-03-30","val":48482000000,"accn":"0000320193-24-000069","fy":2024,"fp":"Q2","form":"10-Q","filed":"2024-05-03"},{"start":"2023-12-31","end":"2024-03-30","val":48482000000,"accn":"0000320193-25-000057","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-05-02","frame":"CY2024Q1"},{"start":"2023-10-01","end":"2024-06-29","val":159301000000,"accn":"0000320193-24-000081","fy":2024,"fp":"Q3","form":"10-Q","filed":"2024-08-02"},{"start":"2023-10-01","end":"2024-06-29","val":159301000000,"accn":"0000320193-25-000073","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-08-01"},{"start":"2024-03-31","end":"2024-06-29","val":46099000000,"accn":"0000320193-24-000081","fy":2024,"fp":"Q3","form":"10-Q","filed":"2024-08-02"},{"start":"2024-03-31","end":"2024-06-29","val":46099000000,"accn":"0000320193-25-000073","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-08-01","frame":"CY2024Q2"},{"start":"2023-10-01","end":"2024-09-28","val":210352000000,"accn":"0000320193-24-000123","fy":2024,"fp":"FY","form":"10-K","filed":"2024-11-01"},{"start":"2023-10-01","end":"2024-09-28","val":210352000000,"accn":"0000320193-25-000079","fy":2025,"fp":"FY","form":"10-K","filed":"2025-10-31","frame":"CY2024"},{"start":"2024-09-29","end":"2024-12-28","val":66025000000,"accn":"0000320193-25-000008","fy":2025,"fp":"Q1","form":"10-Q","filed":"2025-01-31"},{"start":"2024-09-29","end":"2024-12-28","val":66025000000,"accn":"0000320193-26-000006","fy":2026,"fp":"Q1","form":"10-Q","filed":"2026-01-30","frame":"CY2024Q4"},{"start":"2024-09-29","end":"2025-03-29","val":116517000000,"accn":"0000320193-25-000057","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-05-02"},{"start":"2024-09-29","end":"2025-03-29","val":116517000000,"accn":"0000320193-26-000013","fy":2026,"fp":"Q2","form":"10-Q","filed":"2026-05-01"},{"start":"2024-12-29","end":"2025-03-29","val":50492000000,"accn":"0000320193-25-000057","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-05-02"},{"start":"2024-12-29","end":"2025-03-29","val":50492000000,"accn":"0000320193-26-000013","fy":2026,"fp":"Q2","form":"10-Q","filed":"2026-05-01","frame":"CY2025Q1"},{"start":"2024-09-29","end":"2025-06-28","val":166835000000,"accn":"0000320193-25-000073","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-08-01"},{"start":"2024-09-29","end":"2025-06-28","val":166835000000,"accn":"0000320193-26-000020","fy":2026,"fp":"Q3","form":"10-Q","filed":"2026-07-31"},{"start":"2025-03-30","end":"2025-06-28","val":50318000000,"accn":"0000320193-25-000073","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-08-01"},{"start":"2025-03-30","end":"2025-06-28","val":50318000000,"accn":"0000320193-26-000020","fy":2026,"fp":"Q3","form":"10-Q","filed":"2026-07-31","frame":"CY2025Q2"},{"start":"2024-09-29","end":"2025-09-27","val":220960000000,"accn":"0000320193-25-000079","fy":2025,"fp":"FY","form":"10-K","filed":"2025-10-31","frame":"CY2025"},{"start":"2025-09-28","end":"2025-12-27","val":74525000000,"accn":"0000320193-26-000006","fy":2026,"fp":"Q1","form":"10-Q","filed":"2026-01-30","frame":"CY2025Q4"},{"start":"2025-09-28","end":"2026-03-28","val":130928000000,"accn":"0000320193-26-000013","fy":2026,"fp":"Q2","form":"10-Q","filed":"2026-05-01"},{"start":"2025-12-28","end":"2026-03-28","val":56403000000,"accn":"0000320193-26-000013","fy":2026,"fp":"Q2","form":"10-Q","filed":"2026-05-01","frame":"CY2026Q1"},{"start":"2025-09-28","end":"2026-06-27","val":185575000000,"accn":"0000320193-26-000020","fy":2026,"fp":"Q3","form":"10-Q","filed":"2026-07-31"},{"start":"2026-03-29","end":"2026-06-27","val":54647000000,"accn":"0000320193-26-000020","fy":2026,"fp":"Q3","form":"10-Q","filed":"2026-07-31","frame":"CY2026Q2"}]}},"GrossProfit":{"label":"Gross Profit","units":{"USD":[{"start":"2023-10-01","end":"2023-12-30","val":54855000000,"accn":"0000320193-24-000006","fy":2024,"fp":"Q1","form":"10-Q","filed":"2024-02-02"},{"start":"2023-10-01","end":"2023-12-30","val":54855000000,"accn":"0000320193-25-000008","fy":2025,"fp":"Q1","form":"10-Q","filed":"2025-01-31","frame":"CY2023Q4"},{"start":"2023-10-01","end":"2024-03-30","val":97126000000,"accn":"0000320193-24-000069","fy":2024,"fp":"Q2","form":"10-Q","filed":"2024-05-03"},{"start":"2023-10-01","end":"2024-03-30","val":97126000000,"accn":"0000320193-25-000057","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-05-02"},{"start":"2023-12-31","end":"2024-03-30","val":42271000000,"accn":"0000320193-24-000069","fy":2024,"fp":"Q2","form":"10-Q","filed":"2024-05-03"},{"start":"2023-12-31","end":"2024-03-30","val":42271000000,"accn":"0000320193-25-000057","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-05-02","frame":"CY2024Q1"},{"start":"2023-10-01","end":"2024-06-29","val":136804000000,"accn":"0000320193-24-000081","fy":2024,"fp":"Q3","form":"10-Q","filed":"2024-08-02"},{"start":"2023-10-01","end":"2024-06-29","val":136804000000,"accn":"0000320193-25-000073","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-08-01"},{"start":"2024-03-31","end":"2024-06-29","val":39678000000,"accn":"0000320193-24-000081","fy":2024,"fp":"Q3","form":"10-Q","filed":"2024-08-02"},{"start":"2024-03-31","end":"2024-06-29","val":39678000000,"accn":"0000320193-25-000073","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-08-01","frame":"CY2024Q2"},{"start":"2023-10-01","end":"2024-09-28","val":180683000000,"accn":"0000320193-24-000123","fy":2024,"fp":"FY","form":"10-K","filed":"2024-11-01"},{"start":"2023-10-01","end":"2024-09-28","val":180683000000,"accn":"0000320193-25-000079","fy":2025,"fp":"FY","form":"10-K","filed":"2025-10-31","frame":"CY2024"},{"start":"2024-09-29","end":"2024-12-28","val":58275000000,"accn":"0000320193-25-000008","fy":2025,"fp":"Q1","form":"10-Q","filed":"2025-01-31"},{"start":"2024-09-29","end":"2024-12-28","val":58275000000,"accn":"0000320193-26-000006","fy":2026,"fp":"Q1","form":"10-Q","filed":"2026-01-30","frame":"CY2024Q4"},{"start":"2024-09-29","end":"2025-03-29","val":103142000000,"accn":"0000320193-25-000057","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-05-02"},{"start":"2024-09-29","end":"2025-03-29","val":103142000000,"accn":"0000320193-26-000013","fy":2026,"fp":"Q2","form":"10-Q","filed":"2026-05-01"},{"start":"2024-12-29","end":"2025-03-29","val":44867000000,"accn":"0000320193-25-000057","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-05-02"},{"start":"2024-12-29","end":"2025-03-29","val":44867000000,"accn":"0000320193-26-000013","fy":2026,"fp":"Q2","form":"10-Q","filed":"2026-05-01","frame":"CY2025Q1"},{"start":"2024-09-29","end":"2025-06-28","val":146860000000,"accn":"0000320193-25-000073","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-08-01"},{"start":"2024-09-29","end":"2025-06-28","val":146860000000,"accn":"0000320193-26-000020","fy":2026,"fp":"Q3","form":"10-Q","filed":"2026-07-31"},{"start":"2025-03-30","end":"2025-06-28","val":43718000000,"accn":"0000320193-25-000073","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-08-01"},{"start":"2025-03-30","end":"2025-06-28","val":43718000000,"accn":"0000320193-26-000020","fy":2026,"fp":"Q3","form":"10-Q","filed":"2026-07-31","frame":"CY2025Q2"},{"start":"2024-09-29","end":"2025-09-27","val":195201000000,"accn":"0000320193-25-000079","fy":2025,"fp":"FY","form":"10-K","filed":"2025-10-31","frame":"CY2025"},{"start":"2025-09-28","end":"2025-12-27","val":69231000000,"accn":"0000320193-26-000006","fy":2026,"fp":"Q1","form":"10-Q","filed":"2026-01-30","frame":"CY2025Q4"},{"start":"2025-09-28","end":"2026-03-28","val":124012000000,"accn":"0000320193-26-000013","fy":2026,"fp":"Q2","form":"10-Q","filed":"2026-05-01"},{"start":"2025-12-28","end":"2026-03-28","val":54781000000,"accn":"0000320193-26-000013","fy":2026,"fp":"Q2","form":"10-Q","filed":"2026-05-01","frame":"CY2026Q1"},{"start":"2025-09-28","end":"2026-06-27","val":178782000000,"accn":"0000320193-26-000020","fy":2026,"fp":"Q3","form":"10-Q","filed":"2026-07-31"},{"start":"2026-03-29","end":"2026-06-27","val":54770000000,"accn":"0000320193-26-000020","fy":2026,"fp":"Q3","form":"10-Q","filed":"2026-07-31","frame":"CY2026Q2"}]}},"OperatingIncomeLoss":{"label":"Operating Income (Loss)","units":{"USD":[{"start":"2023-10-01","end":"2023-12-30","val":40373000000,"accn":"0000320193-24-000006","fy":2024,"fp":"Q1","form":"10-Q","filed":"2024-02-02"},{"start":"2023-10-01","end":"2023-12-30","val":40373000000,"accn":"0000320193-25-000008","fy":2025,"fp":"Q1","form":"10-Q","filed":"2025-01-31","frame":"CY2023Q4"},{"start":"2023-10-01","end":"2024-03-30","val":68273000000,"accn":"0000320193-24-000069","fy":2024,"fp":"Q2","form":"10-Q","filed":"2024-05-03"},{"start":"2023-10-01","end":"2024-03-30","val":68273000000,"accn":"0000320193-25-000057","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-05-02"},{"start":"2023-12-31","end":"2024-03-30","val":27900000000,"accn":"0000320193-24-000069","fy":2024,"fp":"Q2","form":"10-Q","filed":"2024-05-03"},{"start":"2023-12-31","end":"2024-03-30","val":27900000000,"accn":"0000320193-25-000057","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-05-02","frame":"CY2024Q1"},{"start":"2023-10-01","end":"2024-06-29","val":93625000000,"accn":"0000320193-24-000081","fy":2024,"fp":"Q3","form":"10-Q","filed":"2024-08-02"},{"start":"2023-10-01","end":"2024-06-29","val":93625000000,"accn":"0000320193-25-000073","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-08-01"},{"start":"2024-03-31","end":"2024-06-29","val":25352000000,"accn":"0000320193-24-000081","fy":2024,"fp":"Q3","form":"10-Q","filed":"2024-08-02"},{"start":"2024-03-31","end":"2024-06-29","val":25352000000,"accn":"0000320193-25-000073","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-08-01","frame":"CY2024Q2"},{"start":"2023-10-01","end":"2024-09-28","val":123216000000,"accn":"0000320193-24-000123","fy":2024,"fp":"FY","form":"10-K","filed":"2024-11-01"},{"start":"2023-10-01","end":"2024-09-28","val":123216000000,"accn":"0000320193-25-000079","fy":2025,"fp":"FY","form":"10-K","filed":"2025-10-31","frame":"CY2024"},{"start":"2024-09-29","end":"2024-12-28","val":42832000000,"accn":"0000320193-25-000008","fy":2025,"fp":"Q1","form":"10-Q","filed":"2025-01-31"},{"start":"2024-09-29","end":"2024-12-28","val":42832000000,"accn":"0000320193-26-000006","fy":2026,"fp":"Q1","form":"10-Q","filed":"2026-01-30","frame":"CY2024Q4"},{"start":"2024-09-29","end":"2025-03-29","val":72421000000,"accn":"0000320193-25-000057","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-05-02"},{"start":"2024-09-29","end":"2025-03-29","val":72421000000,"accn":"0000320193-26-000013","fy":2026,"fp":"Q2","form":"10-Q","filed":"2026-05-01"},{"start":"2024-12-29","end":"2025-03-29","val":29589000000,"accn":"0000320193-25-000057","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-05-02"},{"start":"2024-12-29","end":"2025-03-29","val":29589000000,"accn":"0000320193-26-000013","fy":2026,"fp":"Q2","form":"10-Q","filed":"2026-05-01","frame":"CY2025Q1"},{"start":"2024-09-29","end":"2025-06-28","val":100623000000,"accn":"0000320193-25-000073","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-08-01"},{"start":"2024-09-29","end":"2025-06-28","val":100623000000,"accn":"0000320193-26-000020","fy":2026,"fp":"Q3","form":"10-Q","filed":"2026-07-31"},{"start":"2025-03-30","end":"2025-06-28","val":28202000000,"accn":"0000320193-25-000073","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-08-01"},{"start":"2025-03-30","end":"2025-06-28","val":28202000000,"accn":"0000320193-26-000020","fy":2026,"fp":"Q3","form":"10-Q","filed":"2026-07-31","frame":"CY2025Q2"},{"start":"2024-09-29","end":"2025-09-27","val":133050000000,"accn":"0000320193-25-000079","fy":2025,"fp":"FY","form":"10-K","filed":"2025-10-31","frame":"CY2025"},{"start":"2025-09-28","end":"2025-12-27","val":50852000000,"accn":"0000320193-26-000006","fy":2026,"fp":"Q1","form":"10-Q","filed":"2026-01-30","frame":"CY2025Q4"},{"start":"2025-09-28","end":"2026-03-28","val":86737000000,"accn":"0000320193-26-000013","fy":2026,"fp":"Q2","form":"10-Q","filed":"2026-05-01"},{"start":"2025-12-28","end":"2026-03-28","val":35885000000,"accn":"0000320193-26-000013","fy":2026,"fp":"Q2","form":"10-Q","filed":"2026-05-01","frame":"CY2026Q1"},{"start":"2025-09-28","end":"2026-06-27","val":122432000000,"accn":"0000320193-26-000020","fy":2026,"fp":"Q3","form":"10-Q","filed":"2026-07-31"},{"start":"2026-03-29","end":"2026-06-27","val":35695000000,"accn":"0000320193-26-000020","fy":2026,"fp":"Q3","form":"10-Q","filed":"2026-07-31","frame":"CY2026Q2"}]}},"NetIncomeLoss":{"label":"Net Income (Loss) Attributable to Parent","units":{"USD":[{"start":"2023-10-01","end":"2023-12-30","val":33916000000,"accn":"0000320193-24-000006","fy":2024,"fp":"Q1","form":"10-Q","filed":"2024-02-02"},{"start":"2023-10-01","end":"2023-12-30","val":33916000000,"accn":"0000320193-25-000008","fy":2025,"fp":"Q1","form":"10-Q","filed":"2025-01-31","frame":"CY2023Q4"},{"start":"2023-10-01","end":"2024-03-30","val":57552000000,"accn":"0000320193-24-000069","fy":2024,"fp":"Q2","form":"10-Q","filed":"2024-05-03"},{"start":"2023-10-01","end":"2024-03-30","val":57552000000,"accn":"0000320193-25-000057","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-05-02"},{"start":"2023-12-31","end":"2024-03-30","val":23636000000,"accn":"0000320193-24-000069","fy":2024,"fp":"Q2","form":"10-Q","filed":"2024-05-03"},{"start":"2023-12-31","end":"2024-03-30","val":23636000000,"accn":"0000320193-25-000057","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-05-02","frame":"CY2024Q1"},{"start":"2023-10-01","end":"2024-06-29","val":79000000000,"accn":"0000320193-24-000081","fy":2024,"fp":"Q3","form":"10-Q","filed":"2024-08-02"},{"start":"2023-10-01","end":"2024-06-29","val":79000000000,"accn":"0000320193-25-000073","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-08-01"},{"start":"2024-03-31","end":"2024-06-29","val":21448000000,"accn":"0000320193-24-000081","fy":2024,"fp":"Q3","form":"10-Q","filed":"2024-08-02"},{"start":"2024-03-31","end":"2024-06-29","val":21448000000,"accn":"0000320193-25-000073","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-08-01","frame":"CY2024Q2"},{"start":"2023-10-01","end":"2024-09-28","val":93736000000,"accn":"0000320193-24-000123","fy":2024,"fp":"FY","form":"10-K","filed":"2024-11-01"},{"start":"2023-10-01","end":"2024-09-28","val":93736000000,"accn":"0000320193-25-000079","fy":2025,"fp":"FY","form":"10-K","filed":"2025-10-31","frame":"CY2024"},{"start":"2024-09-29","end":"2024-12-28","val":36330000000,"accn":"0000320193-25-000008","fy":2025,"fp":"Q1","form":"10-Q","filed":"2025-01-31"},{"start":"2024-09-29","end":"2024-12-28","val":36330000000,"accn":"0000320193-26-000006","fy":2026,"fp":"Q1","form":"10-Q","filed":"2026-01-30","frame":"CY2024Q4"},{"start":"2024-09-29","end":"2025-03-29","val":61110000000,"accn":"0000320193-25-000057","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-05-02"},{"start":"2024-09-29","end":"2025-03-29","val":61110000000,"accn":"0000320193-26-000013","fy":2026,"fp":"Q2","form":"10-Q","filed":"2026-05-01"},{"start":"2024-12-29","end":"2025-03-29","val":24780000000,"accn":"0000320193-25-000057","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-05-02"},{"start":"2024-12-29","end":"2025-03-29","val":24780000000,"accn":"0000320193-26-000013","fy":2026,"fp":"Q2","form":"10-Q","filed":"2026-05-01","frame":"CY2025Q1"},{"start":"2024-09-29","end":"2025-06-28","val":84544000000,"accn":"0000320193-25-000073","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-08-01"},{"start":"2024-09-29","end":"2025-06-28","val":84544000000,"accn":"0000320193-26-000020","fy":2026,"fp":"Q3","form":"10-Q","filed":"2026-07-31"},{"start":"2025-03-30","end":"2025-06-28","val":23434000000,"accn":"0000320193-25-000073","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-08-01"},{"start":"2025-03-30","end":"2025-06-28","val":23434000000,"accn":"0000320193-26-000020","fy":2026,"fp":"Q3","form":"10-Q","filed":"2026-07-31","frame":"CY2025Q2"},{"start":"2024-09-29","end":"2025-09-27","val":112010000000,"accn":"0000320193-25-000079","fy":2025,"fp":"FY","form":"10-K","filed":"2025-10-31","frame":"CY2025"},{"start":"2025-09-28","end":"2025-12-27","val":42097000000,"accn":"0000320193-26-000006","fy":2026,"fp":"Q1","form":"10-Q","filed":"2026-01-30","frame":"CY2025Q4"},{"start":"2025-09-28","end":"2026-03-28","val":71675000000,"accn":"0000320193-26-000013","fy":2026,"fp":"Q2","form":"10-Q","filed":"2026-05-01"},{"start":"2025-12-28","end":"2026-03-28","val":29578000000,"accn":"0000320193-26-000013","fy":2026,"fp":"Q2","form":"10-Q","filed":"2026-05-01","frame":"CY2026Q1"},{"start":"2025-09-28","end":"2026-06-27","val":101464000000,"accn":"0000320193-26-000020","fy":2026,"fp":"Q3","form":"10-Q","filed":"2026-07-31"},{"start":"2026-03-29","end":"2026-06-27","val":29789000000,"accn":"0000320193-26-000020","fy":2026,"fp":"Q3","form":"10-Q","filed":"2026-07-31","frame":"CY2026Q2"}]}},"EarningsPerShareDiluted":{"label":"Earnings Per Share, Diluted","units":{"USD/shares":[{"start":"2023-10-01","end":"2023-12-30","val":2.18,"accn":"0000320193-24-000006","fy":2024,"fp":"Q1","form":"10-Q","filed":"2024-02-02"},{"start":"2023-10-01","end":"2023-12-30","val":2.18,"accn":"0000320193-25-000008","fy":2025,"fp":"Q1","form":"10-Q","filed":"2025-01-31","frame":"CY2023Q4"},{"start":"2023-10-01","end":"2024-03-30","val":3.71,"accn":"0000320193-24-000069","fy":2024,"fp":"Q2","form":"10-Q","filed":"2024-05-03"},{"start":"2023-10-01","end":"2024-03-30","val":3.71,"accn":"0000320193-25-000057","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-05-02"},{"start":"2023-12-31","end":"2024-03-30","val":1.53,"accn":"0000320193-24-000069","fy":2024,"fp":"Q2","form":"10-Q","filed":"2024-05-03"},{"start":"2023-12-31","end":"2024-03-30","val":1.53,"accn":"0000320193-25-000057","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-05-02","frame":"CY2024Q1"},{"start":"2023-10-01","end":"2024-06-29","val":5.11,"accn":"0000320193-24-000081","fy":2024,"fp":"Q3","form":"10-Q","filed":"2024-08-02"},{"start":"2023-10-01","end":"2024-06-29","val":5.11,"accn":"0000320193-25-000073","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-08-01"},{"start":"2024-03-31","end":"2024-06-29","val":1.4,"accn":"0000320193-24-000081","fy":2024,"fp":"Q3","form":"10-Q","filed":"2024-08-02"},{"start":"2024-03-31","end":"2024-06-29","val":1.4,"accn":"0000320193-25-000073","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-08-01","frame":"CY2024Q2"},{"start":"2023-10-01","end":"2024-09-28","val":6.08,"accn":"0000320193-24-000123","fy":2024,"fp":"FY","form":"10-K","filed":"2024-11-01"},{"start":"2023-10-01","end":"2024-09-28","val":6.08,"accn":"0000320193-25-000079","fy":2025,"fp":"FY","form":"10-K","filed":"2025-10-31","frame":"CY2024"},{"start":"2024-09-29","end":"2024-12-28","val":2.4,"accn":"0000320193-25-000008","fy":2025,"fp":"Q1","form":"10-Q","filed":"2025-01-31"},{"start":"2024-09-29","end":"2024-12-28","val":2.4,"accn":"0000320193-26-000006","fy":2026,"fp":"Q1","form":"10-Q","filed":"2026-01-30","frame":"CY2024Q4"},{"start":"2024-09-29","end":"2025-03-29","val":4.05,"accn":"0000320193-25-000057","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-05-02"},{"start":"2024-09-29","end":"2025-03-29","val":4.05,"accn":"0000320193-26-000013","fy":2026,"fp":"Q2","form":"10-Q","filed":"2026-05-01"},{"start":"2024-12-29","end":"2025-03-29","val":1.65,"accn":"0000320193-25-000057","fy":2025,"fp":"Q2","form":"10-Q","filed":"2025-05-02"},{"start":"2024-12-29","end":"2025-03-29","val":1.65,"accn":"0000320193-26-000013","fy":2026,"fp":"Q2","form":"10-Q","filed":"2026-05-01","frame":"CY2025Q1"},{"start":"2024-09-29","end":"2025-06-28","val":5.62,"accn":"0000320193-25-000073","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-08-01"},{"start":"2024-09-29","end":"2025-06-28","val":5.62,"accn":"0000320193-26-000020","fy":2026,"fp":"Q3","form":"10-Q","filed":"2026-07-31"},{"start":"2025-03-30","end":"2025-06-28","val":1.57,"accn":"0000320193-25-000073","fy":2025,"fp":"Q3","form":"10-Q","filed":"2025-08-01"},{"start":"2025-03-30","end":"2025-06-28","val":1.57,"accn":"0000320193-26-000020","fy":2026,"fp":"Q3","form":"10-Q","filed":"2026-07-31","frame":"CY2025Q2"},{"start":"2024-09-29","end":"2025-09-27","val":7.46,"accn":"0000320193-25-000079","fy":2025,"fp":"FY","form":"10-K","filed":"2025-10-31","frame":"CY2025"},{"start":"2025-09-28","end":"2025-12-27","val":2.84,"accn":"0000320193-26-000006","fy":2026,"fp":"Q1","form":"10-Q","filed":"2026-01-30","frame":"CY2025Q4"},{"start":"2025-09-28","end":"2026-03-28","val":4.85,"accn":"0000320193-26-000013","fy":2026,"fp":"Q2","form":"10-Q","filed":"2026-05-01"},{"start":"2025-12-28","end":"2026-03-28","val":2.01,"accn":"0000320193-26-000013","fy":2026,"fp":"Q2","form":"10-Q","filed":"2026-05-01","frame":"CY2026Q1"},{"start":"2025-09-28","end":"2026-06-27","val":6.88,"accn":"0000320193-26-000020","fy":2026,"fp":"Q3","form":"10-Q","filed":"2026-07-31"},{"start":"2026-03-29","end":"2026-06-27","val":2.02,"accn":"0000320193-26-000020","fy":2026,"fp":"Q3","form":"10-Q","filed":"2026-07-31","frame":"CY2026Q2"}]}}}}}\ No newline at end of filediff --git a/tests/fixtures/trader-analyst/submissions-CIK0000021344.json b/tests/fixtures/trader-analyst/submissions-CIK0000021344.jsonnew file mode 100644index 0000000..6777842--- /dev/null+++ b/tests/fixtures/trader-analyst/submissions-CIK0000021344.json@@ -0,0 +1,352 @@+{+"cik": "0000021344",+"name": "COCA COLA CO",+"tickers": [+"KO"+],+"exchanges": [+"NYSE"+],+"fiscalYearEnd": "1231",+"filings": {+"recent": {+"accessionNumber": [+"0001950047-26-009841",+"0000876661-26-000782",+"0000021344-26-000167",+"0000021344-26-000165",+"0001950047-26-008485",+"0001950047-26-008383",+"0000021344-26-000163",+"0001950047-26-007906",+"0000021344-26-000161",+"0001950047-26-007764",+"0000021344-26-000158",+"0001950047-26-007471",+"0000021344-26-000156",+"0001950047-26-007403",+"0001628280-26-050503",+"0000021344-26-000154",+"0001950047-26-007361",+"0001950047-26-007358",+"0001628280-26-049922"+],+"filingDate": [+"2026-09-28",+"2026-09-22",+"2026-08-24",+"2026-08-21",+"2026-08-20",+"2026-08-19",+"2026-08-11",+"2026-08-10",+"2026-08-07",+"2026-08-06",+"2026-08-03",+"2026-07-31",+"2026-07-30",+"2026-07-29",+"2026-07-29",+"2026-07-29",+"2026-07-28",+"2026-07-28",+"2026-07-28"+],+"reportDate": [+"",+"",+"2026-08-20",+"2026-08-19",+"",+"",+"2026-08-10",+"",+"2026-08-06",+"",+"2026-07-31",+"",+"2026-07-28",+"",+"2026-07-03",+"2026-07-28",+"",+"",+"2026-07-28"+],+"acceptanceDateTime": [+"2026-09-28T20:20:08.000Z",+"2026-09-22T13:39:43.000Z",+"2026-08-24T16:04:00.000Z",+"2026-08-21T16:24:51.000Z",+"2026-08-20T21:03:07.000Z",+"2026-08-19T20:17:19.000Z",+"2026-08-11T16:30:02.000Z",+"2026-08-10T20:44:31.000Z",+"2026-08-07T19:19:22.000Z",+"2026-08-06T20:50:55.000Z",+"2026-08-03T15:52:54.000Z",+"2026-07-31T20:25:00.000Z",+"2026-07-30T15:51:14.000Z",+"2026-07-29T20:20:02.000Z",+"2026-07-29T18:04:37.000Z",+"2026-07-29T15:32:22.000Z",+"2026-07-28T20:22:33.000Z",+"2026-07-28T20:21:53.000Z",+"2026-07-28T10:58:13.000Z"+],+"act": [+"33",+"34",+"",+"",+"33",+"33",+"",+"33",+"",+"33",+"",+"33",+"",+"33",+"34",+"",+"33",+"33",+"34"+],+"form": [+"144",+"25-NSE",+"4",+"4",+"144",+"144",+"4",+"144",+"4",+"144",+"4",+"144",+"4",+"144",+"10-Q",+"4",+"144",+"144",+"8-K"+],+"fileNumber": [+"001-02217",+"001-02217",+"",+"",+"001-02217",+"001-02217",+"",+"001-02217",+"",+"001-02217",+"",+"001-02217",+"",+"001-02217",+"001-02217",+"",+"001-02217",+"001-02217",+"001-02217"+],+"filmNumber": [+"261417490",+"261395438",+"",+"",+"261300933",+"261295402",+"",+"261259147",+"",+"261250071",+"",+"261228851",+"",+"261217879",+"261216406",+"",+"261212172",+"261212154",+"261207488"+],+"items": [+"",+"",+"",+"",+"",+"",+"",+"",+"",+"",+"",+"",+"",+"",+"",+"",+"",+"",+"2.02,9.01"+],+"core_type": [+"144",+"25-NSE",+"4",+"4",+"144",+"144",+"4",+"144",+"4",+"144",+"4",+"144",+"4",+"144",+"XBRL",+"4",+"144",+"144",+"XBRL"+],+"size": [+4676,+3522,+20305,+11383,+6512,+4585,+4350,+4601,+18305,+8299,+12033,+4591,+17165,+7566,+14099008,+15209,+4680,+6855,+2262633+],+"isXBRL": [+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+1,+0,+0,+0,+1+],+"isInlineXBRL": [+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+1,+0,+0,+0,+1+],+"isXBRLNumeric": [+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+1,+0,+0,+0,+0+],+"primaryDocument": [+"xsl144X01/primary_doc.xml",+"xslF25X02/primary_doc.xml",+"xslF345X06/form4.xml",+"xslF345X06/form4.xml",+"xsl144X01/primary_doc.xml",+"xsl144X01/primary_doc.xml",+"xslF345X06/form4.xml",+"xsl144X01/primary_doc.xml",+"xslF345X06/form4.xml",+"xsl144X01/primary_doc.xml",+"xslF345X06/form4.xml",+"xsl144X01/primary_doc.xml",+"xslF345X06/form4.xml",+"xsl144X01/primary_doc.xml",+"ko-20260703.htm",+"xslF345X06/form4.xml",+"xsl144X01/primary_doc.xml",+"xsl144X01/primary_doc.xml",+"ko-20260728.htm"+],+"primaryDocDescription": [+"",+"",+"PRIMARY DOCUMENT",+"PRIMARY DOCUMENT",+"",+"",+"PRIMARY DOCUMENT",+"",+"PRIMARY DOCUMENT",+"",+"PRIMARY DOCUMENT",+"",+"PRIMARY DOCUMENT",+"",+"10-Q",+"PRIMARY DOCUMENT",+"",+"",+"8-K"+]+},+"files": []+}+}\ No newline at end of filediff --git a/tests/fixtures/trader-analyst/submissions-CIK0000320193.json b/tests/fixtures/trader-analyst/submissions-CIK0000320193.jsonnew file mode 100644index 0000000..4df55b6--- /dev/null+++ b/tests/fixtures/trader-analyst/submissions-CIK0000320193.json@@ -0,0 +1,512 @@+{+"cik": "0000320193",+"name": "Apple Inc.",+"tickers": [+"AAPL"+],+"exchanges": [+"Nasdaq"+],+"fiscalYearEnd": "0926",+"filings": {+"recent": {+"accessionNumber": [+"0001140361-26-039158",+"0001140361-26-038674",+"0001140361-26-038672",+"0001140361-26-038669",+"0001140361-26-038667",+"0001958244-26-000636",+"0001959173-26-007235",+"0001969223-26-001055",+"0001140361-26-038307",+"0001140361-26-038028",+"0001140361-26-038027",+"0001140361-26-038026",+"0001140361-26-038024",+"0001140361-26-038022",+"0001140361-26-038021",+"0001140361-26-037584",+"0001950047-26-009738",+"0001140361-26-037020",+"0001140361-26-036226",+"0001140361-26-035636",+"0001140361-26-035362",+"0001140361-26-035359",+"0001140361-26-035325",+"0001140361-26-034741",+"0001140361-26-033928",+"0001140361-26-032884",+"0001950047-26-007959",+"0000320193-26-000020",+"0000320193-26-000018"+],+"filingDate": [+"2026-10-08",+"2026-10-05",+"2026-10-05",+"2026-10-05",+"2026-10-05",+"2026-10-02",+"2026-10-02",+"2026-10-02",+"2026-10-01",+"2026-09-29",+"2026-09-29",+"2026-09-29",+"2026-09-29",+"2026-09-29",+"2026-09-29",+"2026-09-24",+"2026-09-22",+"2026-09-17",+"2026-09-10",+"2026-09-03",+"2026-09-01",+"2026-09-01",+"2026-09-01",+"2026-08-27",+"2026-08-20",+"2026-08-13",+"2026-08-11",+"2026-07-31",+"2026-07-30"+],+"reportDate": [+"2026-10-06",+"2026-10-01",+"2026-10-01",+"2026-10-01",+"2026-10-01",+"",+"",+"",+"2026-09-29",+"2026-09-27",+"2026-09-27",+"2026-09-27",+"2026-09-27",+"2026-09-27",+"2026-09-27",+"2026-09-22",+"",+"2026-09-15",+"2026-09-08",+"2026-09-01",+"2026-09-01",+"2026-09-01",+"2026-04-17",+"2026-08-25",+"2026-08-18",+"2026-08-11",+"",+"2026-06-27",+"2026-07-30"+],+"acceptanceDateTime": [+"2026-10-09T02:30:32.000Z",+"2026-10-06T02:42:45.000Z",+"2026-10-06T02:39:10.000Z",+"2026-10-06T02:35:24.000Z",+"2026-10-06T02:32:06.000Z",+"2026-10-03T01:17:10.000Z",+"2026-10-03T00:20:06.000Z",+"2026-10-03T00:09:51.000Z",+"2026-10-02T02:30:11.000Z",+"2026-09-30T02:44:50.000Z",+"2026-09-30T02:42:09.000Z",+"2026-09-30T02:39:19.000Z",+"2026-09-30T02:36:36.000Z",+"2026-09-30T02:33:40.000Z",+"2026-09-30T02:30:23.000Z",+"2026-09-25T02:30:07.000Z",+"2026-09-23T00:12:40.000Z",+"2026-09-18T02:30:24.000Z",+"2026-09-11T02:30:31.000Z",+"2026-09-04T02:30:44.000Z",+"2026-09-02T02:32:04.000Z",+"2026-09-02T02:30:11.000Z",+"2026-09-02T00:30:35.000Z",+"2026-08-28T02:30:30.000Z",+"2026-08-21T02:30:16.000Z",+"2026-08-14T02:30:20.000Z",+"2026-08-12T00:29:44.000Z",+"2026-07-31T14:01:02.000Z",+"2026-07-31T00:30:28.000Z"+],+"act": [+"",+"",+"",+"",+"",+"33",+"33",+"33",+"",+"",+"",+"",+"",+"",+"",+"",+"33",+"",+"",+"",+"",+"",+"34",+"",+"",+"",+"33",+"34",+"34"+],+"form": [+"4",+"4",+"4",+"4",+"4",+"144",+"144",+"144",+"4",+"4",+"4",+"4",+"4",+"4",+"4",+"4",+"144",+"4",+"4",+"4",+"4",+"3",+"8-K/A",+"4",+"4",+"4",+"144",+"10-Q",+"8-K"+],+"fileNumber": [+"",+"",+"",+"",+"",+"001-36743",+"001-36743",+"001-36743",+"",+"",+"",+"",+"",+"",+"",+"",+"001-36743",+"",+"",+"",+"",+"",+"001-36743",+"",+"",+"",+"001-36743",+"001-36743",+"001-36743"+],+"filmNumber": [+"",+"",+"",+"",+"",+"261437893",+"261436787",+"261436477",+"",+"",+"",+"",+"",+"",+"",+"",+"261396988",+"",+"",+"",+"",+"",+"261351260",+"",+"",+"",+"261263722",+"261225227",+"261223821"+],+"items": [+"",+"",+"",+"",+"",+"",+"",+"",+"",+"",+"",+"",+"",+"",+"",+"",+"",+"",+"",+"",+"",+"",+"5.02",+"",+"",+"",+"",+"",+"2.02,9.01"+],+"core_type": [+"4",+"4",+"4",+"4",+"4",+"144",+"144",+"144",+"4",+"4",+"4",+"4",+"4",+"4",+"4",+"4",+"144",+"4",+"4",+"4",+"4",+"3",+"XBRL",+"4",+"4",+"4",+"144",+"XBRL",+"XBRL"+],+"size": [+4822,+20288,+14780,+18851,+11578,+5383,+5724,+4440,+4822,+8159,+8207,+8239,+8230,+8164,+8259,+4822,+9273,+10785,+4681,+4681,+5615,+21103,+241262,+4672,+4672,+4672,+4966,+5946811,+417360+],+"isXBRL": [+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+1,+0,+0,+0,+0,+1,+1+],+"isInlineXBRL": [+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+1,+0,+0,+0,+0,+1,+1+],+"isXBRLNumeric": [+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+0,+1,+0+],+"primaryDocument": [+"xslF345X06/form4.xml",+"xslF345X06/form4.xml",+"xslF345X06/form4.xml",+"xslF345X06/form4.xml",+"xslF345X06/form4.xml",+"xsl144X01/primary_doc.xml",+"xsl144X01/primary_doc.xml",+"xsl144X01/primary_doc.xml",+"xslF345X06/form4.xml",+"xslF345X06/form4.xml",+"xslF345X06/form4.xml",+"xslF345X06/form4.xml",+"xslF345X06/form4.xml",+"xslF345X06/form4.xml",+"xslF345X06/form4.xml",+"xslF345X06/form4.xml",+"xsl144X01/primary_doc.xml",+"xslF345X06/form4.xml",+"xslF345X06/form4.xml",+"xslF345X06/form4.xml",+"xslF345X06/form4.xml",+"xslF345X06/form3.xml",+"ef20081427_8ka.htm",+"xslF345X06/form4.xml",+"xslF345X06/form4.xml",+"xslF345X06/form4.xml",+"xsl144X01/primary_doc.xml",+"aapl-20260627.htm",+"aapl-20260730.htm"+],+"primaryDocDescription": [+"FORM 4",+"FORM 4",+"FORM 4",+"FORM 4",+"FORM 4",+"",+"",+"",+"FORM 4",+"FORM 4",+"FORM 4",+"FORM 4",+"FORM 4",+"FORM 4",+"FORM 4",+"FORM 4",+"",+"FORM 4",+"FORM 4",+"FORM 4",+"FORM 4",+"FORM 3",+"8-K/A",+"FORM 4",+"FORM 4",+"FORM 4",+"",+"10-Q",+"8-K"+]+},+"files": []+}+}\ No newline at end of filediff --git a/tests/fixtures/trader-budget/berkshire-q2-2026-top5.json b/tests/fixtures/trader-budget/berkshire-q2-2026-top5.jsonnew file mode 100644index 0000000..34cd7b0--- /dev/null+++ b/tests/fixtures/trader-budget/berkshire-q2-2026-top5.json@@ -0,0 +1,48 @@+{+ "source": "Berkshire Hathaway Inc 13F-HR, Q2 2026, accession 0001193125-26-352200, filed 2026-08-14",+ "as_of": "2026-06-30",+ "table_value_total_usd": 299253556246,+ "note": "Top 5 issuers (share classes combined). weight = pct_of_13f, not yet renormalised.",+ "weights": [+ {+ "ticker": "AAPL",+ "name": "Apple",+ "issuer": "APPLE INC",+ "value_usd": 65950296923,+ "pct_of_13f": 22.04,+ "weight": 22.04+ },+ {+ "ticker": "AXP",+ "name": "American Express",+ "issuer": "AMERICAN EXPRESS CO",+ "value_usd": 51282319275,+ "pct_of_13f": 17.14,+ "weight": 17.14+ },+ {+ "ticker": "GOOGL",+ "name": "Alphabet",+ "issuer": "ALPHABET INC",+ "value_usd": 37764088383,+ "pct_of_13f": 12.62,+ "weight": 12.62+ },+ {+ "ticker": "KO",+ "name": "Coca-Cola",+ "issuer": "COCA COLA CO",+ "value_usd": 32508000000,+ "pct_of_13f": 10.86,+ "weight": 10.86+ },+ {+ "ticker": "BAC",+ "name": "Bank of America",+ "issuer": "BANK OF AMER CORP",+ "value_usd": 27543790975,+ "pct_of_13f": 9.2,+ "weight": 9.2+ }+ ]+}diff --git a/tests/fixtures/trader-budget/plan-tsla.json b/tests/fixtures/trader-budget/plan-tsla.jsonnew file mode 100644index 0000000..9a1b0ae--- /dev/null+++ b/tests/fixtures/trader-budget/plan-tsla.json@@ -0,0 +1,21 @@+{+ "created_by": "trader-exit",+ "symbol": "TSLA",+ "side": "buy",+ "date": "2026-10-19",+ "setup": "orb",+ "entry": 364.18,+ "entry_time": "10:15 AM",+ "entry_bar": 8,+ "interval": "5m",+ "opening_range": {"high": 362.18, "low": 354.47, "minutes": 15},+ "stop": 358.32,+ "stop_rule": "or_mid",+ "stop_label": "opening-range midpoint",+ "target": 370.04,+ "target_r": 1.0,+ "target_label": "1R (one times the risk)",+ "risk_per_share": 5.86,+ "reward_risk": 1.0,+ "flat_by": "15:55"+}diff --git a/tests/fixtures/trader-entry/DEMO-1m-synthetic.json b/tests/fixtures/trader-entry/DEMO-1m-synthetic.jsonnew file mode 100644index 0000000..60b9379--- /dev/null+++ b/tests/fixtures/trader-entry/DEMO-1m-synthetic.json@@ -0,0 +1 @@+{"chart":{"result":[{"meta":{"currency":"USD","symbol":"DEMO","exchangeName":"NMS","instrumentType":"EQUITY","regularMarketTime":1792418790,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":100.9,"chartPreviousClose":99.5,"previousClose":99.5,"priceHint":2,"dataGranularity":"1m","range":"1d","note":"SYNTHETIC test bars for trader-entry, not market data"},"timestamp":[1792416600,1792416660,1792416720,1792416780,1792416840,1792416900,1792416960,1792417020,1792417080,1792417140,1792417200,1792417260,1792417320,1792417380,1792417440,1792417500,1792417560,1792417620,1792417680,1792417740,1792417800,1792417860,1792417920,1792417980,1792418040,1792418100,1792418160,1792418220,1792418280,1792418340,1792418400,1792418460,1792418520,1792418580,1792418640,1792418700,1792418760,1792418790],"indicators":{"quote":[{"open":[99.8,100.0,99.2,99.85,100.3,100.0,99.75,99.6,99.85,100.05,100.2,100.15,100.1,100.0,100.05,100.25,100.4,100.35,100.2,null,100.1,100.2,100.3,100.3,100.35,100.4,100.45,100.35,100.5,100.62,100.7,100.65,100.8,100.85,100.9,100.95,100.88,100.9],"high":[100.2,100.1,99.9,100.5,100.4,100.2,99.95,99.9,100.1,100.25,100.35,100.3,100.2,100.15,100.3,100.45,100.48,100.4,100.3,null,100.25,100.35,100.7,100.4,100.45,100.5,100.5,100.5,100.7,100.75,100.78,100.85,100.9,100.95,101.0,101.05,100.95,100.9],"low":[99.4,99.0,99.1,99.8,99.9,99.7,99.5,99.55,99.8,100.0,100.1,100.0,99.95,99.9,100.0,100.2,100.3,100.1,100.05,null,100.0,100.15,100.25,100.2,100.3,100.35,100.3,100.3,100.45,100.55,100.6,100.6,100.7,100.75,100.8,100.85,100.85,100.9],"close":[100.0,99.2,99.85,100.3,100.0,99.75,99.6,99.85,100.05,100.2,100.15,100.1,100.0,100.05,100.25,100.4,100.35,100.2,100.1,null,100.2,100.3,100.3,100.35,100.4,100.45,100.35,100.5,100.62,100.7,100.65,100.8,100.85,100.9,100.95,100.88,100.9,100.9],"volume":[60000,15000,9000,12000,8000,7000,6000,6000,7000,6000,5000,5000,4000,5000,5000,6000,5000,4000,4000,null,4000,5000,15000,5000,5000,6000,5000,6000,9000,8000,7000,30000,9000,8000,8000,7000,2000,0]}]}}],"error":null}}\ No newline at end of filediff --git a/tests/fixtures/trader-entry/TSLA-2026-10-19-5m.json b/tests/fixtures/trader-entry/TSLA-2026-10-19-5m.jsonnew file mode 100644index 0000000..f1c4bdf--- /dev/null+++ b/tests/fixtures/trader-entry/TSLA-2026-10-19-5m.json@@ -0,0 +1 @@+{"chart":{"result":[{"meta":{"currency":"USD","symbol":"TSLA","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":1277818200,"regularMarketTime":1792421385,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":366.07,"regularMarketChangePercent":3.2,"fulldayPrice":366.07,"fulldayChange":11.35,"fulldayChangePercent":3.2,"fiftyTwoWeekHigh":498.83,"fiftyTwoWeekLow":297.38,"regularMarketDayHigh":367.57,"regularMarketDayLow":354.47,"regularMarketVolume":14779043,"longName":"Tesla, Inc.","shortName":"Tesla, Inc.","chartPreviousClose":354.72,"previousClose":354.72,"scale":3,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","start":1792396800,"end":1792416600,"gmtoffset":-14400},"regular":{"timezone":"EDT","start":1792416600,"end":1792440000,"gmtoffset":-14400},"post":{"timezone":"EDT","start":1792440000,"end":1792454400,"gmtoffset":-14400}},"tradingPeriods":[[{"timezone":"EDT","start":1792416600,"end":1792440000,"gmtoffset":-14400}]],"dataGranularity":"5m","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1792416600,1792416900,1792417200,1792417500,1792417800,1792418100,1792418400,1792418700,1792419000,1792419300,1792419600,1792419900,1792420200,1792420500,1792420800,1792421100,1792421385],"indicators":{"quote":[{"open":[357.4849853515625,359.20001220703125,358.1524963378906,360.3699951171875,361.4465026855469,361.010009765625,361.92498779296875,361.4949951171875,361.67999267578125,364.2149963378906,365.0450134277344,365.739990234375,365.8900146484375,365.739990234375,365.7182922363281,366.2099914550781,366.07000732421875],"high":[362.17999267578125,360.0249938964844,361.2200012207031,361.510009765625,362.9200134277344,362.8999938964844,362.1787109375,361.8799133300781,364.3900146484375,365.17999267578125,365.8800048828125,366.739990234375,366.2099914550781,366.489990234375,366.7795104980469,367.5987854003906,366.07000732421875],"low":[354.4700012207031,356.3699951171875,357.8900146484375,359.3800048828125,359.4599914550781,360.8599853515625,360.0201110839844,360.4200134277344,361.3699951171875,363.0,364.3999938964844,365.3999938964844,365.30999755859375,365.1099853515625,365.6285095214844,366.20001220703125,366.07000732421875],"close":[359.17999267578125,358.2699890136719,360.385009765625,361.45001220703125,361.06939697265625,361.92498779296875,361.468505859375,361.67999267578125,364.1759948730469,365.0450134277344,365.75,365.8500061035156,365.75,365.69500732421875,366.1050109863281,366.67999267578125,366.07000732421875],"volume":[3080684,964899,931253,794838,1207272,805723,617820,558955,1000057,982318,739146,748942,13232032,512101,594767,618280,0]}]}}],"error":null}}\ No newline at end of filediff --git a/tests/fixtures/trader-news/chart-TSLA.json b/tests/fixtures/trader-news/chart-TSLA.jsonnew file mode 100644index 0000000..453781a--- /dev/null+++ b/tests/fixtures/trader-news/chart-TSLA.json@@ -0,0 +1 @@+{"chart":{"result":[{"meta":{"currency":"USD","symbol":"TSLA","exchangeName":"NMS","instrumentType":"EQUITY","regularMarketTime":1792421533,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":366.475,"chartPreviousClose":354.72,"previousClose":354.72,"longName":"Tesla, Inc.","shortName":"Tesla, Inc.","dataGranularity":"5m","range":"1d"},"timestamp":[1792416600,1792416900,1792417200,1792417500,1792417800,1792418100,1792418400,1792418700,1792419000,1792419300,1792419600,1792419900,1792420200,1792420500,1792420800,1792421100,1792421400,1792421533],"indicators":{"quote":[{"close":[359.17999267578125,358.2699890136719,360.385009765625,361.45001220703125,361.06939697265625,361.92498779296875,361.468505859375,361.67999267578125,364.1759948730469,365.0450134277344,365.75,365.8500061035156,365.75,365.69500732421875,366.1050109863281,365.7300109863281,366.7449951171875,366.4750061035156],"high":[362.17999267578125,360.0249938964844,361.2200012207031,361.510009765625,362.9200134277344,362.8999938964844,362.1787109375,361.8799133300781,364.3900146484375,365.17999267578125,365.8800048828125,366.739990234375,366.2099914550781,366.489990234375,366.7795104980469,367.5987854003906,366.87890625,366.4750061035156],"low":[354.4700012207031,356.3699951171875,357.8900146484375,359.3800048828125,359.4599914550781,360.8599853515625,360.0201110839844,360.4200134277344,361.3699951171875,363.0,364.3999938964844,365.3999938964844,365.30999755859375,365.1099853515625,365.6285095214844,365.7200012207031,365.3999938964844,366.4750061035156],"open":[357.4849853515625,359.20001220703125,358.1524963378906,360.3699951171875,361.4465026855469,361.010009765625,361.92498779296875,361.4949951171875,361.67999267578125,364.2149963378906,365.0450134277344,365.739990234375,365.8900146484375,365.739990234375,365.7182922363281,366.2099914550781,365.7149963378906,366.4750061035156],"volume":[3080684,964899,931253,794838,1207272,805723,617820,558955,1000057,982318,739146,748942,13232032,512101,594767,713677,228811,0]}]}}],"error":null}}\ No newline at end of filediff --git a/tests/fixtures/trader-news/company_tickers.json b/tests/fixtures/trader-news/company_tickers.jsonnew file mode 100644index 0000000..56fb970--- /dev/null+++ b/tests/fixtures/trader-news/company_tickers.json@@ -0,0 +1,37 @@+{+"1": {+"cik_str": 320193,+"ticker": "AAPL",+"title": "Apple Inc."+},+"2": {+"cik_str": 1652044,+"ticker": "GOOGL",+"title": "Alphabet Inc."+},+"9": {+"cik_str": 1067983,+"ticker": "BRK-B",+"title": "BERKSHIRE HATHAWAY INC"+},+"28": {+"cik_str": 21344,+"ticker": "KO",+"title": "COCA COLA CO"+},+"29": {+"cik_str": 70858,+"ticker": "BAC",+"title": "BANK OF AMERICA CORP /DE/"+},+"70": {+"cik_str": 4962,+"ticker": "AXP",+"title": "AMERICAN EXPRESS CO"+},+"7481": {+"cik_str": 1652044,+"ticker": "GOOG",+"title": "Alphabet Inc."+}+}\ No newline at end of filediff --git a/tests/fixtures/trader-news/sec-8-K-0000021344.xml b/tests/fixtures/trader-news/sec-8-K-0000021344.xmlnew file mode 100644index 0000000..af6d565--- /dev/null+++ b/tests/fixtures/trader-news/sec-8-K-0000021344.xml@@ -0,0 +1,106 @@+<?xml version="1.0" encoding="ISO-8859-1" ?>+ <feed xmlns="http://www.w3.org/2005/Atom">+ <author>+ <email>[email protected]</email>+ <name>Webmaster</name>+ </author>+ <company-info>+ <addresses>+ <address type="mailing">+ <city>ATLANTA</city>+ <state>GA</state>+ <street1>ONE COCA COLA PLAZA</street1>+ <zip>30313</zip>+ </address>+ <address type="business">+ <city>ATLANTA</city>+ <phone>404-676-2121</phone>+ <state>GA</state>+ <street1>ONE COCA COLA PLAZA</street1>+ <zip>30313</zip>+ </address>+ </addresses>+ <assigned-sic>2080</assigned-sic>+ <assigned-sic-desc>BEVERAGES</assigned-sic-desc>+ <assigned-sic-href>https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&SIC=2080&owner=include&count=10</assigned-sic-href>+ <cik>0000021344</cik>+ <cik-href>https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=0000021344&owner=include&count=10</cik-href>+ <conformed-name>COCA COLA CO</conformed-name>+ <fiscal-year-end>1231</fiscal-year-end>+ <state-location>GA</state-location>+ <state-location-href>https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&State=GA&owner=include&count=10</state-location-href>+ <state-of-incorporation>DE</state-of-incorporation>+ </company-info>+ <entry>+ <category label="form type" scheme="https://www.sec.gov/" term="8-K" />+ <content type="text/xml">+ <accession-number>0001628280-26-049922</accession-number>+ <act>34</act>+ <file-number>001-02217</file-number>+ <file-number-href>https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&filenum=001-02217&owner=include&count=10</file-number-href>+ <filing-date>2026-07-28</filing-date>+ <filing-href>https://www.sec.gov/Archives/edgar/data/21344/000162828026049922/0001628280-26-049922-index.htm</filing-href>+ <filing-type>8-K</filing-type>+ <film-number>261207488</film-number>+ <form-name>Current report</form-name>+ <items-desc>items 2.02 and 9.01</items-desc>+ <size>2 MB</size>+ <xbrl_href>https://www.sec.gov/cgi-bin/viewer?action=view&cik=21344&accession_number=0001628280-26-049922&xbrl_type=f</xbrl_href>+ </content>+ <id>urn:tag:sec.gov,2008:accession-number=0001628280-26-049922</id>+ <link href="https://www.sec.gov/Archives/edgar/data/21344/000162828026049922/0001628280-26-049922-index.htm" rel="alternate" type="text/html" />+ <summary type="html"> <b>Filed:</b> 2026-07-28 <b>AccNo:</b> 0001628280-26-049922 <b>Size:</b> 2 MB<br>Item 2.02: Results of Operations and Financial Condition<br>Item 9.01: Financial Statements and Exhibits</summary>+ <title>8-K - Current report</title>+ <updated>2026-07-28T06:58:13-04:00</updated>+ </entry>+ <entry>+ <category label="form type" scheme="https://www.sec.gov/" term="8-K" />+ <content type="text/xml">+ <accession-number>0001628280-26-048466</accession-number>+ <act>34</act>+ <file-number>001-02217</file-number>+ <file-number-href>https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&filenum=001-02217&owner=include&count=10</file-number-href>+ <filing-date>2026-07-16</filing-date>+ <filing-href>https://www.sec.gov/Archives/edgar/data/21344/000162828026048466/0001628280-26-048466-index.htm</filing-href>+ <filing-type>8-K</filing-type>+ <film-number>261180597</film-number>+ <form-name>Current report</form-name>+ <items-desc>item 8.01</items-desc>+ <size>906 KB</size>+ <xbrl_href>https://www.sec.gov/cgi-bin/viewer?action=view&cik=21344&accession_number=0001628280-26-048466&xbrl_type=f</xbrl_href>+ </content>+ <id>urn:tag:sec.gov,2008:accession-number=0001628280-26-048466</id>+ <link href="https://www.sec.gov/Archives/edgar/data/21344/000162828026048466/0001628280-26-048466-index.htm" rel="alternate" type="text/html" />+ <summary type="html"> <b>Filed:</b> 2026-07-16 <b>AccNo:</b> 0001628280-26-048466 <b>Size:</b> 906 KB<br>Item 8.01: Other Events</summary>+ <title>8-K - Current report</title>+ <updated>2026-07-16T16:20:56-04:00</updated>+ </entry>+ <entry>+ <category label="form type" scheme="https://www.sec.gov/" term="8-K" />+ <content type="text/xml">+ <accession-number>0001552781-26-000366</accession-number>+ <act>34</act>+ <file-number>001-02217</file-number>+ <file-number-href>https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&filenum=001-02217&owner=include&count=10</file-number-href>+ <filing-date>2026-06-25</filing-date>+ <filing-href>https://www.sec.gov/Archives/edgar/data/21344/000155278126000366/0001552781-26-000366-index.htm</filing-href>+ <filing-type>8-K</filing-type>+ <film-number>261122139</film-number>+ <form-name>Current report</form-name>+ <items-desc>items 5.02 and 9.01</items-desc>+ <size>1 MB</size>+ <xbrl_href>https://www.sec.gov/cgi-bin/viewer?action=view&cik=21344&accession_number=0001552781-26-000366&xbrl_type=f</xbrl_href>+ </content>+ <id>urn:tag:sec.gov,2008:accession-number=0001552781-26-000366</id>+ <link href="https://www.sec.gov/Archives/edgar/data/21344/000155278126000366/0001552781-26-000366-index.htm" rel="alternate" type="text/html" />+ <summary type="html"> <b>Filed:</b> 2026-06-25 <b>AccNo:</b> 0001552781-26-000366 <b>Size:</b> 1 MB<br>Item 5.02: Departure of Directors or Certain Officers; Election of Directors; Appointment of Certain Officers: Compensatory Arrangements of Certain Officers<br>Item 9.01: Financial Statements and Exhibits</summary>+ <title>8-K - Current report</title>+ <updated>2026-06-25T16:19:25-04:00</updated>+ </entry>+ <id>https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=0000021344</id>+ <link href="https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=0000021344&type=8-K&owner=include&start=0&count=10" rel="alternate" type="text/html" />+ <link href="https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=0000021344&type=8-K&owner=include&start=0&count=10&output=atom" rel="self" type="application/atom+xml" />+ <link href="https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=0000021344&type=8-K%25&datea=&dateb=&owner=include&count=10&output=atom&start=10" rel="next" type="application/atom+xml" />+ <title>COCA COLA CO (0000021344)</title>+ <updated>2026-10-13T22:33:31-04:00</updated>+ </feed>diff --git a/tests/fixtures/trader-news/sec-8-K-0000320193.xml b/tests/fixtures/trader-news/sec-8-K-0000320193.xmlnew file mode 100644index 0000000..0f0b92f--- /dev/null+++ b/tests/fixtures/trader-news/sec-8-K-0000320193.xml@@ -0,0 +1,121 @@+<?xml version="1.0" encoding="ISO-8859-1" ?>+ <feed xmlns="http://www.w3.org/2005/Atom">+ <author>+ <email>[email protected]</email>+ <name>Webmaster</name>+ </author>+ <company-info>+ <addresses>+ <address type="mailing">+ <city>CUPERTINO</city>+ <state>CA</state>+ <street1>ONE APPLE PARK WAY</street1>+ <zip>95014</zip>+ </address>+ <address type="business">+ <city>CUPERTINO</city>+ <phone>(408) 996-1010</phone>+ <state>CA</state>+ <street1>ONE APPLE PARK WAY</street1>+ <zip>95014</zip>+ </address>+ </addresses>+ <assigned-sic>3571</assigned-sic>+ <assigned-sic-desc>ELECTRONIC COMPUTERS</assigned-sic-desc>+ <assigned-sic-href>https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&SIC=3571&owner=include&count=10</assigned-sic-href>+ <cik>0000320193</cik>+ <cik-href>https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=0000320193&owner=include&count=10</cik-href>+ <conformed-name>Apple Inc.</conformed-name>+ <fiscal-year-end>0926</fiscal-year-end>+ <formerly-names count="3">+ <names>+ <date>2007-01-04</date>+ <name>APPLE COMPUTER INC</name>+ </names>+ <names>+ <date>1997-07-28</date>+ <name>APPLE COMPUTER INC/ FA</name>+ </names>+ <names>+ <date>2019-08-05</date>+ <name>APPLE INC</name>+ </names>+ </formerly-names>+ <state-location>CA</state-location>+ <state-location-href>https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&State=CA&owner=include&count=10</state-location-href>+ <state-of-incorporation>CA</state-of-incorporation>+ </company-info>+ <entry>+ <category label="form type" scheme="https://www.sec.gov/" term="8-K/A" />+ <content type="text/xml">+ <accession-number>0001140361-26-035325</accession-number>+ <act>34</act>+ <amend>[Amend]</amend>+ <file-number>001-36743</file-number>+ <file-number-href>https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&filenum=001-36743&owner=include&count=10</file-number-href>+ <filing-date>2026-09-01</filing-date>+ <filing-href>https://www.sec.gov/Archives/edgar/data/320193/000114036126035325/0001140361-26-035325-index.htm</filing-href>+ <filing-type>8-K/A</filing-type>+ <film-number>261351260</film-number>+ <form-name>Current report</form-name>+ <items-desc>item 5.02</items-desc>+ <size>241 KB</size>+ <xbrl_href>https://www.sec.gov/cgi-bin/viewer?action=view&cik=320193&accession_number=0001140361-26-035325&xbrl_type=f</xbrl_href>+ </content>+ <id>urn:tag:sec.gov,2008:accession-number=0001140361-26-035325</id>+ <link href="https://www.sec.gov/Archives/edgar/data/320193/000114036126035325/0001140361-26-035325-index.htm" rel="alternate" type="text/html" />+ <summary type="html"> <b>Filed:</b> 2026-09-01 <b>AccNo:</b> 0001140361-26-035325 <b>Size:</b> 241 KB<br>Item 5.02: Departure of Directors or Certain Officers; Election of Directors; Appointment of Certain Officers: Compensatory Arrangements of Certain Officers</summary>+ <title>8-K/A [Amend] - Current report</title>+ <updated>2026-09-01T16:30:35-04:00</updated>+ </entry>+ <entry>+ <category label="form type" scheme="https://www.sec.gov/" term="8-K" />+ <content type="text/xml">+ <accession-number>0000320193-26-000018</accession-number>+ <act>34</act>+ <file-number>001-36743</file-number>+ <file-number-href>https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&filenum=001-36743&owner=include&count=10</file-number-href>+ <filing-date>2026-07-30</filing-date>+ <filing-href>https://www.sec.gov/Archives/edgar/data/320193/000032019326000018/0000320193-26-000018-index.htm</filing-href>+ <filing-type>8-K</filing-type>+ <film-number>261223821</film-number>+ <form-name>Current report</form-name>+ <items-desc>items 2.02 and 9.01</items-desc>+ <size>417 KB</size>+ <xbrl_href>https://www.sec.gov/cgi-bin/viewer?action=view&cik=320193&accession_number=0000320193-26-000018&xbrl_type=f</xbrl_href>+ </content>+ <id>urn:tag:sec.gov,2008:accession-number=0000320193-26-000018</id>+ <link href="https://www.sec.gov/Archives/edgar/data/320193/000032019326000018/0000320193-26-000018-index.htm" rel="alternate" type="text/html" />+ <summary type="html"> <b>Filed:</b> 2026-07-30 <b>AccNo:</b> 0000320193-26-000018 <b>Size:</b> 417 KB<br>Item 2.02: Results of Operations and Financial Condition<br>Item 9.01: Financial Statements and Exhibits</summary>+ <title>8-K - Current report</title>+ <updated>2026-07-30T16:30:28-04:00</updated>+ </entry>+ <entry>+ <category label="form type" scheme="https://www.sec.gov/" term="8-K" />+ <content type="text/xml">+ <accession-number>0000320193-26-000011</accession-number>+ <act>34</act>+ <file-number>001-36743</file-number>+ <file-number-href>https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&filenum=001-36743&owner=include&count=10</file-number-href>+ <filing-date>2026-04-30</filing-date>+ <filing-href>https://www.sec.gov/Archives/edgar/data/320193/000032019326000011/0000320193-26-000011-index.htm</filing-href>+ <filing-type>8-K</filing-type>+ <film-number>26926130</film-number>+ <form-name>Current report</form-name>+ <items-desc>items 2.02 and 9.01</items-desc>+ <size>412 KB</size>+ <xbrl_href>https://www.sec.gov/cgi-bin/viewer?action=view&cik=320193&accession_number=0000320193-26-000011&xbrl_type=f</xbrl_href>+ </content>+ <id>urn:tag:sec.gov,2008:accession-number=0000320193-26-000011</id>+ <link href="https://www.sec.gov/Archives/edgar/data/320193/000032019326000011/0000320193-26-000011-index.htm" rel="alternate" type="text/html" />+ <summary type="html"> <b>Filed:</b> 2026-04-30 <b>AccNo:</b> 0000320193-26-000011 <b>Size:</b> 412 KB<br>Item 2.02: Results of Operations and Financial Condition<br>Item 9.01: Financial Statements and Exhibits</summary>+ <title>8-K - Current report</title>+ <updated>2026-04-30T16:30:41-04:00</updated>+ </entry>+ <id>https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=0000320193</id>+ <link href="https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=0000320193&type=8-K&owner=include&start=0&count=10" rel="alternate" type="text/html" />+ <link href="https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=0000320193&type=8-K&owner=include&start=0&count=10&output=atom" rel="self" type="application/atom+xml" />+ <link href="https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=0000320193&type=8-K%25&datea=&dateb=&owner=include&count=10&output=atom&start=10" rel="next" type="application/atom+xml" />+ <title>Apple Inc. (0000320193)</title>+ <updated>2026-10-13T22:18:10-04:00</updated>+ </feed>diff --git a/tests/fixtures/trader-news/yahoo-AAPL.xml b/tests/fixtures/trader-news/yahoo-AAPL.xmlnew file mode 100644index 0000000..8986606--- /dev/null+++ b/tests/fixtures/trader-news/yahoo-AAPL.xml@@ -0,0 +1,60 @@+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<rss version="2.0">+ <channel>+ <copyright>Copyright (c) 2026 Yahoo Inc. All rights reserved.</copyright>+ <description>Latest Financial News for AAPL</description>+ <image>+ <height>45</height>+ <link>http://finance.yahoo.com/q/h?s=AAPL</link>+ <title>Yahoo! Finance: AAPL News</title>+ <url>https://s.yimg.com/rz/stage/p/yahoo_finance_en-US_h_p_finance_2.png</url>+ <width>144</width>+ </image>+ <item>+ <description>Yahoo Finance Technology Editor Dan Howley joins Market Domination host Brooke DiPalma to discuss the latest round of Apple (AAPL) smart home products and the company's edge in competing with Google (GOOG) and Amazon (AMZN).</description>+ <guid isPermaLink="false">b32e819f-7aa9-4b0a-91b1-3ac7979de1f4</guid>+ <link>https://finance.yahoo.com/video/apple-may-have-a-way-to-dominate-the-smart-home-space-194652300.html?.tsrc=rss</link>+ <pubDate>Tue, 13 Oct 2026 19:46:52 +0000</pubDate>+ <title>Apple may have a way to dominate the smart home space</title>+ </item>+ <item>+ <description>Apple’s new smart-home hub puts messages, calendars, FaceTime and smart home controls on a screen designed to make your iPhone less essential at home. WSJ’s Nicole Nguyen gives her first impressions.</description>+ <guid isPermaLink="false">1fe6cc83-8d8f-3bbc-a80a-df68fd475409</guid>+ <link>https://finance.yahoo.com/video/apple-299-homeview-tech-giant-222100009.html?.tsrc=rss</link>+ <pubDate>Tue, 13 Oct 2026 22:21:00 +0000</pubDate>+ <title>Apple’s $299 HomeView Is The Tech Giant’s Next Bet on the Smart Home</title>+ </item>+ <item>+ <description>Apple stock finished with a market cap of $4.98 trillion after it released its new smart home lineup.</description>+ <guid isPermaLink="false">44e3206a-a255-3b83-94a0-ab1efc4b012f</guid>+ <link>https://finance.yahoo.com/m/44e3206a-a255-3b83-94a0-ab1efc4b012f/apple-takes-on-amazon-with.html?.tsrc=rss</link>+ <pubDate>Tue, 13 Oct 2026 20:37:00 +0000</pubDate>+ <title>Apple Takes on Amazon With New Smart Home Gadgets. It Still Isn’t Worth $5 Trillion.</title>+ </item>+ <item>+ <description>A federal judge ruled that Apple can access OpenAI's interview materials involving former Apple employees, as well as private messages and testimony from key figures in the case.</description>+ <guid isPermaLink="false">d3667d87-c646-3bba-acee-f2232e1aca9c</guid>+ <link>https://finance.yahoo.com/technology/ai/articles/judge-orders-openai-turn-over-203644748.html?.tsrc=rss</link>+ <pubDate>Tue, 13 Oct 2026 20:36:44 +0000</pubDate>+ <title>Judge orders OpenAI to turn over hiring records in Apple trade secrets case</title>+ </item>+ <item>+ <description>Apple entered the smart home market with a product launch event headlined by the company's HomeView device control hub. Apple stock rose.</description>+ <guid isPermaLink="false">24497fee-3636-3690-9127-568bddae03f0</guid>+ <link>https://finance.yahoo.com/m/24497fee-3636-3690-9127-568bddae03f0/apple-introduces-homeview.html?.tsrc=rss</link>+ <pubDate>Tue, 13 Oct 2026 20:24:24 +0000</pubDate>+ <title>Apple Introduces HomeView Smart Home Hub, Other Gadgets</title>+ </item>+ <item>+ <description>New CEO John Ternus rides countertop gadgets to a $5 trillion market cap.</description>+ <guid isPermaLink="false">40221747-5f82-3945-9291-021447756a0c</guid>+ <link>https://app.moby.co/home/news/news-apple-hits-fresh-all-time-high?utm_source=yahoo_finance&utm_medium=rss&.tsrc=rss</link>+ <pubDate>Tue, 13 Oct 2026 19:50:32 +0000</pubDate>+ <title>Apple Hits Fresh All-Time High</title>+ </item>+ <language>en-US</language>+ <lastBuildDate>Wed, 14 Oct 2026 02:18:03 +0000</lastBuildDate>+ <link>http://finance.yahoo.com/q/h?s=AAPL</link>+ <title>Yahoo! Finance: AAPL News</title>+ </channel>+</rss>diff --git a/tests/fixtures/trader-news/yahoo-KO.xml b/tests/fixtures/trader-news/yahoo-KO.xmlnew file mode 100644index 0000000..07c4b96--- /dev/null+++ b/tests/fixtures/trader-news/yahoo-KO.xml@@ -0,0 +1,46 @@+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<rss version="2.0">+ <channel>+ <copyright>Copyright (c) 2026 Yahoo Inc. All rights reserved.</copyright>+ <description>Latest Financial News for KO</description>+ <image>+ <height>45</height>+ <link>http://finance.yahoo.com/q/h?s=KO</link>+ <title>Yahoo! Finance: KO News</title>+ <url>https://s.yimg.com/rz/stage/p/yahoo_finance_en-US_h_p_finance_2.png</url>+ <width>144</width>+ </image>+<item>+ <description>Key TakeawaysChevron yields 3. 4%, and Coca-Cola 2.</description>+ <guid isPermaLink="false">7686cd29-a1bb-3108-9dc8-298261c05359</guid>+ <link>https://www.tikr.com/blog/coca-cola-or-chevron-the-one-dividend-stock-id-hold-for-the-next-20-years?ref=yahoofinance&.tsrc=rss</link>+ <pubDate>Tue, 13 Oct 2026 20:02:03 +0000</pubDate>+ <title>Coca-Cola or Chevron: The One Dividend Stock I’d Hold for the Next 20 Years</title>+ </item>+ <item>+ <description>Coca-Cola has handed income investors a bigger check every year for six decades, but last year its dividend bill outpaced its free cash flow by billions. Whether that gap signals trouble or a one-time blip could define the next ten years of raises.</description>+ <guid isPermaLink="false">c3603a17-81cd-3157-a433-a539bf8b085a</guid>+ <link>https://247wallst.com/investing/2026/10/13/coca-cola-has-raised-dividends-for-63-years-can-it-make-it-another-decade/?.tsrc=rss</link>+ <pubDate>Tue, 13 Oct 2026 18:45:42 +0000</pubDate>+ <title>Coca-Cola Has Raised Dividends for 63 Years. Can It Make It Another Decade?</title>+ </item>+ <item>+ <description>Here is how Coca-Cola (KO) and Grocery Outlet Holding Corp. (GO) have performed compared to their sector so far this year.</description>+ <guid isPermaLink="false">3650af04-b760-3d69-902a-3fd9fba44194</guid>+ <link>https://finance.yahoo.com/markets/stocks/articles/coca-cola-ko-stock-outpacing-124002572.html?.tsrc=rss</link>+ <pubDate>Tue, 13 Oct 2026 12:40:02 +0000</pubDate>+ <title>Is Coca-Cola (KO) Stock Outpacing Its Consumer Staples Peers This Year?</title>+ </item>+ <item>+ <description>PEP trades near its 52-week low as North American weakness, margin pressures and reduced earnings expectations raise questions about its recovery prospects.</description>+ <guid isPermaLink="false">8cb2b8e5-64c9-3309-854e-90e702035345</guid>+ <link>https://finance.yahoo.com/markets/stocks/articles/pepsico-trades-near-52-week-153700765.html?.tsrc=rss</link>+ <pubDate>Tue, 13 Oct 2026 15:37:00 +0000</pubDate>+ <title>PepsiCo Trades Near 52-Week Low: Should You Buy Now or Wait?</title>+ </item>+ <language>en-US</language>+ <lastBuildDate>Wed, 14 Oct 2026 02:33:31 +0000</lastBuildDate>+ <link>http://finance.yahoo.com/q/h?s=KO</link>+ <title>Yahoo! Finance: KO News</title>+ </channel>+</rss>diff --git a/tests/fixtures/trader-news/yahoo-TSLA.xml b/tests/fixtures/trader-news/yahoo-TSLA.xmlnew file mode 100644index 0000000..91b0c5c--- /dev/null+++ b/tests/fixtures/trader-news/yahoo-TSLA.xml@@ -0,0 +1,144 @@+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<rss version="2.0">+ <channel>+ <copyright>Copyright (c) 2026 Yahoo Inc. All rights reserved.</copyright>+ <description>Latest Financial News for TSLA</description>+ <image>+ <height>45</height>+ <link>http://finance.yahoo.com/q/h?s=TSLA</link>+ <title>Yahoo! Finance: TSLA News</title>+ <url>https://s.yimg.com/rz/stage/p/yahoo_finance_en-US_h_p_finance_2.png</url>+ <width>144</width>+ </image>+ <item>+ <description>Yahoo Finance Executive Editor Brian Sozzi breaks down Elon Musk's monumental five-day run — unveiling a flying, barrel-rolling electric Tesla (TSLA) car and wanting to gift every kid in the U.S. one share of SpaceX (SPCX) starting next year — and why it's not worth listening to the skeptics.</description>+ <guid isPermaLink="false">7bf93755-a466-4f4d-ab3a-310908f3eca2</guid>+ <link>https://finance.yahoo.com/video/what-to-say-to-the-skeptics-during-elon-musks-five-day-run-143217090.html?.tsrc=rss</link>+ <pubDate>Mon, 19 Oct 2026 14:32:17 +0000</pubDate>+ <title>What to say to the skeptics during Elon Musk's five-day run</title>+ </item>+ <item>+ <description>Stocks gained on Monday as investors shifted their focus to earnings from Netflix, Tesla, and Meta.</description>+ <guid isPermaLink="false">2c1007e0-fb36-49e5-9e7f-d70b7d446f3d</guid>+ <link>https://finance.yahoo.com/markets/article/tech-rebounds-as-semiconductor-stocks-jump-alphacheck-135003909.html?.tsrc=rss</link>+ <pubDate>Mon, 19 Oct 2026 13:50:03 +0000</pubDate>+ <title>Tech rebounds as semiconductor stocks jump: AlphaCheck</title>+ </item>+ <item>+ <description>Big Tech's Q3 earnings parade kicks off this week.</description>+ <guid isPermaLink="false">5b7d9dec-d185-4b1f-857c-54c032099c97</guid>+ <link>https://finance.yahoo.com/markets/live/earnings-live-updates-all-eyes-on-musk-and-meta-as-q3-earnings-roll-on-134152191.html?.tsrc=rss</link>+ <pubDate>Mon, 19 Oct 2026 13:41:52 +0000</pubDate>+ <title>Earnings live updates: All eyes on Musk and Meta as Q3 earnings rev up</title>+ </item>+ <item>+ <description>Yahoo Finance's Innes Fere takes a closer look at the top stories for investors to watch for the week of Oct. 19, including Q3 earnings reports from Netflix (NFLX), SpaceX (SPCX), Meta (META), and Tesla (TSLA), alongside September pending home sales.</description>+ <guid isPermaLink="false">ec7ffb3e-c5e4-430d-8c7d-b912b5e89033</guid>+ <link>https://finance.yahoo.com/video/meta-musk-earnings-september-pending-120000067.html?.tsrc=rss</link>+ <pubDate>Mon, 19 Oct 2026 12:00:00 +0000</pubDate>+ <title>Meta and Musk earnings and September pending home sales: What to Watch</title>+ </item>+ <item>+ <description>Global regulators are tightening financial rules to improve transparency and curb risks, which puts more scrutiny on listed executives and traditional corporate structures. Founder led businesses can look appealing in this setting because the person who built the company is still heavily invested in its long term success. This article highlights three stocks run by their original leaders and explains why this ownership mindset can matter for your portfolio. The three stocks highlighted here...</description>+ <guid isPermaLink="false">9a4f968c-fae4-3f90-a231-177eb9a1a42b</guid>+ <link>https://finance.yahoo.com/markets/stocks/articles/3-founder-led-stocks-revenue-131121611.html?.tsrc=rss</link>+ <pubDate>Mon, 19 Oct 2026 13:11:21 +0000</pubDate>+ <title>3 Founder Led Stocks With Revenue Growth Up To 17%</title>+ </item>+ <item>+ <description>Could SpaceX wind up being the key factor in whether Tesla stock beats the market?</description>+ <guid isPermaLink="false">46b8b777-b7c9-3631-a2c3-ecad7fdd6d08</guid>+ <link>https://www.fool.com/investing/2026/10/19/tesla-stock-vs-the-sp-500-which-investment-wins-th/?.tsrc=rss</link>+ <pubDate>Mon, 19 Oct 2026 12:32:00 +0000</pubDate>+ <title>Tesla Stock vs. the S&P 500: Which Investment Wins Through 2030?</title>+ </item>+ <item>+ <description>RBC analyst Tom Narayan believes he knows what price a Tesla-SpaceX deal could get done at.</description>+ <guid isPermaLink="false">24874872-02fc-312d-ab0a-030d5dafda4f</guid>+ <link>https://finance.yahoo.com/m/24874872-02fc-312d-ab0a-030d5dafda4f/tesla-spacex-merger-mania.html?.tsrc=rss</link>+ <pubDate>Mon, 19 Oct 2026 12:04:00 +0000</pubDate>+ <title>Tesla-SpaceX Merger Mania Strikes Wall Street Ahead of Earnings</title>+ </item>+ <item>+ <description>Yahoo Finance Executive Editor Brian Sozzi gives his unfiltered take on his takeaways from a week by SpaceX (SPCX) and Tesla (TSLA) founder Elon Musk. A period in which the innovator introduced the world's first flying car and announced a SpaceX stock giveaway for every child in America.</description>+ <guid isPermaLink="false">1c3f1fe6-3e5c-45cf-beed-747b6eb1d7d3</guid>+ <link>https://finance.yahoo.com/video/flying-teslas-and-spacex-stock-giveaways-whats-elon-musk-up-to-143207771.html?.tsrc=rss</link>+ <pubDate>Mon, 19 Oct 2026 14:32:07 +0000</pubDate>+ <title>Flying Teslas and SpaceX stock giveaways: What's Elon Musk up to?</title>+ </item>+ <item>+ <description>Elon Musk pledged to give a share of his SpaceX stock to "every kid in America." SpaceX stock is up about 1% on Monday.</description>+ <guid isPermaLink="false">09846e36-2ac5-354a-ba60-fe373a5d1095</guid>+ <link>https://finance.yahoo.com/m/09846e36-2ac5-354a-ba60-fe373a5d1095/spacex-stock-climbs-after.html?.tsrc=rss</link>+ <pubDate>Mon, 19 Oct 2026 12:59:24 +0000</pubDate>+ <title>SpaceX Stock Climbs After Musk Gift Pledge; Analysts Predict Tesla Merger Price</title>+ </item>+ <item>+ <description>Get ready for a SpaceX EPS.</description>+ <guid isPermaLink="false">477b6e3c-fce4-4271-adca-112e822adc53</guid>+ <link>https://finance.yahoo.com/technology/article/spacex-surprises-wall-street-with-oct-20-earnings-date--heres-why-123059651.html?.tsrc=rss</link>+ <pubDate>Mon, 19 Oct 2026 12:30:59 +0000</pubDate>+ <title>SpaceX surprises Wall Street with Oct. 20 earnings date — here's why</title>+ </item>+ <item>+ <description>The proposed distribution could potentially cover around 70 million Americans under 18.</description>+ <guid isPermaLink="false">7a9db891-46da-3a32-a01a-150aca182723</guid>+ <link>https://stocktwits.com/news-articles/markets/equity/elon-musk-give-one-spcx-share-to-every-us-child-next-year/cZx8VCIRBMN?.tsrc=rss</link>+ <pubDate>Mon, 19 Oct 2026 12:03:56 +0000</pubDate>+ <title>Elon Musk Says He Will Give One SPCX Share To Every US Child Next Year – ‘Will Be First Of Many’</title>+ </item>+ <item>+ <description>Investing.com -- Melius Research says Apple’s run to a $5 trillion market value has been the “most disliked rally in history,” but it believes the gains can continue.</description>+ <guid isPermaLink="false">735e4d95-09d4-3bbb-97c6-a900750bfbaf</guid>+ <link>https://finance.yahoo.com/markets/stocks/articles/apple-stock-staged-rally-5t-135117599.html?.tsrc=rss</link>+ <pubDate>Mon, 19 Oct 2026 13:51:17 +0000</pubDate>+ <title>Apple stock staged a rally to $5T "that no one liked": Melius</title>+ </item>+ <item>+ <description>Global regulators are tightening financial rules to curb risk and improve transparency, which puts extra scrutiny on complex corporate structures and short term leadership incentives. Founder run businesses often look different. Their bosses usually hold large personal stakes and think in decades, not quarters. This article explains why that long term mindset can matter for a portfolio, then highlights three founder led stocks from the screener that may warrant a closer look. The three stocks...</description>+ <guid isPermaLink="false">2ac4c174-2d19-3dba-aaef-93fbe3c0ed98</guid>+ <link>https://finance.yahoo.com/markets/stocks/articles/newcleo-2-founder-led-stocks-131315064.html?.tsrc=rss</link>+ <pubDate>Mon, 19 Oct 2026 13:13:15 +0000</pubDate>+ <title>newcleo And 2 Founder Led Stocks To Watch</title>+ </item>+ <item>+ <description>(Updates with economic data, recent oil price movement, world markets' overview and corporate stock</description>+ <guid isPermaLink="false">f389ca09-762c-330a-8b42-8e5db3f0bc8e</guid>+ <link>https://finance.yahoo.com/markets/stocks/articles/tech-stock-rebound-nudges-us-130104078.html?.tsrc=rss</link>+ <pubDate>Mon, 19 Oct 2026 13:01:04 +0000</pubDate>+ <title>Update: Tech Stock Rebound Nudges US Equity Futures Mostly Higher Pre-Bell</title>+ </item>+ <item>+ <description>The most concerning figure for a Ford Motor (F) holder is the loss at model e. Management noted on the July 28 call that model e lost $919 million before interest and taxes in fiscal Q2 2026. This loss occurred on revenue of $1 billion, meaning the segment lost nearly as much money as it brought in. Is that loss getting smaller, and how big is it next to what the rest of Ford earns.</description>+ <guid isPermaLink="false">1a762489-423c-3c40-b9d3-8eca0e3d15aa</guid>+ <link>https://www.trefis.com/articles/619182/what-could-go-wrong-with-ford-stock/2026-10-19?.tsrc=rss</link>+ <pubDate>Mon, 19 Oct 2026 12:55:52 +0000</pubDate>+ <title>What Could Go Wrong With Ford Stock?</title>+ </item>+ <item>+ <description>News of the day for Oct. 19, 2026</description>+ <guid isPermaLink="false">c7347a41-1f5b-3cd2-9610-3073b412a4ec</guid>+ <link>https://www.investopedia.com/5-things-to-know-before-the-stock-market-opens-on-monday-octoebr-19-2026-12181590?.tsrc=rss</link>+ <pubDate>Mon, 19 Oct 2026 12:30:12 +0000</pubDate>+ <title>5 Things to Know Before the Stock Market Opens on Monday</title>+ </item>+ <item>+ <description>Is the artificial-intelligence bloodbath finally over, or will a slew of Big Tech earnings reports only make things worse?</description>+ <guid isPermaLink="false">3b07bca3-439e-3ef6-ae1d-fa40534bbbc5</guid>+ <link>https://finance.yahoo.com/m/3b07bca3-439e-3ef6-ae1d-fa40534bbbc5/stock-futures-rebound-as-tech.html?.tsrc=rss</link>+ <pubDate>Mon, 19 Oct 2026 12:15:36 +0000</pubDate>+ <title>Stock Futures Rebound as Tech Claws Back Losses</title>+ </item>+ <item>+ <description>US equity futures were edging mostly higher pre-bell Monday as traders observed technology-related s</description>+ <guid isPermaLink="false">b0d7244b-3f15-3704-a6b5-b7c06531be2d</guid>+ <link>https://finance.yahoo.com/markets/stocks/articles/tech-stock-rebound-nudges-us-120243477.html?.tsrc=rss</link>+ <pubDate>Mon, 19 Oct 2026 12:02:43 +0000</pubDate>+ <title>Tech Stock Rebound Nudges US Equity Futures Mostly Higher Pre-Bell</title>+ </item>+ <language>en-US</language>+ <lastBuildDate>Mon, 19 Oct 2026 14:52:40 +0000</lastBuildDate>+ <link>http://finance.yahoo.com/q/h?s=TSLA</link>+ <title>Yahoo! Finance: TSLA News</title>+ </channel>+</rss>diff --git a/tests/fixtures/trader-pelosi/2026FD.zip b/tests/fixtures/trader-pelosi/2026FD.zipnew file mode 100644index 0000000..0253004Binary files /dev/null and b/tests/fixtures/trader-pelosi/2026FD.zip differdiff --git a/tests/fixtures/trader-pelosi/ptr-20033725-excerpt.txt b/tests/fixtures/trader-pelosi/ptr-20033725-excerpt.txtnew file mode 100644index 0000000..6445ded--- /dev/null+++ b/tests/fixtures/trader-pelosi/ptr-20033725-excerpt.txt@@ -0,0 +1,58 @@+ Filing ID #20033725++ P T R+ Clerk of the House of Representatives • Legislative Resource Center • B81 Cannon Building • Washington, DC 20515+++F I+Name: Hon. Nancy Pelosi+Status: Member+State/District: CA11+++T+ID Owner Asset Transaction Date Notification Amount Cap.+ Type Date Gains >+ $200?++ SP NVIDIA Corporation - Common Stock P 01/16/2026 01/16/2026 $250,001 -+ (NVDA) [ST] $500,000+ F S : New+ D : Exercised 50 call options purchased 1/14/25 (5,000 shares) at a strike price of $80 with an expiration date of+ 1/16/26.+++ SP PayPal Holdings, Inc. - Common S 12/30/2025 12/30/2025 $250,001 -+ Stock (PYPL) [ST] $500,000+ F S : New+ D : Sold 5,000 shares.+++ SP Tempus AI, Inc. - Class A Common P 01/16/2026 01/16/2026 $50,001 -+ID Owner Asset Transaction Date Notification Amount Cap.+ Type Date Gains >+ $200?+ Stock (TEM) [ST] $100,000+ F S : New+ D : Exercised 50 call options purchased 1/14/25 (5,000 shares) at a strike price of $20 with an expiration date of+ 1/16/26.+++ SP Versant Media Group, Inc. - Class A E 01/02/2026 01/02/2026 $15.00+ Common Stock (VSNT) [ST]+ F S : New+ D : 776 shares and cash in lieu received as a result of spinoff from Comcast Corporation. No shares of Comcast+ were surrendered as a result of the spinoff.+++ SP Vistra Corp. Common Stock (VST) P 01/16/2026 01/16/2026 $100,001 -+ [ST] $250,000+ F S : New+ D : Exercised 50 call options purchased 1/14/25 (5,000 shares) at a strike price of $50 with an expiration date of+ 1/16/26.+++* For the complete list of asset type abbreviations, please visit https://fd.house.gov/reference/asset-type-codes.aspx.+++Digitally Signed: Hon. Nancy Pelosi , 01/23/2026diff --git a/tests/fixtures/trader-pelosi/ptr-20035143.txt b/tests/fixtures/trader-pelosi/ptr-20035143.txtnew file mode 100644index 0000000..9ed468b--- /dev/null+++ b/tests/fixtures/trader-pelosi/ptr-20035143.txt@@ -0,0 +1,73 @@+ Filing ID #20035143++ P T R+ Clerk of the House of Representatives • Legislative Resource Center • B81 Cannon Building • Washington, DC 20515+++F I+Name: Hon. Nancy Pelosi+Status: Member+State/District: CA11+++T+ID Owner Asset Transaction Date Notification Amount Cap.+ Type Date Gains >+ $200?++ SP Bloom Energy Corporation Class A P 07/24/2026 07/24/2026 $1,000,001 -+ Common Stock (BE) [ST] $5,000,000+ F S : New+ D : Purchased 10,000 shares.+++ SP Bloom Energy Corporation Class A P 07/24/2026 07/24/2026 $1,000,001 -+ Common Stock (BE) [OP] $5,000,000+ F S : New+ D : Purchased 100 call options with a strike price of $100 and an expiration date of 6/17/27.+++ SP Bloom Energy Corporation Class A P 07/28/2026 07/28/2026 $500,001 -+ Common Stock (BE) [ST] $1,000,000+ F S : New+ D : Purchased 5,000 shares.+++ SP Bloom Energy Corporation Class A P 07/28/2026 07/28/2026 $500,001 -+ Common Stock (BE) [OP] $1,000,000+ F S : New+ D : Purchased 100 call options with a strike price of $100 and an expiration date of 6/17/27.+++ SP Intel Corporation - Common Stock P 07/24/2026 07/24/2026 $250,001 -+ (INTC) [OP] $500,000+ F S : New+ D : Purchased 50 call options with a strike price of $50 and an expiration date of 6/17/27.+++ SP Intel Corporation - Common Stock P 07/24/2026 07/24/2026 $500,001 -+ (INTC) [ST] $1,000,000+ F S : New+ D : Purchased 10,000 shares.+ID Owner Asset Transaction Date Notification Amount Cap.+ Type Date Gains >+ $200?++ SP REOF XXV, LLC [AB] P 07/27/2026 07/27/2026 $500,001 -+ $1,000,000+ F S : New+ D : Additional investment in LLC which is acquiring and restoring a luxury hotel property in San Francisco, CA.++* For the complete list of asset type abbreviations, please visit https://fd.house.gov/reference/asset-type-codes.aspx.+++I P O+ Yes No+++C S+ I CERTIFY that the statements I have made on the attached Periodic Transaction Report are true, complete, and correct to the best of+my knowledge and belief. Further, I CERTIFY that I have disclosed all transactions as required by the STOCK Act.++Digitally Signed: Hon. Nancy Pelosi , 08/21/2026+\ No newline at end of filediff --git a/tests/fixtures/trader-pelosi/ptr-20035562-excerpt.txt b/tests/fixtures/trader-pelosi/ptr-20035562-excerpt.txtnew file mode 100644index 0000000..749f688--- /dev/null+++ b/tests/fixtures/trader-pelosi/ptr-20035562-excerpt.txt@@ -0,0 +1,85 @@+ Filing ID #20035562++ P T R+ Clerk of the House of Representatives • Legislative Resource Center • B81 Cannon Building • Washington, DC 20515+++F I+Name: Hon. Maria Elvira Salazar+Status: Member+State/District: FL27+++T+ID Owner Asset Transaction Date Notification Amount Cap.+ Type Date Gains >+ $200?++ Berkshire Hathaway Inc. New S (partial) 09/24/2026 10/01/2026 $1,001 - $15,000+ Common Stock (BRK.B) [ST]+ F S : New+ S O : UBS IRA Account+++ Biogen Inc. - Common Stock (BIIB) S (partial) 09/24/2026 10/01/2026 $1,001 - $15,000+ [ST]+ F S : New+ S O : UBS IRA Account+++ Boeing Company (BA) [ST] S (partial) 09/24/2026 10/01/2026 $1,001 - $15,000++ F S : New+ S O : UBS IRA Account+++ Brookfield Renewable Partners L.P. S 09/24/2026 10/01/2026 $1,001 - $15,000+ Limited Partnership Units (BEP) [ST]+ F S : New+ S O : UBS IRA Account+++ Chevron Corporation Common Stock P 09/02/2026 10/01/2026 $1,001 - $15,000+ (CVX) [ST]+ F S : New+ S O : UBS Brokerage Account+++ Chubb Limited Common Stock (CB) S (partial) 09/24/2026 10/01/2026 $1,001 - $15,000+ [ST]+ F S : New+ S O : UBS IRA Account+ Corning Incorporated Common Stock P 09/08/2026 10/01/2026 $1,001 - $15,000+ (GLW) [ST]+ F S : New+ S O : UBS IRA Account+++ International Business Machines S 09/04/2026 10/01/2026 $1,001 - $15,000+ Corporation Common Stock (IBM)+ [ST]+ F S : New+ S O : UBS IRA Account+++* For the complete list of asset type abbreviations, please visit https://fd.house.gov/reference/asset-type-codes.aspx.+++I V D++ UBS Brokerage Account++ UBS IRA Account++++I P O+ Yes No+++C S+ I CERTIFY that the statements I have made on the attached Periodic Transaction Report are true, complete, and correct to the best of+my knowledge and belief. Further, I CERTIFY that I have disclosed all transactions as required by the STOCK Act.++Digitally Signed: Hon. Maria Elvira Salazar , 10/07/2026+\ No newline at end of filediff --git a/tests/fixtures/trader-pelosi/ptr-20035590.txt b/tests/fixtures/trader-pelosi/ptr-20035590.txtnew file mode 100644index 0000000..b103836--- /dev/null+++ b/tests/fixtures/trader-pelosi/ptr-20035590.txt@@ -0,0 +1,48 @@+ Filing ID #20035590++ P T R+ Clerk of the House of Representatives • Legislative Resource Center • B81 Cannon Building • Washington, DC 20515+++F I+Name: Hon. Josh Gottheimer+Status: Member+State/District: NJ05+++T+ID Owner Asset Transaction Date Notification Amount Cap.+ Type Date Gains >+ $200?++ JT Applied Materials, Inc. - Common S 09/15/2026 10/06/2026 $1,001 - $15,000+ Stock (AMAT) [ST]+ F S : New+ S O : Morgan Stanley - Select UMA Account # 1+++ JT McDonald's Corporation Common S (partial) 09/25/2026 10/06/2026 $1,001 - $15,000+ Stock (MCD) [ST]+ F S : New+ S O : Morgan Stanley - Select UMA Account # 1++* For the complete list of asset type abbreviations, please visit https://fd.house.gov/reference/asset-type-codes.aspx.+++I V D++ Morgan Stanley - Select UMA Account # 1 (Owner: JT)+ L : US++++I P O+ Yes No+++C S+ I CERTIFY that the statements I have made on the attached Periodic Transaction Report are true, complete, and correct to the best of+my knowledge and belief. Further, I CERTIFY that I have disclosed all transactions as required by the STOCK Act.++Digitally Signed: Hon. Josh Gottheimer , 10/07/2026+\ No newline at end of filediff --git a/tests/fixtures/trader-risk/orders-reel.json b/tests/fixtures/trader-risk/orders-reel.jsonnew file mode 100644index 0000000..1e69658--- /dev/null+++ b/tests/fixtures/trader-risk/orders-reel.json@@ -0,0 +1,41 @@+{+ "created_by": "trader-budget",+ "status": "proposed",+ "orders": [+ {+ "symbol": "AAPL",+ "side": "buy",+ "notional": "1250",+ "type": "market",+ "time_in_force": "day"+ },+ {+ "symbol": "AXP",+ "side": "buy",+ "notional": "1119",+ "type": "market",+ "time_in_force": "day"+ },+ {+ "symbol": "GOOGL",+ "side": "buy",+ "notional": "823",+ "type": "market",+ "time_in_force": "day"+ },+ {+ "symbol": "KO",+ "side": "buy",+ "notional": "708",+ "type": "market",+ "time_in_force": "day"+ },+ {+ "symbol": "BAC",+ "side": "buy",+ "notional": "600",+ "type": "market",+ "time_in_force": "day"+ }+ ]+}diff --git a/tests/fixtures/trader-risk/orders-tsla.json b/tests/fixtures/trader-risk/orders-tsla.jsonnew file mode 100644index 0000000..2e6bfbb--- /dev/null+++ b/tests/fixtures/trader-risk/orders-tsla.json@@ -0,0 +1,31 @@+{+ "created_by": "trader-budget",+ "created_at": "2026-10-19T14:15:00Z",+ "status": "proposed",+ "paper": true,+ "note": "Proposals only. Nothing is placed until trader-risk passes each order and you say yes to it in the chat.",+ "source": "trader/plan.json (TSLA orb 2026-10-19)",+ "orders": [+ {+ "symbol": "TSLA",+ "side": "buy",+ "qty": "8",+ "type": "market",+ "time_in_force": "day",+ "order_class": "bracket",+ "take_profit_limit_price": "370.04",+ "stop_loss_stop_price": "358.32",+ "why": "opening-range breakout on TSLA: 8 shares, bound by your $50 max loss per trade (8 x 5.86 = $46.88 at the stop)",+ "plan": {+ "entry": 364.18,+ "stop": 358.32,+ "target": 370.04,+ "risk_per_share": 5.86,+ "max_loss": 46.88,+ "setup": "orb",+ "entry_time": "10:15 AM",+ "flat_by": "15:55"+ }+ }+ ]+}diff --git a/tests/fixtures/trader-scanner/TSLA-5m-live-2026-10-20-1001.json b/tests/fixtures/trader-scanner/TSLA-5m-live-2026-10-20-1001.jsonnew file mode 100644index 0000000..6e654f3--- /dev/null+++ b/tests/fixtures/trader-scanner/TSLA-5m-live-2026-10-20-1001.json@@ -0,0 +1 @@+{"chart":{"result":[{"meta":{"currency":"USD","symbol":"TSLA","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":1277818200,"regularMarketTime":1792504907,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":371.615,"regularMarketChangePercent":0.966,"fulldayPrice":371.615,"fulldayChange":3.555,"fulldayChangePercent":0.966,"fiftyTwoWeekHigh":498.83,"fiftyTwoWeekLow":297.38,"regularMarketDayHigh":371.84,"regularMarketDayLow":363.64,"regularMarketVolume":6193620,"longName":"Tesla, Inc.","shortName":"Tesla, Inc.","chartPreviousClose":368.06,"previousClose":368.06,"scale":3,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"tradingPeriods":[[{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400}]],"dataGranularity":"5m","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1792503000,1792503300,1792503600,1792503900,1792504200,1792504500,1792504800,1792504907],"indicators":{"quote":[{"low":[363.6400146484375,365.8599853515625,364.70001220703125,365.2699890136719,367.11358642578125,368.0,370.1099853515625,371.614990234375],"open":[370.3479919433594,367.2107849121094,366.2099914550781,366.2300109863281,367.3299865722656,368.4599914550781,370.61199951171875,371.614990234375],"high":[370.489990234375,367.75,366.67999267578125,367.4800109863281,368.84991455078125,370.7250061035156,370.8800048828125,371.614990234375],"close":[367.3479919433594,366.2699890136719,366.17999267578125,367.3382873535156,368.3599853515625,370.5849914550781,370.8652038574219,371.614990234375],"volume":[2507242,736505,691998,4623726,710581,636675,182618,0]}]}}],"error":null}}\ No newline at end of filediff --git a/tests/fixtures/trader-scanner/daily-spark-2026-10-19.json b/tests/fixtures/trader-scanner/daily-spark-2026-10-19.jsonnew file mode 100644index 0000000..51703e2--- /dev/null+++ b/tests/fixtures/trader-scanner/daily-spark-2026-10-19.json@@ -0,0 +1 @@+{"spark":{"result":[{"symbol":"BLK","response":[{"meta":{"currency":"USD","symbol":"BLK","exchangeName":"NYQ","instrumentType":"EQUITY","regularMarketTime":1792421490,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":1121.54,"regularMarketVolume":106202,"regularMarketDayHigh":1141.39,"regularMarketDayLow":1121.54,"chartPreviousClose":1072.2,"dataGranularity":"1d","range":"3mo"},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[1054.1099853515625,1038.239990234375,1056.6300048828125,1037.1600341796875,1055.6700439453125,1062.1400146484375,1097.550048828125,1079.18994140625,1098.3699951171875,1090.3900146484375,1126.6300048828125,1131.1300048828125,1133.5799560546875,1129.300048828125,1136.3900146484375,1131.4000244140625,1148.8399658203125,1160.9100341796875,1182.8399658203125,1173.72998046875,1147.1099853515625,1154.3499755859375,1158.9200439453125,1139.8199462890625,1156.550048828125,1172.6099853515625,1176.6400146484375,1173.2099609375,1167.5699462890625,1164.47998046875,1155.6099853515625,1128.0999755859375,1107.0799560546875,1126.1500244140625,1122.2900390625,1095.3699951171875,1072.030029296875,1062.4000244140625,1079.6500244140625,1065.5999755859375,1058.6600341796875,1037.239990234375,1053.9599609375,1069.780029296875,1090.27001953125,1066.6600341796875,1060.8900146484375,1073.449951171875,1086.31005859375,1071.25,1067.93994140625,1058.2900390625,1064.3599853515625,1059.6300048828125,1066.449951171875,1079.4200439453125,1069.6300048828125,1065.3499755859375,1082.3900146484375,1083.9200439453125,1066.1199951171875,1073.7900390625,1120.780029296875,1134.3800048828125,1121.5400390625]}]}}]},{"symbol":"CI","response":[{"meta":{"currency":"USD","symbol":"CI","exchangeName":"NYQ","instrumentType":"EQUITY","regularMarketTime":1792421529,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":297.825,"regularMarketVolume":165951,"regularMarketDayHigh":302.135,"regularMarketDayLow":297.665,"chartPreviousClose":281.45,"dataGranularity":"1d","range":"3mo"},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[283.94000244140625,290.489990234375,284.8500061035156,286.2900085449219,289.57000732421875,291.0199890136719,301.05999755859375,296.4700012207031,287.6600036621094,279.04998779296875,282.05999755859375,274.04998779296875,270.5,275.25,282.489990234375,278.3999938964844,273.8699951171875,277.4100036621094,277.989990234375,282.55999755859375,275.3299865722656,278.5,277.45001220703125,274.4100036621094,277.510009765625,280.45001220703125,279.32000732421875,280.8699951171875,277.6700134277344,278.8800048828125,276.0799865722656,283.05999755859375,282.8399963378906,286.260009765625,282.5199890136719,275.8299865722656,278.1700134277344,280.9100036621094,280.760009765625,290.04998779296875,288.8999938964844,280.45001220703125,276.0,275.2799987792969,274.4700012207031,273.739990234375,268.2699890136719,265.5,272.010009765625,271.8299865722656,275.260009765625,271.8299865722656,267.9599914550781,270.5299987792969,271.2900085449219,274.3699951171875,278.510009765625,281.0299987792969,282.42999267578125,283.3399963378906,282.5299987792969,289.5799865722656,298.80999755859375,302.29998779296875,297.82501220703125]}]}}]},{"symbol":"XOM","response":[{"meta":{"currency":"USD","symbol":"XOM","exchangeName":"NYQ","instrumentType":"EQUITY","regularMarketTime":1792421403,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":177.595,"regularMarketVolume":2279958,"regularMarketDayHigh":179.3,"regularMarketDayLow":177.234,"chartPreviousClose":147.36,"dataGranularity":"1d","range":"3mo"},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[148.36000061035156,151.7100067138672,154.4499969482422,156.88999938964844,156.94000244140625,154.77000427246094,153.0399932861328,156.75,156.97000122070312,155.44000244140625,155.05999755859375,153.9600067138672,151.6300048828125,154.83999633789062,153.0399932861328,159.7899932861328,159.8000030517578,159.75,158.61000061035156,160.10000610351562,161.4600067138672,165.55999755859375,164.77000427246094,166.14999389648438,165.11000061035156,164.0500030517578,160.63999938964844,158.19000244140625,156.44000244140625,156.7100067138672,160.9499969482422,164.5500030517578,164.14999389648438,162.2100067138672,159.47000122070312,160.66000366210938,164.22999572753906,165.22999572753906,165.99000549316406,165.0800018310547,169.32000732421875,163.32000732421875,163.27000427246094,163.5399932861328,158.3000030517578,158.7100067138672,161.22999572753906,162.13999938964844,160.58999633789062,162.52000427246094,161.35000610351562,162.75,163.82000732421875,164.00999450683594,164.0,164.47999572753906,164.0500030517578,168.5,168.94000244140625,172.14999389648438,174.0800018310547,177.00999450683594,174.67999267578125,178.97999572753906,177.59500122070312]}]}}]},{"symbol":"HD","response":[{"meta":{"currency":"USD","symbol":"HD","exchangeName":"NYQ","instrumentType":"EQUITY","regularMarketTime":1792421408,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":308.21,"regularMarketVolume":599552,"regularMarketDayHigh":308.265,"regularMarketDayLow":306.056,"chartPreviousClose":338.87,"dataGranularity":"1d","range":"3mo"},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[333.0400085449219,331.6000061035156,331.45001220703125,324.7099914550781,332.9800109863281,336.0899963378906,344.4700012207031,338.2699890136719,333.3500061035156,331.9599914550781,340.0199890136719,348.239990234375,353.1400146484375,349.5199890136719,355.6199951171875,350.7799987792969,354.4800109863281,343.42999267578125,341.70001220703125,338.8599853515625,337.8800048828125,337.489990234375,344.29998779296875,334.489990234375,335.6099853515625,337.42999267578125,337.8800048828125,334.8500061035156,328.6099853515625,330.19000244140625,327.8299865722656,319.7699890136719,318.510009765625,318.07000732421875,321.04998779296875,313.70001220703125,310.45001220703125,305.69000244140625,308.739990234375,310.8699951171875,305.4800109863281,302.4700012207031,302.510009765625,299.9800109863281,297.20001220703125,305.3500061035156,296.7200012207031,292.17999267578125,293.20001220703125,289.8900146484375,288.0400085449219,284.489990234375,282.4599914550781,282.8500061035156,281.1499938964844,286.69000244140625,285.7699890136719,295.4700012207031,290.739990234375,290.6199951171875,293.9200134277344,295.510009765625,308.239990234375,309.6300048828125,308.2099914550781]}]}}]},{"symbol":"KO","response":[{"meta":{"currency":"USD","symbol":"KO","exchangeName":"NYQ","instrumentType":"EQUITY","regularMarketTime":1792421409,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":93.83,"regularMarketVolume":3680307,"regularMarketDayHigh":93.99,"regularMarketDayLow":92.622,"chartPreviousClose":81.56,"dataGranularity":"1d","range":"3mo"},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[82.12000274658203,81.97000122070312,82.19999694824219,81.16999816894531,82.25,84.06999969482422,88.2699966430664,89.08000183105469,88.48999786376953,87.58999633789062,86.86000061035156,86.55999755859375,86.83000183105469,86.8499984741211,87.05000305175781,86.87000274658203,86.4800033569336,86.70999908447266,87.41999816894531,87.70999908447266,86.9800033569336,88.81999969482422,90.3499984741211,90.5,91.0999984741211,91.98999786376953,91.63999938964844,90.08000183105469,89.05999755859375,89.66000366210938,88.66999816894531,88.0,88.23999786376953,88.80999755859375,88.06999969482422,88.36000061035156,87.55000305175781,87.83000183105469,88.29000091552734,89.3499984741211,88.70999908447266,87.87000274658203,88.05999755859375,88.25,87.12000274658203,88.61000061035156,88.08999633789062,88.0999984741211,87.80999755859375,87.18000030517578,86.83999633789062,86.08000183105469,86.0999984741211,85.6500015258789,86.51000213623047,86.16999816894531,85.81999969482422,87.7699966430664,88.05000305175781,89.79000091552734,90.11000061035156,91.77999877929688,92.0,93.9000015258789,93.83000183105469]}]}}]},{"symbol":"CCL","response":[{"meta":{"currency":"USD","symbol":"CCL","exchangeName":"NYQ","instrumentType":"EQUITY","regularMarketTime":1792421491,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":26.115,"regularMarketVolume":3329022,"regularMarketDayHigh":26.26,"regularMarketDayLow":25.76,"chartPreviousClose":26.41,"dataGranularity":"1d","range":"3mo"},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[26.040000915527344,26.15999984741211,26.100000381469727,25.270000457763672,26.329999923706055,27.1200008392334,28.229999542236328,27.809999465942383,27.770000457763672,27.809999465942383,28.739999771118164,29.59000015258789,29.670000076293945,28.790000915527344,28.989999771118164,27.75,27.729999542236328,27.670000076293945,28.420000076293945,28.1200008392334,27.729999542236328,27.270000457763672,26.690000534057617,25.3700008392334,25.729999542236328,25.709999084472656,26.139999389648438,25.59000015258789,24.950000762939453,24.760000228881836,23.889999389648438,23.229999542236328,23.739999771118164,23.479999542236328,23.510000228881836,23.200000762939453,22.700000762939453,22.469999313354492,22.75,22.559999465942383,22.110000610351562,22.350000381469727,22.170000076293945,21.84000015258789,22.309999465942383,22.280000686645508,21.799999237060547,21.790000915527344,22.25,22.139999389648438,25.110000610351562,24.540000915527344,25.06999969482422,25.760000228881836,25.559999465942383,26.579999923706055,26.149999618530273,26.1299991607666,26.350000381469727,26.479999542236328,26.729999542236328,25.969999313354492,26.459999084472656,25.899999618530273,26.114999771118164]}]}}]},{"symbol":"RCL","response":[{"meta":{"currency":"USD","symbol":"RCL","exchangeName":"NYQ","instrumentType":"EQUITY","regularMarketTime":1792421486,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":278.335,"regularMarketVolume":349431,"regularMarketDayHigh":282.12,"regularMarketDayLow":275.78,"chartPreviousClose":286.96,"dataGranularity":"1d","range":"3mo"},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[286.1600036621094,287.8999938964844,285.8500061035156,283.4100036621094,293.5400085449219,305.0400085449219,322.5,323.5799865722656,321.94000244140625,318.29998779296875,324.0,325.739990234375,327.4200134277344,320.54998779296875,320.0,308.0,307.1499938964844,308.0,309.8800048828125,305.0,301.7900085449219,300.0,300.55999755859375,287.6199951171875,292.0,293.0,292.2900085449219,290.0,284.79998779296875,279.4100036621094,268.739990234375,265.70001220703125,265.6000061035156,265.54998779296875,265.19000244140625,264.5,259.760009765625,259.010009765625,260.1400146484375,255.33999633789062,249.3000030517578,253.9199981689453,249.74000549316406,245.80999755859375,250.25,234.88999938964844,230.3000030517578,238.97999572753906,242.6999969482422,242.58999633789062,260.6700134277344,265.8599853515625,269.989990234375,277.739990234375,275.0299987792969,288.7799987792969,282.32000732421875,281.4100036621094,282.260009765625,280.6700134277344,281.510009765625,274.30999755859375,280.010009765625,277.67999267578125,278.3349914550781]}]}}]},{"symbol":"F","response":[{"meta":{"currency":"USD","symbol":"F","exchangeName":"NYQ","instrumentType":"EQUITY","regularMarketTime":1792421472,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":12.325,"regularMarketVolume":4834984,"regularMarketDayHigh":12.43,"regularMarketDayLow":12.31,"chartPreviousClose":14.23,"dataGranularity":"1d","range":"3mo"},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[13.989999771118164,14.270000457763672,14.420000076293945,14.149999618530273,14.369999885559082,14.680000305175781,14.960000038146973,15.279999732971191,14.859999656677246,14.680000305175781,14.430000305175781,14.239999771118164,14.130000114440918,13.789999961853027,13.979999542236328,14.0,13.979999542236328,13.829999923706055,13.890000343322754,14.369999885559082,14.050000190734863,13.930000305175781,14.5,13.989999771118164,14.40999984741211,13.930000305175781,13.949999809265137,13.899999618530273,13.949999809265137,13.880000114440918,13.9399995803833,13.84000015258789,14.140000343322754,14.40999984741211,14.619999885559082,14.0,13.449999809265137,13.880000114440918,13.970000267028809,13.859999656677246,13.5,13.350000381469727,13.609999656677246,13.210000038146973,13.170000076293945,13.100000381469727,12.9399995803833,12.600000381469727,12.710000038146973,12.380000114440918,12.300000190734863,12.0600004196167,12.270000457763672,12.100000381469727,12.149999618530273,12.279999732971191,12.119999885559082,12.25,12.170000076293945,12.0,12.100000381469727,12.050000190734863,12.3100004196167,12.430000305175781,12.324999809265137]}]}}]},{"symbol":"JPM","response":[{"meta":{"currency":"USD","symbol":"JPM","exchangeName":"NYQ","instrumentType":"EQUITY","regularMarketTime":1792421401,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":337.89,"regularMarketVolume":1182274,"regularMarketDayHigh":341.01,"regularMarketDayLow":336.62,"chartPreviousClose":341.1,"dataGranularity":"1d","range":"3mo"},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[338.8699951171875,345.2300109863281,348.2099914550781,349.8999938964844,353.2099914550781,356.20001220703125,357.30999755859375,344.7099914550781,350.8500061035156,351.7900085449219,352.6400146484375,357.5199890136719,359.239990234375,356.29998779296875,357.5199890136719,359.7900085449219,362.0400085449219,365.17999267578125,363.1099853515625,362.8399963378906,360.9599914550781,363.25,357.260009765625,351.54998779296875,351.5799865722656,356.3900146484375,356.69000244140625,356.5,354.2200012207031,357.6199951171875,356.0199890136719,354.95001220703125,356.2200012207031,362.05999755859375,358.6400146484375,353.510009765625,354.7099914550781,353.55999755859375,356.2300109863281,350.1300048828125,352.489990234375,348.9200134277344,349.30999755859375,349.6700134277344,352.0400085449219,340.0,337.5299987792969,338.55999755859375,343.05999755859375,336.5899963378906,334.9800109863281,330.8299865722656,333.17999267578125,332.3800048828125,332.3800048828125,331.2799987792969,329.5799865722656,331.4200134277344,332.989990234375,334.29998779296875,331.42999267578125,335.2799987792969,335.5299987792969,339.7200012207031,337.8900146484375]}]}}]},{"symbol":"GE","response":[{"meta":{"currency":"USD","symbol":"GE","exchangeName":"NYQ","instrumentType":"EQUITY","regularMarketTime":1792421475,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":311.445,"regularMarketVolume":846193,"regularMarketDayHigh":315.34,"regularMarketDayLow":310.64,"chartPreviousClose":348.83,"dataGranularity":"1d","range":"3mo"},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[341.29998779296875,340.70001220703125,341.19000244140625,349.0,353.7300109863281,361.6099853515625,363.5899963378906,350.6300048828125,355.0400085449219,360.07000732421875,368.92999267578125,377.2799987792969,381.2200012207031,374.54998779296875,370.0799865722656,366.70001220703125,368.05999755859375,365.3299865722656,360.6400146484375,368.3800048828125,369.42999267578125,375.0899963378906,356.2300109863281,344.6400146484375,348.3699951171875,341.8399963378906,349.5400085449219,354.3900146484375,342.7300109863281,342.5799865722656,335.7099914550781,331.0899963378906,329.5,333.4800109863281,337.1199951171875,334.9100036621094,325.4200134277344,324.1499938964844,323.6600036621094,317.55999755859375,307.04998779296875,312.8999938964844,313.4700012207031,314.2699890136719,319.010009765625,319.2200012207031,319.79998779296875,319.7799987792969,327.0899963378906,318.239990234375,317.8900146484375,312.2900085449219,312.3900146484375,309.55999755859375,306.3399963378906,309.3900146484375,303.6199951171875,305.6199951171875,308.20001220703125,308.6400146484375,307.6300048828125,307.0199890136719,312.0,313.8299865722656,311.44500732421875]}]}}]},{"symbol":"BAC","response":[{"meta":{"currency":"USD","symbol":"BAC","exchangeName":"NYQ","instrumentType":"EQUITY","regularMarketTime":1792421523,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":51.045,"regularMarketVolume":8531643,"regularMarketDayHigh":51.53,"regularMarketDayLow":51.015,"chartPreviousClose":61.27,"dataGranularity":"1d","range":"3mo"},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[60.41999816894531,61.220001220703125,61.619998931884766,61.279998779296875,62.04999923706055,62.130001068115234,62.619998931884766,61.06999969482422,61.72999954223633,61.95000076293945,62.47999954223633,62.900001525878906,63.25,63.0,63.16999816894531,63.86000061035156,64.0,64.80999755859375,64.08999633789062,64.48999786376953,63.88999938964844,64.2300033569336,63.16999816894531,61.86000061035156,61.689998626708984,62.33000183105469,62.43000030517578,62.22999954223633,61.16999816894531,62.31999969482422,61.939998626708984,61.9900016784668,62.599998474121094,63.040000915527344,62.68000030517578,62.38999938964844,62.66999816894531,62.560001373291016,62.689998626708984,59.470001220703125,59.52000045776367,57.900001525878906,58.18000030517578,57.72999954223633,57.959999084472656,56.20000076293945,56.0,56.029998779296875,56.70000076293945,55.470001220703125,54.959999084472656,54.43000030517578,53.72999954223633,53.75,54.0,54.09000015258789,53.52000045776367,53.61000061035156,54.31999969482422,54.58000183105469,53.959999084472656,51.38999938964844,51.70000076293945,51.22999954223633,51.04499816894531]}]}}]},{"symbol":"PLUG","response":[{"meta":{"currency":"USD","symbol":"PLUG","exchangeName":"NCM","instrumentType":"EQUITY","regularMarketTime":1792421566,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":1.405,"regularMarketVolume":13296693,"regularMarketDayHigh":1.44,"regularMarketDayLow":1.39,"chartPreviousClose":2.17,"dataGranularity":"1d","range":"3mo"},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[2.130000114440918,2.2699999809265137,2.2300000190734863,2.190000057220459,2.0899999141693115,2.059999942779541,1.9600000381469727,1.899999976158142,2.0899999141693115,2.059999942779541,2.0799999237060547,2.1600000858306885,2.0999999046325684,2.069999933242798,2.180000066757202,2.109999895095825,2.2200000286102295,2.2899999618530273,2.299999952316284,2.319999933242798,2.2799999713897705,2.1600000858306885,2.25,2.200000047683716,2.2699999809265137,2.1700000762939453,2.2699999809265137,2.1700000762939453,2.2699999809265137,2.190000057220459,2.1600000858306885,2.0899999141693115,2.0899999141693115,2.109999895095825,2.1700000762939453,2.259999990463257,2.1700000762939453,2.109999895095825,2.0999999046325684,2.059999942779541,2.049999952316284,2.0199999809265137,2.119999885559082,2.0899999141693115,2.0899999141693115,2.109999895095825,2.0399999618530273,1.9600000381469727,1.9800000190734863,1.8600000143051147,1.909999966621399,1.940000057220459,1.8899999856948853,1.899999976158142,1.8899999856948853,1.8600000143051147,1.7799999713897705,1.7300000190734863,1.6799999475479126,1.6200000047683716,1.559999942779541,1.4500000476837158,1.4900000095367432,1.3799999952316284,1.4049999713897705]}]}}]},{"symbol":"MS","response":[{"meta":{"currency":"USD","symbol":"MS","exchangeName":"NYQ","instrumentType":"EQUITY","regularMarketTime":1792421520,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":180.495,"regularMarketVolume":773787,"regularMarketDayHigh":182.22,"regularMarketDayLow":180.31,"chartPreviousClose":215.5,"dataGranularity":"1d","range":"3mo"},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[210.94000244140625,216.39999389648438,218.5,215.17999267578125,214.47999572753906,214.55999755859375,211.5800018310547,203.1300048828125,210.05999755859375,210.4199981689453,211.22999572753906,217.0399932861328,218.27000427246094,213.75,216.3300018310547,215.3300018310547,215.07000732421875,217.63999938964844,218.3800048828125,217.36000061035156,218.2100067138672,217.5500030517578,214.22999572753906,207.4499969482422,214.1999969482422,214.0800018310547,216.77000427246094,214.0800018310547,214.86000061035156,214.77000427246094,213.32000732421875,211.0399932861328,211.82000732421875,217.14999389648438,217.72000122070312,216.24000549316406,215.35000610351562,212.66000366210938,214.3800048828125,206.5800018310547,206.27999877929688,202.4199981689453,203.52000427246094,202.5800018310547,206.1199951171875,200.17999267578125,198.38999938964844,196.32000732421875,196.30999755859375,193.63999938964844,192.75999450683594,188.0800018310547,188.00999450683594,190.30999755859375,190.19000244140625,191.02000427246094,189.7100067138672,187.44000244140625,190.02000427246094,190.02000427246094,186.63999938964844,181.50999450683594,182.10000610351562,180.57000732421875,180.4949951171875]}]}}]},{"symbol":"RIVN","response":[{"meta":{"currency":"USD","symbol":"RIVN","exchangeName":"NMS","instrumentType":"EQUITY","regularMarketTime":1792421471,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":12.265,"regularMarketVolume":5955070,"regularMarketDayHigh":12.52,"regularMarketDayLow":12.16,"chartPreviousClose":17.455,"dataGranularity":"1d","range":"3mo"},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[17.239999771118164,17.760000228881836,17.18000030517578,16.459999084472656,15.84000015258789,16.479999542236328,16.690000534057617,16.329999923706055,16.829999923706055,15.220000267028809,15.354999542236328,15.760000228881836,15.5600004196167,15.380000114440918,16.0,16.389999389648438,16.360000610351562,15.930000305175781,15.819999694824219,15.359999656677246,14.869999885559082,14.779999732971191,15.729999542236328,16.010000228881836,16.969999313354492,16.600000381469727,16.739999771118164,16.329999923706055,16.799999237060547,16.06999969482422,16.059999465942383,15.53499984741211,15.609999656677246,15.90999984741211,15.739999771118164,16.170000076293945,16.0049991607666,16.049999237060547,16.030000686645508,15.859999656677246,15.539999961853027,15.229999542236328,15.399999618530273,14.989999771118164,15.359999656677246,15.140000343322754,15.020000457763672,15.289999961853027,15.470000267028809,14.789999961853027,14.970000267028809,14.9399995803833,14.760000228881836,14.300000190734863,14.600000381469727,14.510000228881836,14.34000015258789,14.329999923706055,13.960000038146973,13.539999961853027,13.369999885559082,12.949999809265137,13.020000457763672,12.420000076293945,12.265000343322754]}]}}]},{"symbol":"PNC","response":[{"meta":{"currency":"USD","symbol":"PNC","exchangeName":"NYQ","instrumentType":"EQUITY","regularMarketTime":1792421516,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":217.07,"regularMarketVolume":284603,"regularMarketDayHigh":218.37,"regularMarketDayLow":216.29,"chartPreviousClose":252.86,"dataGranularity":"1d","range":"3mo"},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[250.13999938964844,250.3800048828125,252.50999450683594,249.25999450683594,250.99000549316406,249.63999938964844,251.60000610351562,248.49000549316406,248.7100067138672,249.8699951171875,251.72000122070312,254.13999938964844,255.3699951171875,252.75999450683594,252.55999755859375,251.75999450683594,254.22999572753906,255.4600067138672,255.1999969482422,256.9700012207031,254.5500030517578,254.27999877929688,246.4600067138672,241.6199951171875,243.1300048828125,243.67999267578125,244.11000061035156,244.6699981689453,243.50999450683594,242.22000122070312,239.6300048828125,237.49000549316406,242.4600067138672,245.17999267578125,245.60000610351562,242.91000366210938,240.69000244140625,242.97999572753906,244.24000549316406,242.72000122070312,240.77999877929688,231.49000549316406,232.00999450683594,233.1699981689453,233.25,227.9600067138672,224.02999877929688,223.33999633789062,225.63999938964844,223.6699981689453,221.64999389648438,222.25999450683594,220.75,221.02999877929688,220.27999877929688,220.16000366210938,217.72000122070312,219.67999267578125,219.2100067138672,221.25999450683594,219.47999572753906,215.8000030517578,214.94000244140625,217.38999938964844,217.07000732421875]}]}}]},{"symbol":"TSLA","response":[{"meta":{"currency":"USD","symbol":"TSLA","exchangeName":"NMS","instrumentType":"EQUITY","regularMarketTime":1792421396,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":365.795,"regularMarketVolume":14800817,"regularMarketDayHigh":367.57,"regularMarketDayLow":354.47,"chartPreviousClose":380.84,"dataGranularity":"1d","range":"3mo"},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[369.57000732421875,378.92999267578125,374.010009765625,319.69000244140625,313.0299987792969,309.2200012207031,307.44000244140625,298.32000732421875,308.8500061035156,311.2099914550781,322.0799865722656,327.3500061035156,321.54998779296875,319.5299987792969,328.5799865722656,330.8800048828125,332.80999755859375,327.510009765625,339.9599914550781,342.2699890136719,339.29998779296875,336.8699951171875,351.1199951171875,345.1300048828125,362.8599853515625,348.95001220703125,350.25,345.82000732421875,354.80999755859375,348.75,367.95001220703125,356.0899963378906,357.010009765625,376.3699951171875,354.0799865722656,368.1600036621094,367.80999755859375,363.55999755859375,365.44000244140625,358.9700012207031,356.5799865722656,358.0799865722656,366.20001220703125,364.2699890136719,375.29998779296875,378.8999938964844,380.1199951171875,377.94000244140625,372.1099853515625,357.45001220703125,352.8399963378906,354.80999755859375,354.1099853515625,370.5899963378906,378.7300109863281,380.67999267578125,377.80999755859375,375.0,382.70001220703125,378.0299987792969,375.2300109863281,367.1600036621094,362.44000244140625,354.7200012207031,365.7950134277344]}]}}]},{"symbol":"NVDA","response":[{"meta":{"currency":"USD","symbol":"NVDA","exchangeName":"NMS","instrumentType":"EQUITY","regularMarketTime":1792421394,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":217.63,"regularMarketVolume":32396665,"regularMarketDayHigh":218.409,"regularMarketDayLow":214.7,"chartPreviousClose":202.81,"dataGranularity":"1d","range":"3mo"},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[203.27999877929688,207.2899932861328,212.05999755859375,208.75999450683594,206.83999633789062,196.50999450683594,197.00999450683594,190.00999450683594,195.0399932861328,200.75,206.63999938964844,211.94000244140625,219.22000122070312,218.99000549316406,223.9600067138672,217.5500030517578,217.5,224.08999633789062,225.3000030517578,225.16000366210938,225.00999450683594,219.74000549316406,217.55999755859375,216.85000610351562,214.72000122070312,208.47999572753906,213.0500030517578,209.66000366210938,227.97999572753906,217.5500030517578,220.77999877929688,217.44000244140625,224.41000366210938,228.4499969482422,230.36000061035156,225.72999572753906,223.6699981689453,218.36000061035156,218.2899932861328,210.9600067138672,212.1699981689453,213.89999389648438,219.33999633789062,222.27000427246094,227.3800048828125,228.8699951171875,225.50999450683594,224.5800018310547,225.07000732421875,228.86000061035156,227.2100067138672,228.3800048828125,230.86000061035156,233.9499969482422,238.89999389648438,239.24000549316406,237.47000122070312,230.47999572753906,229.27999877929688,226.32000732421875,228.52000427246094,221.3000030517578,217.22999572753906,214.1300048828125,217.62989807128906]}]}}]},{"symbol":"MSFT","response":[{"meta":{"currency":"USD","symbol":"MSFT","exchangeName":"NMS","instrumentType":"EQUITY","regularMarketTime":1792421391,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":534.788,"regularMarketVolume":4399888,"regularMarketDayHigh":534.788,"regularMarketDayLow":528.48,"chartPreviousClose":393.82,"dataGranularity":"1d","range":"3mo"},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[402.2900085449219,397.75,390.3399963378906,381.5799865722656,381.70001220703125,389.1000061035156,393.3500061035156,390.5400085449219,451.1000061035156,464.7200012207031,487.6499938964844,492.80999755859375,487.4599914550781,499.8599853515625,499.989990234375,506.05999755859375,503.80999755859375,492.42999267578125,496.8800048828125,495.3999938964844,480.3500061035156,481.6300048828125,484.30999755859375,481.1499938964844,483.239990234375,487.30999755859375,491.7099914550781,496.3699951171875,505.05999755859375,513.530029296875,507.2900085449219,501.0199890136719,496.82000732421875,510.1199951171875,499.70001220703125,493.95001220703125,491.6499938964844,492.44000244140625,495.6300048828125,505.4100036621094,497.1199951171875,490.29998779296875,497.75,493.7799987792969,501.6099853515625,498.0,500.5899963378906,497.92999267578125,516.1699829101562,509.2200012207031,508.9599914550781,512.9000244140625,512.7999877929688,517.530029296875,525.1799926757812,529.2999877929688,529.760009765625,522.6099853515625,535.0700073242188,541.1500244140625,543.4500122070312,533.6900024414062,539.4400024414062,529.0499877929688,534.7880249023438]}]}}]},{"symbol":"AMZN","response":[{"meta":{"currency":"USD","symbol":"AMZN","exchangeName":"NMS","instrumentType":"EQUITY","regularMarketTime":1792421391,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":260.79,"regularMarketVolume":15095309,"regularMarketDayHigh":261.2,"regularMarketDayLow":255.22,"chartPreviousClose":247.23,"dataGranularity":"1d","range":"3mo"},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[249.99000549316406,247.5500030517578,244.85000610351562,233.66000366210938,232.11000061035156,231.38999938964844,230.86000061035156,226.64999389648438,235.5,271.5799865722656,284.0199890136719,277.4200134277344,272.6499938964844,272.260009765625,274.4800109863281,278.0899963378906,272.2699890136719,267.2799987792969,265.1300048828125,262.6499938964844,261.30999755859375,259.45001220703125,265.8399963378906,260.1099853515625,258.6300048828125,262.07000732421875,261.05999755859375,260.2799987792969,256.260009765625,266.42999267578125,259.7699890136719,254.9199981689453,254.97999572753906,258.8999938964844,258.510009765625,256.9700012207031,252.39999389648438,251.88999938964844,256.7799987792969,253.5399932861328,248.4199981689453,245.9600067138672,251.19000244140625,253.7100067138672,258.45001220703125,254.97999572753906,249.27000427246094,249.3800048828125,249.6699981689453,246.14999389648438,246.6699981689453,249.14999389648438,248.22999572753906,251.52000427246094,251.39999389648438,256.2900085449219,259.9200134277344,254.05999755859375,262.42999267578125,259.5299987792969,258.5799865722656,254.0800018310547,254.75999450683594,250.0,260.7900085449219]}]}}]}],"error":null}}diff --git a/tests/fixtures/trader-scanner/spark-3mo-live-2026-10-20.json b/tests/fixtures/trader-scanner/spark-3mo-live-2026-10-20.jsonnew file mode 100644index 0000000..0f99516--- /dev/null+++ b/tests/fixtures/trader-scanner/spark-3mo-live-2026-10-20.json@@ -0,0 +1 @@+{"spark":{"result":[{"symbol":"AMZN","response":[{"meta":{"currency":"USD","symbol":"AMZN","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":863703000,"regularMarketTime":1792440001,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":262.45,"regularMarketChangePercent":4.98,"fulldayPrice":263.5,"fulldayChange":1.05,"fulldayChangePercent":0.4,"fiftyTwoWeekHigh":287.2,"fiftyTwoWeekLow":196.0,"regularMarketDayHigh":263.71,"regularMarketDayLow":255.22,"regularMarketVolume":54744203,"longName":"Amazon.com, Inc.","shortName":"Amazon.com, Inc.","chartPreviousClose":247.23,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"dataGranularity":"1d","range":"3mo","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[249.99,247.55,244.85,233.66,232.11,231.39,230.86,226.65,235.5,271.58,284.02,277.42,272.65,272.26,274.48,278.09,272.27,267.28,265.13,262.65,261.31,259.45,265.84,260.11,258.63,262.07,261.06,260.28,256.26,266.43,259.77,254.92,254.98,258.9,258.51,256.97,252.4,251.89,256.78,253.54,248.42,245.96,251.19,253.71,258.45,254.98,249.27,249.38,249.67,246.15,246.67,249.15,248.23,251.52,251.4,256.29,259.92,254.06,262.43,259.53,258.58,254.08,254.76,250.0,262.45]}]}}]},{"symbol":"AMC","response":[{"meta":{"currency":"USD","symbol":"AMC","exchangeName":"NYQ","fullExchangeName":"NYSE","instrumentType":"EQUITY","firstTradeDate":1387377000,"regularMarketTime":1792440003,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":2.98,"regularMarketChangePercent":2.405,"fulldayPrice":2.948,"fulldayChange":-0.032,"fulldayChangePercent":-1.057,"fiftyTwoWeekHigh":3.4,"fiftyTwoWeekLow":0.93,"regularMarketDayHigh":3.06,"regularMarketDayLow":2.9,"regularMarketVolume":22795658,"longName":"AMC Entertainment Holdings, Inc.","shortName":"AMC Entertainment Holdings, Inc","chartPreviousClose":1.94,"priceHint":4,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"dataGranularity":"1d","range":"3mo","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[2.46,2.2,2.25,2.28,2.27,2.51,2.67,2.75,2.77,2.82,2.85,2.68,2.67,2.57,2.59,2.42,2.4,2.53,2.63,2.5,2.44,2.38,2.52,2.47,2.55,2.67,2.65,2.61,2.7,2.59,2.64,2.58,2.64,2.54,2.65,2.56,2.46,2.36,2.46,2.5,2.55,2.66,2.71,2.7,2.89,2.97,2.87,2.91,2.94,3.29,3.08,3.0,2.76,2.77,2.79,2.95,2.88,2.88,2.98,3.0,3.06,2.89,3.02,2.91,2.98]}]}}]},{"symbol":"SOFI","response":[{"meta":{"currency":"USD","symbol":"SOFI","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":1609770600,"regularMarketTime":1792440001,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":14.3,"regularMarketChangePercent":-1.718,"fulldayPrice":14.1,"fulldayChange":-0.2,"fulldayChangePercent":-1.399,"fiftyTwoWeekHigh":32.73,"fiftyTwoWeekLow":13.86,"regularMarketDayHigh":14.76,"regularMarketDayLow":14.265,"regularMarketVolume":39523886,"longName":"SoFi Technologies, Inc.","shortName":"SoFi Technologies, Inc.","chartPreviousClose":17.28,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"dataGranularity":"1d","range":"3mo","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[17.01,17.64,17.07,16.65,16.46,16.88,16.74,15.25,16.47,16.31,18.03,18.7,18.25,18.1,18.38,18.12,17.98,17.94,18.43,18.29,18.31,17.66,18.42,17.92,18.91,18.24,19.0,18.84,19.18,18.06,17.88,17.05,17.84,18.51,18.22,18.01,17.33,17.21,17.32,17.65,17.07,16.84,16.73,16.96,16.97,17.16,16.55,16.8,16.58,15.93,15.91,15.72,15.84,15.77,15.92,15.76,15.66,15.61,15.8,15.23,15.24,14.22,15.09,14.55,14.3]}]}}]},{"symbol":"F","response":[{"meta":{"currency":"USD","symbol":"F","exchangeName":"NYQ","fullExchangeName":"NYSE","instrumentType":"EQUITY","firstTradeDate":76253400,"regularMarketTime":1792440002,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":12.18,"regularMarketChangePercent":-2.011,"fulldayPrice":11.949,"fulldayChange":-0.231,"fulldayChangePercent":-1.9,"fiftyTwoWeekHigh":17.78,"fiftyTwoWeekLow":11.11,"regularMarketDayHigh":12.43,"regularMarketDayLow":12.13,"regularMarketVolume":31290747,"longName":"Ford Motor Company","shortName":"Ford Motor Company","chartPreviousClose":14.23,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"dataGranularity":"1d","range":"3mo","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[13.99,14.27,14.42,14.15,14.37,14.68,14.96,15.28,14.86,14.68,14.43,14.24,14.13,13.79,13.98,14.0,13.98,13.83,13.89,14.37,14.05,13.93,14.5,13.99,14.41,13.93,13.95,13.9,13.95,13.88,13.94,13.84,14.14,14.41,14.62,14.0,13.45,13.88,13.97,13.86,13.5,13.35,13.61,13.21,13.17,13.1,12.94,12.6,12.71,12.38,12.3,12.06,12.27,12.1,12.15,12.28,12.12,12.25,12.17,12.0,12.1,12.05,12.31,12.43,12.18]}]}}]},{"symbol":"AAPL","response":[{"meta":{"currency":"USD","symbol":"AAPL","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":345479400,"regularMarketTime":1792440001,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":342.94,"regularMarketChangePercent":-0.151,"fulldayPrice":339.25,"fulldayChange":-3.69,"fulldayChangePercent":-1.076,"fiftyTwoWeekHigh":348.15,"fiftyTwoWeekLow":243.42,"regularMarketDayHigh":345.99,"regularMarketDayLow":340.115,"regularMarketVolume":34524344,"longName":"Apple Inc.","shortName":"Apple Inc.","chartPreviousClose":333.74,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"dataGranularity":"1d","range":"3mo","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[326.59,327.74,325.89,321.66,333.02,336.91,340.08,338.19,333.43,308.91,303.42,309.38,311.0,312.41,313.33,308.26,304.91,302.25,305.26,305.93,305.59,310.03,316.83,311.3,309.35,310.34,309.9,313.45,314.58,319.7,316.85,325.13,324.96,328.21,319.97,316.22,315.34,326.57,332.27,333.08,331.34,332.41,337.0,336.13,338.98,339.75,337.02,335.92,341.07,338.4,329.4,333.02,330.32,333.69,332.89,333.63,336.67,340.42,336.64,340.97,341.27,342.96,342.0,343.46,342.94]}]}}]},{"symbol":"NVDA","response":[{"meta":{"currency":"USD","symbol":"NVDA","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":917015400,"regularMarketTime":1792440001,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":217.09,"regularMarketChangePercent":1.382,"fulldayPrice":216.02,"fulldayChange":-1.07,"fulldayChangePercent":-0.493,"fiftyTwoWeekHigh":243.37,"fiftyTwoWeekLow":164.27,"regularMarketDayHigh":219.62,"regularMarketDayLow":214.7,"regularMarketVolume":98236684,"longName":"NVIDIA Corporation","shortName":"NVIDIA Corporation","chartPreviousClose":202.81,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"dataGranularity":"1d","range":"3mo","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[203.28,207.29,212.06,208.76,206.84,196.51,197.01,190.01,195.04,200.75,206.64,211.94,219.22,218.99,223.96,217.55,217.5,224.09,225.3,225.16,225.01,219.74,217.56,216.85,214.72,208.48,213.05,209.66,227.98,217.55,220.78,217.44,224.41,228.45,230.36,225.73,223.67,218.36,218.29,210.96,212.17,213.9,219.34,222.27,227.38,228.87,225.51,224.58,225.07,228.86,227.21,228.38,230.86,233.95,238.9,239.24,237.47,230.48,229.28,226.32,228.52,221.3,217.23,214.13,217.09]}]}}]},{"symbol":"BRK-B","response":[{"meta":{"currency":"USD","symbol":"BRK-B","exchangeName":"NYQ","fullExchangeName":"NYSE","instrumentType":"EQUITY","firstTradeDate":831648600,"regularMarketTime":1792440038,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":532.23,"regularMarketChangePercent":0.039,"fulldayPrice":535.0,"fulldayChange":2.53,"fulldayChangePercent":0.475,"fiftyTwoWeekHigh":537.74,"fiftyTwoWeekLow":464.01,"regularMarketDayHigh":533.17,"regularMarketDayLow":528.84,"regularMarketVolume":4776764,"longName":"Berkshire Hathaway Inc.","shortName":"Berkshire Hathaway Inc. New","chartPreviousClose":490.91,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"dataGranularity":"1d","range":"3mo","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[491.25,489.65,489.39,490.85,494.93,497.18,512.37,509.16,509.68,511.54,513.14,517.22,518.85,524.61,521.8,529.42,516.38,510.0,506.93,504.03,498.23,502.96,499.62,496.86,495.82,504.32,504.32,504.91,503.7,505.0,504.03,502.33,505.24,508.13,506.03,505.83,506.72,507.0,510.37,514.95,516.76,519.8,509.2,509.77,502.01,503.49,507.17,505.18,505.48,503.09,502.35,497.95,500.5,502.65,504.26,505.54,506.25,511.05,515.62,517.6,520.59,526.35,525.68,532.02,532.23]}]}}]},{"symbol":"PLTR","response":[{"meta":{"currency":"USD","symbol":"PLTR","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":1601472600,"regularMarketTime":1792440001,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":194.15,"regularMarketChangePercent":4.365,"fulldayPrice":193.12,"fulldayChange":-1.03,"fulldayChangePercent":-0.531,"fiftyTwoWeekHigh":212.94,"fiftyTwoWeekLow":106.37,"regularMarketDayHigh":196.99,"regularMarketDayLow":186.155,"regularMarketVolume":23719536,"longName":"Palantir Technologies Inc.","shortName":"Palantir Technologies Inc.","chartPreviousClose":132.38,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"dataGranularity":"1d","range":"3mo","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[134.85,132.66,124.57,123.37,122.92,131.53,123.53,123.0,122.26,123.06,125.65,162.66,158.43,155.92,172.01,175.23,174.94,171.04,179.01,174.04,172.55,171.54,175.19,173.96,179.94,175.89,172.73,177.5,185.93,186.29,186.38,179.92,169.46,182.53,174.33,170.3,169.53,165.86,167.23,173.31,172.56,174.34,176.24,177.64,183.09,184.99,191.79,192.59,189.67,187.48,186.97,187.05,190.04,188.75,189.4,192.07,194.12,198.78,209.05,209.0,208.67,200.97,200.5,186.03,194.15]}]}}]},{"symbol":"INTC","response":[{"meta":{"currency":"USD","symbol":"INTC","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":322151400,"regularMarketTime":1792440001,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":92.03,"regularMarketChangePercent":2.426,"fulldayPrice":90.81,"fulldayChange":-1.22,"fulldayChangePercent":-1.326,"fiftyTwoWeekHigh":142.35,"fiftyTwoWeekLow":32.89,"regularMarketDayHigh":95.39,"regularMarketDayLow":91.88,"regularMarketVolume":101113975,"longName":"Intel Corporation","shortName":"Intel Corporation","chartPreviousClose":95.04,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"dataGranularity":"1d","range":"3mo","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[97.06,105.45,102.62,100.23,92.32,91.67,86.3,81.88,91.13,90.2,91.0,100.86,101.06,99.81,101.65,97.52,97.71,100.95,104.56,102.5,103.49,96.69,92.8,92.13,90.07,87.26,87.48,88.24,92.09,89.47,89.51,88.97,90.05,91.67,95.8,104.47,106.24,100.32,102.94,97.19,97.14,101.05,108.8,108.6,121.78,123.86,122.6,127.39,123.0,116.03,115.93,120.23,120.0,119.33,116.19,112.5,113.12,107.08,104.7,101.35,102.81,98.12,95.37,89.85,92.03]}]}}]},{"symbol":"META","response":[{"meta":{"currency":"USD","symbol":"META","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":1337347800,"regularMarketTime":1792440000,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":705.44,"regularMarketChangePercent":-0.548,"fulldayPrice":698.3,"fulldayChange":-7.14,"fulldayChangePercent":-1.012,"fiftyTwoWeekHigh":779.82,"fiftyTwoWeekLow":520.26,"regularMarketDayHigh":708.7,"regularMarketDayLow":693.86,"regularMarketVolume":15788171,"longName":"Meta Platforms, Inc.","shortName":"Meta Platforms, Inc.","chartPreviousClose":646.01,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"dataGranularity":"1d","range":"3mo","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[645.85,643.81,627.17,606.1,595.19,593.87,593.41,585.61,539.03,556.71,590.24,587.94,588.77,589.9,592.1,594.92,599.12,578.85,594.97,589.85,568.97,543.67,546.03,545.83,549.9,559.02,570.05,576.14,571.1,578.02,572.34,578.54,592.85,610.68,616.77,613.48,653.69,644.38,648.03,665.6,670.24,673.31,682.31,665.75,741.25,736.6,744.1,777.59,751.66,715.62,738.79,725.18,725.93,728.08,741.9,738.88,721.31,720.89,718.67,742.96,762.5,737.54,736.72,709.33,705.44]}]}}]},{"symbol":"TSLA","response":[{"meta":{"currency":"USD","symbol":"TSLA","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":1277818200,"regularMarketTime":1792440001,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":368.06,"regularMarketChangePercent":3.761,"fulldayPrice":369.079,"fulldayChange":1.019,"fulldayChangePercent":0.277,"fiftyTwoWeekHigh":498.83,"fiftyTwoWeekLow":297.38,"regularMarketDayHigh":369.581,"regularMarketDayLow":354.47,"regularMarketVolume":38651173,"longName":"Tesla, Inc.","shortName":"Tesla, Inc.","chartPreviousClose":380.84,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"dataGranularity":"1d","range":"3mo","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[369.57,378.93,374.01,319.69,313.03,309.22,307.44,298.32,308.85,311.21,322.08,327.35,321.55,319.53,328.58,330.88,332.81,327.51,339.96,342.27,339.3,336.87,351.12,345.13,362.86,348.95,350.25,345.82,354.81,348.75,367.95,356.09,357.01,376.37,354.08,368.16,367.81,363.56,365.44,358.97,356.58,358.08,366.2,364.27,375.3,378.9,380.12,377.94,372.11,357.45,352.84,354.81,354.11,370.59,378.73,380.68,377.81,375.0,382.7,378.03,375.23,367.16,362.44,354.72,368.06]}]}}]},{"symbol":"AMD","response":[{"meta":{"currency":"USD","symbol":"AMD","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":322151400,"regularMarketTime":1792440001,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":538.05,"regularMarketChangePercent":1.759,"fulldayPrice":532.0,"fulldayChange":-6.05,"fulldayChangePercent":-1.124,"fiftyTwoWeekHigh":658.52,"fiftyTwoWeekLow":188.22,"regularMarketDayHigh":554.409,"regularMarketDayLow":535.67,"regularMarketVolume":20120889,"longName":"Advanced Micro Devices, Inc.","shortName":"Advanced Micro Devices, Inc.","chartPreviousClose":495.76,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"dataGranularity":"1d","range":"3mo","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[503.57,544.43,552.33,539.69,521.95,494.95,454.62,429.56,485.39,476.15,484.64,518.58,482.05,489.28,483.36,469.56,474.32,482.93,483.01,514.39,506.0,484.39,466.42,469.46,473.25,456.75,479.18,480.93,476.67,465.58,470.72,459.61,457.06,456.16,477.57,505.74,521.1,503.6,516.13,493.41,504.2,512.5,545.09,559.82,615.52,623.77,614.61,629.26,630.63,607.87,607.57,611.76,615.73,633.91,631.75,649.42,645.86,620.68,608.1,594.24,605.53,570.82,562.23,528.75,538.05]}]}}]},{"symbol":"MSFT","response":[{"meta":{"currency":"USD","symbol":"MSFT","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":511108200,"regularMarketTime":1792440000,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":533.52,"regularMarketChangePercent":0.845,"fulldayPrice":534.91,"fulldayChange":1.39,"fulldayChangePercent":0.261,"fiftyTwoWeekHigh":553.72,"fiftyTwoWeekLow":349.2,"regularMarketDayHigh":535.568,"regularMarketDayLow":528.48,"regularMarketVolume":17469801,"longName":"Microsoft Corporation","shortName":"Microsoft Corporation","chartPreviousClose":393.82,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"dataGranularity":"1d","range":"3mo","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[402.29,397.75,390.34,381.58,381.7,389.1,393.35,390.54,451.1,464.72,487.65,492.81,487.46,499.86,499.99,506.06,503.81,492.43,496.88,495.4,480.35,481.63,484.31,481.15,483.24,487.31,491.71,496.37,505.06,513.53,507.29,501.02,496.82,510.12,499.7,493.95,491.65,492.44,495.63,505.41,497.12,490.3,497.75,493.78,501.61,498.0,500.59,497.93,516.17,509.22,508.96,512.9,512.8,517.53,525.18,529.3,529.76,522.61,535.07,541.15,543.45,533.69,539.44,529.05,533.52]}]}}]},{"symbol":"BAC","response":[{"meta":{"currency":"USD","symbol":"BAC","exchangeName":"NYQ","fullExchangeName":"NYSE","instrumentType":"EQUITY","firstTradeDate":99153000,"regularMarketTime":1792440002,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":50.39,"regularMarketChangePercent":-1.64,"fulldayPrice":50.382,"fulldayChange":-0.008,"fulldayChangePercent":-0.017,"fiftyTwoWeekHigh":65.23,"fiftyTwoWeekLow":46.12,"regularMarketDayHigh":51.53,"regularMarketDayLow":50.2,"regularMarketVolume":42647374,"longName":"Bank of America Corporation","shortName":"Bank of America Corporation","chartPreviousClose":61.27,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"dataGranularity":"1d","range":"3mo","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[60.42,61.22,61.62,61.28,62.05,62.13,62.62,61.07,61.73,61.95,62.48,62.9,63.25,63.0,63.17,63.86,64.0,64.81,64.09,64.49,63.89,64.23,63.17,61.86,61.69,62.33,62.43,62.23,61.17,62.32,61.94,61.99,62.6,63.04,62.68,62.39,62.67,62.56,62.69,59.47,59.52,57.9,58.18,57.73,57.96,56.2,56.0,56.03,56.7,55.47,54.96,54.43,53.73,53.75,54.0,54.09,53.52,53.61,54.32,54.58,53.96,51.39,51.7,51.23,50.39]}]}}]},{"symbol":"KO","response":[{"meta":{"currency":"USD","symbol":"KO","exchangeName":"NYQ","fullExchangeName":"NYSE","instrumentType":"EQUITY","firstTradeDate":-252322200,"regularMarketTime":1792440002,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":93.42,"regularMarketChangePercent":-0.511,"fulldayPrice":93.975,"fulldayChange":0.54,"fulldayChangePercent":0.578,"fiftyTwoWeekHigh":94.1,"fiftyTwoWeekLow":67.27,"regularMarketDayHigh":93.99,"regularMarketDayLow":92.622,"regularMarketVolume":16433909,"longName":"The Coca-Cola Company","shortName":"Coca-Cola Company (The)","chartPreviousClose":81.56,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"dataGranularity":"1d","range":"3mo","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[82.12,81.97,82.2,81.17,82.25,84.07,88.27,89.08,88.49,87.59,86.86,86.56,86.83,86.85,87.05,86.87,86.48,86.71,87.42,87.71,86.98,88.82,90.35,90.5,91.1,91.99,91.64,90.08,89.06,89.66,88.67,88.0,88.24,88.81,88.07,88.36,87.55,87.83,88.29,89.35,88.71,87.87,88.06,88.25,87.12,88.61,88.09,88.1,87.81,87.18,86.84,86.08,86.1,85.65,86.51,86.17,85.82,87.77,88.05,89.79,90.11,91.78,92.0,93.9,93.42]}]}}]},{"symbol":"GOOGL","response":[{"meta":{"currency":"USD","symbol":"GOOGL","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":1092922200,"regularMarketTime":1792440001,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":344.18,"regularMarketChangePercent":1.054,"fulldayPrice":342.93,"fulldayChange":-1.25,"fulldayChangePercent":-0.363,"fiftyTwoWeekHigh":408.61,"fiftyTwoWeekLow":244.15,"regularMarketDayHigh":346.58,"regularMarketDayLow":341.85,"regularMarketVolume":19012489,"longName":"Alphabet Inc.","shortName":"Alphabet Inc.","chartPreviousClose":346.77,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"dataGranularity":"1d","range":"3mo","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[351.99,347.15,342.09,317.69,319.74,326.56,333.71,336.71,333.66,356.13,373.51,377.65,362.43,357.75,354.3,357.52,343.8,343.54,346.36,345.9,344.0,344.2,344.72,340.67,344.82,348.06,346.96,342.0,340.65,346.59,339.35,335.02,337.12,342.48,338.46,338.36,330.65,332.6,338.5,349.39,344.98,342.87,347.33,349.54,354.97,351.16,337.83,342.36,343.92,342.75,340.92,344.08,338.24,343.5,346.47,347.68,350.5,348.29,351.66,352.72,353.78,347.64,349.22,340.59,344.18]}]}}]},{"symbol":"LCID","response":[{"meta":{"currency":"USD","symbol":"LCID","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":1600435800,"regularMarketTime":1792440001,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":3.095,"regularMarketChangePercent":-1.118,"fulldayPrice":3.08,"fulldayChange":-0.015,"fulldayChangePercent":-0.485,"fiftyTwoWeekHigh":20.31,"fiftyTwoWeekLow":2.37,"regularMarketDayHigh":3.16,"regularMarketDayLow":3.09,"regularMarketVolume":5248666,"longName":"Lucid Group, Inc.","shortName":"Lucid Group, Inc.","chartPreviousClose":7.36,"priceHint":4,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"dataGranularity":"1d","range":"3mo","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[7.11,7.32,6.78,6.45,6.3,6.5,7.9,7.96,8.12,7.38,7.7,7.78,6.7,6.98,7.04,6.61,6.7,6.54,6.44,6.22,6.22,5.77,5.92,5.625,5.51,5.09,5.26,4.95,5.09,5.01,4.85,4.55,4.71,4.6,4.68,4.63,4.27,4.18,4.22,4.16,4.12,4.04,4.28,4.09,4.3,4.32,4.16,4.15,4.07,3.9,4.07,4.07,4.19,4.13,4.17,4.16,3.89,3.82,3.79,3.435,3.355,3.29,3.5,3.13,3.095]}]}}]},{"symbol":"PLUG","response":[{"meta":{"currency":"USD","symbol":"PLUG","exchangeName":"NCM","fullExchangeName":"NasdaqCM","instrumentType":"EQUITY","firstTradeDate":941203800,"regularMarketTime":1792440001,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":1.37,"regularMarketChangePercent":-0.725,"fulldayPrice":1.341,"fulldayChange":-0.029,"fulldayChangePercent":-2.131,"fiftyTwoWeekHigh":4.33,"fiftyTwoWeekLow":1.35,"regularMarketDayHigh":1.44,"regularMarketDayLow":1.37,"regularMarketVolume":37739053,"longName":"Plug Power Inc.","shortName":"Plug Power, Inc.","chartPreviousClose":2.17,"priceHint":4,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"dataGranularity":"1d","range":"3mo","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1784554200,1784640600,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[2.13,2.27,2.19,2.09,2.06,1.96,1.9,2.09,2.06,2.08,2.16,2.1,2.07,2.18,2.11,2.22,2.29,2.3,2.32,2.28,2.16,2.25,2.2,2.27,2.17,2.27,2.17,2.27,2.19,2.16,2.09,2.09,2.11,2.17,2.26,2.17,2.11,2.1,2.06,2.05,2.02,2.12,2.09,2.09,2.11,2.04,1.96,1.98,1.86,1.91,1.94,1.89,1.9,1.89,1.86,1.78,1.73,1.68,1.62,1.56,1.45,1.49,1.38,1.37]}]}}]},{"symbol":"RIVN","response":[{"meta":{"currency":"USD","symbol":"RIVN","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":1636554600,"regularMarketTime":1792440000,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":12.34,"regularMarketChangePercent":-0.644,"fulldayPrice":12.27,"fulldayChange":-0.07,"fulldayChangePercent":-0.567,"fiftyTwoWeekHigh":22.69,"fiftyTwoWeekLow":12.16,"regularMarketDayHigh":12.52,"regularMarketDayLow":12.16,"regularMarketVolume":19797066,"longName":"Rivian Automotive, Inc.","shortName":"Rivian Automotive, Inc.","chartPreviousClose":17.455,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"dataGranularity":"1d","range":"3mo","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","ytd","max"]},"timestamp":[1784554200,1784640600,1784727000,1784813400,1784899800,1785159000,1785245400,1785331800,1785418200,1785504600,1785763800,1785850200,1785936600,1786023000,1786109400,1786368600,1786455000,1786541400,1786627800,1786714200,1786973400,1787059800,1787146200,1787232600,1787319000,1787578200,1787664600,1787751000,1787837400,1787923800,1788183000,1788269400,1788355800,1788442200,1788528600,1788874200,1788960600,1789047000,1789133400,1789392600,1789479000,1789565400,1789651800,1789738200,1789997400,1790083800,1790170200,1790256600,1790343000,1790602200,1790688600,1790775000,1790861400,1790947800,1791207000,1791293400,1791379800,1791466200,1791552600,1791811800,1791898200,1791984600,1792071000,1792157400,1792416600],"indicators":{"quote":[{"close":[17.24,17.76,17.18,16.46,15.84,16.48,16.69,16.33,16.83,15.22,15.355,15.76,15.56,15.38,16.0,16.39,16.36,15.93,15.82,15.36,14.87,14.78,15.73,16.01,16.97,16.6,16.74,16.33,16.8,16.07,16.06,15.535,15.61,15.91,15.74,16.17,16.005,16.05,16.03,15.86,15.54,15.23,15.4,14.99,15.36,15.14,15.02,15.29,15.47,14.79,14.97,14.94,14.76,14.3,14.6,14.51,14.34,14.33,13.96,13.54,13.37,12.95,13.02,12.42,12.34]}]}}]}],"error":null}}\ No newline at end of filediff --git a/tests/fixtures/trader-scanner/spark-5m-live-2026-10-20-1001.json b/tests/fixtures/trader-scanner/spark-5m-live-2026-10-20-1001.jsonnew file mode 100644index 0000000..1d23d00--- /dev/null+++ b/tests/fixtures/trader-scanner/spark-5m-live-2026-10-20-1001.json@@ -0,0 +1 @@+{"spark":{"result":[{"symbol":"AMZN","response":[{"meta":{"currency":"USD","symbol":"AMZN","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":863703000,"regularMarketTime":1792504905,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":262.795,"regularMarketChangePercent":0.131,"fulldayPrice":262.795,"fulldayChange":0.345,"fulldayChangePercent":0.131,"fiftyTwoWeekHigh":287.2,"fiftyTwoWeekLow":196.0,"regularMarketDayHigh":265.34,"regularMarketDayLow":260.42,"regularMarketVolume":7960240,"longName":"Amazon.com, Inc.","shortName":"Amazon.com, Inc.","chartPreviousClose":262.45,"previousClose":262.45,"scale":3,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"tradingPeriods":[[{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400}]],"dataGranularity":"5m","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1792503000,1792503300,1792503600,1792503900,1792504200,1792504500,1792504800,1792504905],"indicators":{"quote":[{"close":[262.665,261.675,260.683,262.071,262.1,262.92,262.45,262.795]}]}}]},{"symbol":"TSLA","response":[{"meta":{"currency":"USD","symbol":"TSLA","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":1277818200,"regularMarketTime":1792504907,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":371.69,"regularMarketChangePercent":0.986,"fulldayPrice":371.69,"fulldayChange":3.63,"fulldayChangePercent":0.986,"fiftyTwoWeekHigh":498.83,"fiftyTwoWeekLow":297.38,"regularMarketDayHigh":371.84,"regularMarketDayLow":363.64,"regularMarketVolume":6190367,"longName":"Tesla, Inc.","shortName":"Tesla, Inc.","chartPreviousClose":368.06,"previousClose":368.06,"scale":3,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"tradingPeriods":[[{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400}]],"dataGranularity":"5m","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1792503000,1792503300,1792503600,1792503900,1792504200,1792504500,1792504800,1792504907],"indicators":{"quote":[{"close":[367.348,366.27,366.18,367.338,368.36,370.585,370.865,371.69]}]}}]},{"symbol":"AAPL","response":[{"meta":{"currency":"USD","symbol":"AAPL","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":345479400,"regularMarketTime":1792504905,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":341.91,"regularMarketChangePercent":-0.3,"fulldayPrice":341.91,"fulldayChange":-1.03,"fulldayChangePercent":-0.3,"fiftyTwoWeekHigh":348.15,"fiftyTwoWeekLow":243.42,"regularMarketDayHigh":343.03,"regularMarketDayLow":338.7,"regularMarketVolume":5123907,"longName":"Apple Inc.","shortName":"Apple Inc.","chartPreviousClose":342.94,"previousClose":342.94,"scale":3,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"tradingPeriods":[[{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400}]],"dataGranularity":"5m","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1792503000,1792503300,1792503600,1792503900,1792504200,1792504500,1792504800,1792504905],"indicators":{"quote":[{"close":[342.32,341.075,340.48,340.66,341.38,341.69,342.11,341.91]}]}}]},{"symbol":"MSFT","response":[{"meta":{"currency":"USD","symbol":"MSFT","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":511108200,"regularMarketTime":1792504905,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":529.37,"regularMarketChangePercent":-0.778,"fulldayPrice":529.37,"fulldayChange":-4.15,"fulldayChangePercent":-0.778,"fiftyTwoWeekHigh":553.72,"fiftyTwoWeekLow":349.2,"regularMarketDayHigh":534.21,"regularMarketDayLow":525.86,"regularMarketVolume":2409731,"longName":"Microsoft Corporation","shortName":"Microsoft Corporation","chartPreviousClose":533.52,"previousClose":533.52,"scale":3,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"tradingPeriods":[[{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400}]],"dataGranularity":"5m","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1792503000,1792503300,1792503600,1792503900,1792504200,1792504500,1792504800,1792504905],"indicators":{"quote":[{"close":[533.64,530.755,526.676,528.95,528.095,529.315,529.239,529.37]}]}}]},{"symbol":"META","response":[{"meta":{"currency":"USD","symbol":"META","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":1337347800,"regularMarketTime":1792504905,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":684.415,"regularMarketChangePercent":-2.98,"fulldayPrice":684.415,"fulldayChange":-20.955,"fulldayChangePercent":-2.97,"fiftyTwoWeekHigh":779.82,"fiftyTwoWeekLow":520.26,"regularMarketDayHigh":696.0,"regularMarketDayLow":681.05,"regularMarketVolume":3466564,"longName":"Meta Platforms, Inc.","shortName":"Meta Platforms, Inc.","chartPreviousClose":705.44,"previousClose":705.44,"scale":3,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"tradingPeriods":[[{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400}]],"dataGranularity":"5m","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1792503000,1792503300,1792503600,1792503900,1792504200,1792504500,1792504800,1792504905],"indicators":{"quote":[{"close":[688.96,687.015,683.64,684.41,682.32,683.865,684.358,684.415]}]}}]},{"symbol":"KO","response":[{"meta":{"currency":"USD","symbol":"KO","exchangeName":"NYQ","fullExchangeName":"NYSE","instrumentType":"EQUITY","firstTradeDate":-252322200,"regularMarketTime":1792504905,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":93.24,"regularMarketChangePercent":-0.193,"fulldayPrice":93.24,"fulldayChange":-0.18,"fulldayChangePercent":-0.193,"fiftyTwoWeekHigh":94.1,"fiftyTwoWeekLow":67.27,"regularMarketDayHigh":93.96,"regularMarketDayLow":93.22,"regularMarketVolume":1852985,"longName":"The Coca-Cola Company","shortName":"Coca-Cola Company (The)","chartPreviousClose":93.42,"previousClose":93.42,"scale":3,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"tradingPeriods":[[{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400}]],"dataGranularity":"5m","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1792503000,1792503300,1792503600,1792503900,1792504200,1792504500,1792504800,1792504905],"indicators":{"quote":[{"close":[93.8,93.71,93.89,93.72,93.71,93.375,93.33,93.24]}]}}]},{"symbol":"PLTR","response":[{"meta":{"currency":"USD","symbol":"PLTR","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":1601472600,"regularMarketTime":1792504906,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":192.955,"regularMarketChangePercent":-0.615,"fulldayPrice":192.955,"fulldayChange":-1.195,"fulldayChangePercent":-0.615,"fiftyTwoWeekHigh":212.94,"fiftyTwoWeekLow":106.37,"regularMarketDayHigh":193.28,"regularMarketDayLow":189.42,"regularMarketVolume":2914566,"longName":"Palantir Technologies Inc.","shortName":"Palantir Technologies Inc.","chartPreviousClose":194.15,"previousClose":194.15,"scale":3,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"tradingPeriods":[[{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400}]],"dataGranularity":"5m","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1792503000,1792503300,1792503600,1792503900,1792504200,1792504500,1792504800,1792504906],"indicators":{"quote":[{"close":[191.79,192.042,189.909,192.24,191.52,192.839,192.78,192.955]}]}}]},{"symbol":"JPM","response":[{"meta":{"currency":"USD","symbol":"JPM","exchangeName":"NYQ","fullExchangeName":"NYSE","instrumentType":"EQUITY","firstTradeDate":322151400,"regularMarketTime":1792504905,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":337.765,"regularMarketChangePercent":1.27,"fulldayPrice":337.765,"fulldayChange":4.235,"fulldayChangePercent":1.27,"fiftyTwoWeekHigh":366.5,"fiftyTwoWeekLow":279.1,"regularMarketDayHigh":339.035,"regularMarketDayLow":332.55,"regularMarketVolume":1125486,"longName":"JPMorgan Chase & Co.","shortName":"JP Morgan Chase & Co.","chartPreviousClose":333.53,"previousClose":333.53,"scale":3,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"tradingPeriods":[[{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400}]],"dataGranularity":"5m","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1792503000,1792503300,1792503600,1792503900,1792504200,1792504500,1792504800,1792504905],"indicators":{"quote":[{"close":[333.48,336.47,337.14,337.94,338.68,338.02,337.885,337.765]}]}}]},{"symbol":"BAC","response":[{"meta":{"currency":"USD","symbol":"BAC","exchangeName":"NYQ","fullExchangeName":"NYSE","instrumentType":"EQUITY","firstTradeDate":99153000,"regularMarketTime":1792504906,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":50.705,"regularMarketChangePercent":0.625,"fulldayPrice":50.705,"fulldayChange":0.315,"fulldayChangePercent":0.625,"fiftyTwoWeekHigh":65.23,"fiftyTwoWeekLow":46.12,"regularMarketDayHigh":50.885,"regularMarketDayLow":50.01,"regularMarketVolume":6966227,"longName":"Bank of America Corporation","shortName":"Bank of America Corporation","chartPreviousClose":50.39,"previousClose":50.39,"scale":3,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"tradingPeriods":[[{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400}]],"dataGranularity":"5m","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1792503000,1792503300,1792503600,1792503900,1792504200,1792504500,1792504800,1792504906],"indicators":{"quote":[{"close":[50.105,50.75,50.71,50.715,50.84,50.75,50.745,50.705]}]}}]},{"symbol":"GOOGL","response":[{"meta":{"currency":"USD","symbol":"GOOGL","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":1092922200,"regularMarketTime":1792504905,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":343.93,"regularMarketChangePercent":-0.073,"fulldayPrice":343.93,"fulldayChange":-0.25,"fulldayChangePercent":-0.073,"fiftyTwoWeekHigh":408.61,"fiftyTwoWeekLow":244.15,"regularMarketDayHigh":344.32,"regularMarketDayLow":341.0,"regularMarketVolume":2252714,"longName":"Alphabet Inc.","shortName":"Alphabet Inc.","chartPreviousClose":344.18,"previousClose":344.18,"scale":3,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"tradingPeriods":[[{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400}]],"dataGranularity":"5m","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1792503000,1792503300,1792503600,1792503900,1792504200,1792504500,1792504800,1792504905],"indicators":{"quote":[{"close":[342.98,341.945,342.02,342.935,342.37,343.45,343.7,343.93]}]}}]},{"symbol":"BRK-B","response":[{"meta":{"currency":"USD","symbol":"BRK-B","exchangeName":"NYQ","fullExchangeName":"NYSE","instrumentType":"EQUITY","firstTradeDate":831648600,"regularMarketTime":1792504907,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":537.75,"regularMarketChangePercent":1.037,"fulldayPrice":537.75,"fulldayChange":5.52,"fulldayChangePercent":1.037,"fiftyTwoWeekHigh":538.97,"fiftyTwoWeekLow":464.01,"regularMarketDayHigh":538.97,"regularMarketDayLow":533.85,"regularMarketVolume":873509,"longName":"Berkshire Hathaway Inc.","shortName":"Berkshire Hathaway Inc. New","chartPreviousClose":532.23,"previousClose":532.23,"scale":3,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"tradingPeriods":[[{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400}]],"dataGranularity":"5m","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1792503000,1792503300,1792503600,1792503900,1792504200,1792504500,1792504800,1792504907],"indicators":{"quote":[{"close":[536.27,536.925,537.46,537.5,538.42,537.62,537.695,537.75]}]}}]},{"symbol":"XOM","response":[{"meta":{"currency":"USD","symbol":"XOM","exchangeName":"NYQ","fullExchangeName":"NYSE","instrumentType":"EQUITY","firstTradeDate":-252322200,"regularMarketTime":1792504905,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":178.09,"regularMarketChangePercent":-0.107,"fulldayPrice":178.09,"fulldayChange":-0.19,"fulldayChangePercent":-0.107,"fiftyTwoWeekHigh":180.26,"fiftyTwoWeekLow":111.99,"regularMarketDayHigh":180.26,"regularMarketDayLow":177.65,"regularMarketVolume":1272615,"longName":"ExxonMobil Holdings Corporation","shortName":"ExxonMobil Holdings Corporation","chartPreviousClose":178.28,"previousClose":178.28,"scale":3,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"tradingPeriods":[[{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400}]],"dataGranularity":"5m","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1792503000,1792503300,1792503600,1792503900,1792504200,1792504500,1792504800,1792504905],"indicators":{"quote":[{"close":[179.31,178.61,178.14,177.93,178.28,178.155,178.185,178.09]}]}}]},{"symbol":"NVDA","response":[{"meta":{"currency":"USD","symbol":"NVDA","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":917015400,"regularMarketTime":1792504907,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":214.675,"regularMarketChangePercent":-1.112,"fulldayPrice":214.675,"fulldayChange":-2.415,"fulldayChangePercent":-1.112,"fiftyTwoWeekHigh":243.37,"fiftyTwoWeekLow":164.27,"regularMarketDayHigh":216.46,"regularMarketDayLow":212.77,"regularMarketVolume":16322367,"longName":"NVIDIA Corporation","shortName":"NVIDIA Corporation","chartPreviousClose":217.09,"previousClose":217.09,"scale":3,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"tradingPeriods":[[{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400}]],"dataGranularity":"5m","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1792503000,1792503300,1792503600,1792503900,1792504200,1792504500,1792504800,1792504907],"indicators":{"quote":[{"close":[214.355,214.315,213.07,213.715,213.8,214.44,214.456,214.675]}]}}]},{"symbol":"COIN","response":[{"meta":{"currency":"USD","symbol":"COIN","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":1618407000,"regularMarketTime":1792504907,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":169.82,"regularMarketChangePercent":0.813,"fulldayPrice":169.82,"fulldayChange":1.37,"fulldayChangePercent":0.813,"fiftyTwoWeekHigh":373.25,"fiftyTwoWeekLow":139.11,"regularMarketDayHigh":170.227,"regularMarketDayLow":165.9,"regularMarketVolume":887966,"longName":"Coinbase Global, Inc.","shortName":"Coinbase Global, Inc.","chartPreviousClose":168.45,"previousClose":168.45,"scale":3,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"tradingPeriods":[[{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400}]],"dataGranularity":"5m","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1792503000,1792503300,1792503600,1792503900,1792504200,1792504500,1792504800,1792504907],"indicators":{"quote":[{"close":[166.35,168.625,167.07,169.1,168.705,169.82,170.07,169.82]}]}}]},{"symbol":"AMC","response":[{"meta":{"currency":"USD","symbol":"AMC","exchangeName":"NYQ","fullExchangeName":"NYSE","instrumentType":"EQUITY","firstTradeDate":1387377000,"regularMarketTime":1792504906,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":3.014,"regularMarketChangePercent":1.138,"fulldayPrice":3.014,"fulldayChange":0.034,"fulldayChangePercent":1.138,"fiftyTwoWeekHigh":3.4,"fiftyTwoWeekLow":0.93,"regularMarketDayHigh":3.019,"regularMarketDayLow":2.935,"regularMarketVolume":2005022,"longName":"AMC Entertainment Holdings, Inc.","shortName":"AMC Entertainment Holdings, Inc","chartPreviousClose":2.98,"previousClose":2.98,"scale":3,"priceHint":4,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"tradingPeriods":[[{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400}]],"dataGranularity":"5m","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1792503000,1792503300,1792503600,1792503900,1792504200,1792504500,1792504800,1792504906],"indicators":{"quote":[{"close":[2.965,2.96,2.962,2.98,2.99,3.005,2.995,3.014]}]}}]},{"symbol":"AMD","response":[{"meta":{"currency":"USD","symbol":"AMD","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":322151400,"regularMarketTime":1792504907,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":534.735,"regularMarketChangePercent":-0.616,"fulldayPrice":534.735,"fulldayChange":-3.315,"fulldayChangePercent":-0.616,"fiftyTwoWeekHigh":658.52,"fiftyTwoWeekLow":188.22,"regularMarketDayHigh":535.3,"regularMarketDayLow":524.6,"regularMarketVolume":2838501,"longName":"Advanced Micro Devices, Inc.","shortName":"Advanced Micro Devices, Inc.","chartPreviousClose":538.05,"previousClose":538.05,"scale":3,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"tradingPeriods":[[{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400}]],"dataGranularity":"5m","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1792503000,1792503300,1792503600,1792503900,1792504200,1792504500,1792504800,1792504907],"indicators":{"quote":[{"close":[530.795,530.16,527.4,529.96,530.2,533.69,534.25,534.735]}]}}]},{"symbol":"SOFI","response":[{"meta":{"currency":"USD","symbol":"SOFI","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":1609770600,"regularMarketTime":1792504907,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":14.725,"regularMarketChangePercent":2.972,"fulldayPrice":14.725,"fulldayChange":0.425,"fulldayChangePercent":2.972,"fiftyTwoWeekHigh":32.73,"fiftyTwoWeekLow":13.86,"regularMarketDayHigh":14.75,"regularMarketDayLow":14.18,"regularMarketVolume":8391786,"longName":"SoFi Technologies, Inc.","shortName":"SoFi Technologies, Inc.","chartPreviousClose":14.3,"previousClose":14.3,"scale":3,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"tradingPeriods":[[{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400}]],"dataGranularity":"5m","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1792503000,1792503300,1792503600,1792503900,1792504200,1792504500,1792504800,1792504907],"indicators":{"quote":[{"close":[14.285,14.45,14.415,14.56,14.595,14.7,14.71,14.725]}]}}]},{"symbol":"INTC","response":[{"meta":{"currency":"USD","symbol":"INTC","exchangeName":"NMS","fullExchangeName":"NasdaqGS","instrumentType":"EQUITY","firstTradeDate":322151400,"regularMarketTime":1792504907,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":90.83,"regularMarketChangePercent":-1.304,"fulldayPrice":90.83,"fulldayChange":-1.2,"fulldayChangePercent":-1.304,"fiftyTwoWeekHigh":142.35,"fiftyTwoWeekLow":32.89,"regularMarketDayHigh":91.05,"regularMarketDayLow":88.77,"regularMarketVolume":17549477,"longName":"Intel Corporation","shortName":"Intel Corporation","chartPreviousClose":92.03,"previousClose":92.03,"scale":3,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"tradingPeriods":[[{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400}]],"dataGranularity":"5m","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1792503000,1792503300,1792503600,1792503900,1792504200,1792504500,1792504800,1792504907],"indicators":{"quote":[{"close":[89.51,89.7,88.85,89.73,89.79,90.47,90.642,90.83]}]}}]},{"symbol":"UBER","response":[{"meta":{"currency":"USD","symbol":"UBER","exchangeName":"NYQ","fullExchangeName":"NYSE","instrumentType":"EQUITY","firstTradeDate":1557495000,"regularMarketTime":1792504896,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":69.53,"regularMarketChangePercent":-0.615,"fulldayPrice":69.53,"fulldayChange":-0.43,"fulldayChangePercent":-0.615,"fiftyTwoWeekHigh":100.35,"fiftyTwoWeekLow":65.41,"regularMarketDayHigh":69.585,"regularMarketDayLow":68.43,"regularMarketVolume":2687369,"longName":"Uber Technologies, Inc.","shortName":"Uber Technologies, Inc.","chartPreviousClose":69.96,"previousClose":69.96,"scale":3,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"tradingPeriods":[[{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400}]],"dataGranularity":"5m","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1792503000,1792503300,1792503600,1792503900,1792504200,1792504500,1792504800,1792504896],"indicators":{"quote":[{"close":[68.51,68.99,68.82,69.39,69.425,69.515,69.526,69.53]}]}}]},{"symbol":"F","response":[{"meta":{"currency":"USD","symbol":"F","exchangeName":"NYQ","fullExchangeName":"NYSE","instrumentType":"EQUITY","firstTradeDate":76253400,"regularMarketTime":1792504903,"hasPrePostMarketData":true,"gmtoffset":-14400,"timezone":"EDT","exchangeTimezoneName":"America/New_York","regularMarketPrice":12.071,"regularMarketChangePercent":-0.897,"fulldayPrice":12.071,"fulldayChange":-0.109,"fulldayChangePercent":-0.897,"fiftyTwoWeekHigh":17.78,"fiftyTwoWeekLow":11.11,"regularMarketDayHigh":12.08,"regularMarketDayLow":11.81,"regularMarketVolume":6292492,"longName":"Ford Motor Company","shortName":"Ford Motor Company","chartPreviousClose":12.18,"previousClose":12.18,"scale":3,"priceHint":2,"currentTradingPeriod":{"pre":{"timezone":"EDT","end":1792503000,"start":1792483200,"gmtoffset":-14400},"regular":{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400},"post":{"timezone":"EDT","end":1792540800,"start":1792526400,"gmtoffset":-14400}},"tradingPeriods":[[{"timezone":"EDT","end":1792526400,"start":1792503000,"gmtoffset":-14400}]],"dataGranularity":"5m","range":"1d","validRanges":["1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max"]},"timestamp":[1792503000,1792503300,1792503600,1792503900,1792504200,1792504500,1792504800,1792504903],"indicators":{"quote":[{"close":[11.97,12.035,12.035,12.025,12.06,12.03,12.061,12.071]}]}}]}],"error":null}}\ No newline at end of filediff --git a/tests/fixtures/trader-scanner/symdir/nasdaqlisted.txt b/tests/fixtures/trader-scanner/symdir/nasdaqlisted.txtnew file mode 100644index 0000000..4bfc241--- /dev/null+++ b/tests/fixtures/trader-scanner/symdir/nasdaqlisted.txt@@ -0,0 +1,20 @@+Symbol|Security Name|Market Category|Test Issue|Financial Status|Round Lot Size|ETF|NextShares+AAAP|Pacer Barings CLO Market Flex ETF|G|N|N|100|Y|N+AACG|ATA Creativity Global - American Depositary Shares, each representing two common shares|S|N|D|100|N|N+AACI|Armada Acquisition Corp. III - Class A Ordinary Share|G|N|N|100|N|N+AACIU|Armada Acquisition Corp. III - Units|G|N|N|100|N|N+AACIW|Armada Acquisition Corp. III - Warrant|G|N|N|100|N|N+AACPR|Apogee Acquisition Corp - Rights|G|N|N|100|N|N+AAPL|Apple Inc. - Common Stock|Q|N|N|40|N|N+ARCIU|Archimedes Tech SPAC Partners III Co. - Unit|G|N|N|100|N|N+ARLP|Alliance Resource Partners, L.P. - Common Units Representing Limited Partnership Interests|Q|N|N|100|N|N+CDZIP|Cadiz, Inc. - Depositary Shares|G|N|N|100|N|N+CHTRP|Charter Communications, Inc. - Series A Cumulative Redeemable Preferred Stock|Q|N|N|100|N|N+GENVR|Gen Digital Inc. - Contingent Value Rights|G|N|N|100|N|N+HAVAR|Harvard Ave Acquisition Corporation - Rights that convert on a 1/10th of 1 basis to Class A ordinary Shares|G|N|N|100|N|N+OBAI|Our Bond, Inc. - Common Stock|G|N|D|100|N|N+ORGO|Organogenesis Holdings Inc. - Class A |S|N|N|100|N|N+PFBC|Preferred Bank - Common Stock|Q|N|N|100|N|N+TSLA|Tesla, Inc. - Common Stock|Q|N|N|40|N|N+ZAZZT|Tick Pilot Test Stock Class A Common Stock|G|Y|N|100|N|N+File Creation Time: 1019202610:01|||||||diff --git a/tests/fixtures/trader-scanner/symdir/otherlisted.txt b/tests/fixtures/trader-scanner/symdir/otherlisted.txtnew file mode 100644index 0000000..6cf5348--- /dev/null+++ b/tests/fixtures/trader-scanner/symdir/otherlisted.txt@@ -0,0 +1,20 @@+ACT Symbol|Security Name|Exchange|CQS Symbol|ETF|Round Lot Size|Test Issue|NASDAQ Symbol+A|Agilent Technologies, Inc. Common Stock|N|A|N|100|N|A+AAC.U|Ares Acquisition Corporation III Units, each consisting of one Class A ordinary share and one-tenth of one redeemable warrant|N|AAC.U|N|100|N|AAC=+AAC.W|Ares Acquisition Corporation III Redeemable warrants, each whole warrant exercisable for one Class A ordinary share at an exercise price of $11.50|N|AAC.WS|N|100|N|AAC++ABR$D|Arbor Realty Trust 6.375% Series D Cumulative Redeemable Preferred Stock, Liquidation Preference $25.00 per Share|N|ABRpD|N|100|N|ABR-D+AME|AMETEK, Inc.|N|AME|N|100|N|AME+AMX|America Movil, S.A.B. de C.V. American Depositary Shares (each representing the right to receive twenty (20) Series B Shares|N|AMX|N|100|N|AMX+ATMP|iPath Select MLP ETN|Z|ATMP|N|100|N|ATMP+BEP|Brookfield Renewable Partners L.P. Limited Partnership Units|N|BEP|N|100|N|BEP+BF.B|Brown Forman Inc Class B Common Stock|N|BF.B|N|100|N|BF.B+BHK|Blackrock Core Bond Trust|N|BHK|N|100|N|BHK+BRK.B|Berkshire Hathaway Inc. New Common Stock|N|BRK.B|N|40|N|BRK.B+EAI|Entergy Arkansas, LLC First Mortgage Bonds, 4.875% Series Due September 1, 2066|N|EAI|N|100|N|EAI+GJH|Synthetic Fixed-Income Securities Inc 6.375% (STRATS) Cl A-1|N|GJH|N|100|N|GJH+IRS|IRSA Inversiones Y Representaciones S.A. Global Depositary Shares (Each representing ten shares of Common Stock)|N|IRS|N|100|N|IRS+KO|Coca-Cola Company (The) Common Stock|N|KO|N|100|N|KO+PRT|PermRock Royalty Trust Units of Beneficial Interest|N|PRT|N|100|N|PRT+SPY|State Street SPDR S&P 500 ETF Trust|P|SPY|Y|40|N|SPY+ZZZTX|TXSE Test Stk 5 Common Stock|F|ZZZTX|N|40|Y|ZZZTX+File Creation Time: 1019202610:01||||||diff --git a/tests/fixtures/trader-scanner/wall5m-2026-10-19.json.gz b/tests/fixtures/trader-scanner/wall5m-2026-10-19.json.gznew file mode 100644index 0000000..857b649Binary files /dev/null and b/tests/fixtures/trader-scanner/wall5m-2026-10-19.json.gz differdiff --git a/tests/fixtures/trader-timemachine/TSLA-60d5m.json.gz b/tests/fixtures/trader-timemachine/TSLA-60d5m.json.gznew file mode 100644index 0000000..791c3cfBinary files /dev/null and b/tests/fixtures/trader-timemachine/TSLA-60d5m.json.gz differdiff --git a/tests/test_alerts.py b/tests/test_alerts.pynew file mode 100644index 0000000..f85b498--- /dev/null+++ b/tests/test_alerts.py@@ -0,0 +1,454 @@+import datetime+import gzip+import io+import json+import os+import shutil+import tempfile+import unittest+import urllib.error+from contextlib import redirect_stdout, redirect_stderr++from _load import load, ROOT, FIX++alerts = load("trader-alerts", "alerts")++QDIR = os.path.join(FIX, "trader-alerts")+PLAN = os.path.join(FIX, "trader-budget", "plan-tsla.json")+DT = datetime.datetime+UA = "Mozilla/5.0 (compatible; day-trader-skill/2.0; +https://github.com/Jakeschincariol/day-trader-skill)"++# NYSE holidays as published at https://www.nyse.com/markets/hours-calendars (read 2026-10-13)+NYSE_2026 = ["2026-01-01", "2026-01-19", "2026-02-16", "2026-04-03", "2026-05-25", "2026-06-19",+ "2026-07-03", "2026-09-07", "2026-11-26", "2026-12-25"]+NYSE_2027 = ["2027-01-01", "2027-01-18", "2027-02-15", "2027-03-26", "2027-05-31", "2027-06-18",+ "2027-07-05", "2027-09-06", "2027-11-25", "2027-12-24"]+EARLY = ["2026-11-27", "2026-12-24", "2027-11-26"]+++def ny(text):+ return alerts.parse_now(text)+++def run(argv):+ out, err = io.StringIO(), io.StringIO()+ with redirect_stdout(out), redirect_stderr(err):+ code = alerts.main(argv)+ return code, out.getvalue(), err.getvalue()+++def plan_rules():+ with open(PLAN) as fh:+ return alerts.rules_from_plan(json.load(fh))+++class Calendar(unittest.TestCase):+ def test_holidays_match_the_published_list(self):+ self.assertEqual(sorted(alerts.NYSE_HOLIDAYS), NYSE_2026 + NYSE_2027)+ self.assertEqual(sorted(alerts.NYSE_EARLY_CLOSE), EARLY)+ for d in list(alerts.NYSE_HOLIDAYS) + list(alerts.NYSE_EARLY_CLOSE):+ self.assertLess(datetime.date.fromisoformat(d).weekday(), 5, d)++ def test_daylight_saving_switches(self):+ self.assertEqual(alerts.eastern_offset(DT(2026, 3, 8, 6, 59)), -5)+ self.assertEqual(alerts.eastern_offset(DT(2026, 3, 8, 7, 0)), -4)+ self.assertEqual(alerts.eastern_offset(DT(2026, 11, 1, 5, 59)), -4)+ self.assertEqual(alerts.eastern_offset(DT(2026, 11, 1, 6, 0)), -5)+ self.assertEqual(alerts.eastern_offset(DT(2027, 3, 14, 7, 0)), -4)++ def test_parse_now(self):+ self.assertEqual(ny("2026-10-13T09:30"), DT(2026, 10, 13, 13, 30))+ self.assertEqual(ny("2026-10-19 10:15"), DT(2026, 10, 19, 14, 15))+ self.assertEqual(ny("2026-12-01T09:30"), DT(2026, 12, 1, 14, 30))+ self.assertEqual(ny("2026-10-13T20:00:01Z"), DT(2026, 10, 13, 20, 0, 1))+ with self.assertRaises(alerts.AlertError):+ ny("tomorrow")++ def test_market_status(self):+ st = alerts.market_status(ny("2026-10-13T10:00"))+ self.assertTrue(st["open"])+ self.assertFalse(alerts.market_status(ny("2026-10-13T09:29"))["open"])+ self.assertEqual(alerts.market_status(ny("2026-10-13T09:29"))["next_open"], "2026-10-13 09:30")+ after = alerts.market_status(ny("2026-10-13T16:00"))+ self.assertFalse(after["open"])+ self.assertEqual(after["next_open"], "2026-10-14 09:30")+ july = alerts.market_status(ny("2026-07-03T11:00"))+ self.assertFalse(july["open"])+ self.assertIn("Independence Day", july["reason"])+ self.assertEqual(july["next_open"], "2026-07-06 09:30")+ self.assertTrue(alerts.market_status(ny("2026-11-27T12:59"))["open"])+ self.assertFalse(alerts.market_status(ny("2026-11-27T13:00"))["open"])+ xmas = alerts.market_status(ny("2027-12-24T10:00"))+ self.assertFalse(xmas["open"])+ self.assertEqual(xmas["next_open"], "2027-12-27 09:30")+ self.assertTrue(alerts.market_status(ny("2027-12-31T10:00"))["open"])+ self.assertEqual(alerts.market_status(ny("2026-10-17T10:00"))["reason"], "weekend")+ self.assertFalse(alerts.market_status(ny("2028-03-01T10:00"))["calendar_known"])+++class Quotes(unittest.TestCase):+ def test_yahoo_fixtures(self):+ with open(os.path.join(QDIR, "yahoo-AAPL.json")) as fh:+ q = alerts.parse_yahoo(fh.read(), "AAPL")+ self.assertEqual(q["price"], 341.27)+ self.assertEqual(q["prev_close"], 340.97)+ self.assertEqual(q["time"], "2026-10-13T20:00:01Z")+ with open(os.path.join(QDIR, "yahoo-TSLA.json")) as fh:+ q = alerts.parse_yahoo(fh.read(), "TSLA")+ self.assertEqual((q["price"], q["prev_close"], round(q["open"], 2)), (366.475, 354.72, 357.48))+ self.assertEqual(q["time"], "2026-10-19T14:52:13Z")++ def test_stooq_fixture(self):+ with open(os.path.join(QDIR, "stooq-AAPL.csv")) as fh:+ q = alerts.parse_stooq(fh.read(), "AAPL")+ self.assertEqual(q["price"], 341.27)+ self.assertEqual(q["open"], 344.67)+ with open(os.path.join(QDIR, "stooq-ZZZZ.csv")) as fh:+ with self.assertRaises(alerts.AlertError):+ alerts.parse_stooq(fh.read(), "ZZZZ")++ def test_urls_and_user_agent(self):+ self.assertEqual(alerts.UA, UA)+ self.assertEqual(alerts.stooq_url("BRK.B"), "https://stooq.com/q/l/?s=brk-b.us&f=sd2t2ohlcv&h&e=csv")+ self.assertEqual(alerts.yahoo_url("brk.b"),+ "https://query2.finance.yahoo.com/v8/finance/chart/BRK-B?range=1d&interval=1d")+ self.assertIn("//query1.finance.yahoo.com/", alerts.yahoo_url("TSLA", alerts.YAHOO_HOSTS[1]))++ def test_offline_quotes_and_errors(self):+ q, errors = alerts.get_quotes(["AAPL", "KO", "ZZZZ", "NOPE"], "yahoo", QDIR)+ self.assertEqual(sorted(q), ["AAPL", "KO"])+ self.assertEqual(q["KO"]["price"], 90.11)+ self.assertEqual(len(errors), 2)+ self.assertIn("No data found", errors[0])++ def test_offline_gz(self):+ d = tempfile.mkdtemp()+ try:+ with open(os.path.join(QDIR, "yahoo-TSLA.json"), "rb") as src:+ with gzip.open(os.path.join(d, "yahoo-TSLA.json.gz"), "wb") as dst:+ dst.write(src.read())+ q, errors = alerts.get_quotes(["TSLA"], "yahoo", d)+ self.assertEqual((q["TSLA"]["price"], errors), (366.475, []))+ finally:+ shutil.rmtree(d)+++class FakeNet(object):+ """Stands in for urllib: answers each request with the next status code."""++ def __init__(self, codes, body=None):+ self.codes, self.calls, self.sleeps = list(codes), [], []+ with open(os.path.join(QDIR, "yahoo-TSLA.json")) as fh:+ self.body = body or fh.read()++ def urlopen(self, req, timeout=None):+ self.calls.append((req.full_url.split("/")[2], req.get_header("User-agent")))+ code = self.codes.pop(0)+ if code != 200:+ fp = io.BytesIO(b'{"chart":{"result":null,"error":{"code":"Not Found",'+ b'"description":"No data found, symbol may be delisted"}}}' if code == 404 else b"")+ raise urllib.error.HTTPError(req.full_url, code, "x", {}, fp)+ return io.BytesIO(self.body.encode("utf-8"))+++class Network(unittest.TestCase):+ def setUp(self):+ self.saved = (alerts._urlopen, alerts._sleep)++ def tearDown(self):+ alerts._urlopen, alerts._sleep = self.saved++ def net(self, codes):+ f = FakeNet(codes)+ alerts._urlopen = f.urlopen+ alerts._sleep = f.sleeps.append+ return f++ def hosts(self, f):+ return [h.split(".")[0] for h, _ in f.calls]++ def test_query2_first_with_the_contract_user_agent(self):+ f = self.net([200])+ q, errors = alerts.get_quotes(["TSLA"])+ self.assertEqual((q["TSLA"]["price"], errors), (366.475, []))+ self.assertEqual(f.calls, [("query2.finance.yahoo.com", UA)])++ def test_one_retry_with_a_pause_on_429(self):+ f = self.net([429, 200])+ self.assertEqual(alerts.get_quotes(["TSLA"])[0]["TSLA"]["price"], 366.475)+ self.assertEqual(self.hosts(f), ["query2", "query2"])+ self.assertEqual(f.sleeps, [alerts.BACKOFF])++ def test_falls_back_to_query1_on_429_and_5xx(self):+ f = self.net([429, 429, 200])+ self.assertIn("TSLA", alerts.get_quotes(["TSLA"])[0])+ self.assertEqual(self.hosts(f), ["query2", "query2", "query1"])+ f = self.net([503, 200])+ self.assertIn("TSLA", alerts.get_quotes(["TSLA"])[0])+ self.assertEqual(self.hosts(f), ["query2", "query1"])+ f = self.net([500, 502])+ q, errors = alerts.get_quotes(["TSLA"])+ self.assertEqual(q, {})+ self.assertIn("query1.finance.yahoo.com/v8/finance/chart/TSLA answered HTTP 502", errors[0])++ def test_a_404_is_yahoos_answer_and_a_403_is_not_retried(self):+ f = self.net([404])+ q, errors = alerts.get_quotes(["NOPE"])+ self.assertIn("No data found", errors[0])+ self.assertEqual(self.hosts(f), ["query2"])+ f = self.net([403])+ q, errors = alerts.get_quotes(["TSLA"])+ self.assertIn("HTTP 403", errors[0])+ self.assertEqual(self.hosts(f), ["query2"])++ def test_a_pause_between_tickers(self):+ f = self.net([200, 200])+ alerts.get_quotes(["TSLA", "AAPL"])+ self.assertEqual(f.sleeps, [alerts.PAUSE])+++class Rules(unittest.TestCase):+ def setUp(self):+ self.q, _ = alerts.get_quotes(["AAPL", "BAC", "KO", "TSLA"], "yahoo", QDIR)+ self.open = alerts.market_status(ny("2026-10-13T10:00"))+ self.now = ny("2026-10-13T10:00")++ def at(self, text, rules, state=None, quotes=None):+ now = ny(text)+ return alerts.evaluate(rules, self.q if quotes is None else quotes, alerts.market_status(now),+ state or {}, now)++ def test_a_target_rings_once(self):+ rules = [{"id": "aapl-340", "symbol": "AAPL", "type": "above", "price": 340}]+ rings, st = alerts.evaluate(rules, self.q, self.open, {}, self.now)+ self.assertEqual(len(rings), 1)+ self.assertIn("AAPL is $341.27: at or above your alert level $340", rings[0]["message"])+ rings, st = alerts.evaluate(rules, self.q, self.open, st, self.now)+ self.assertEqual(rings, [])++ def test_stop_and_rearm(self):+ rules = [{"id": "bac-stop", "symbol": "BAC", "type": "stop", "price": 54, "rearm": True}]+ rings, st = alerts.evaluate(rules, self.q, self.open, {}, self.now)+ self.assertIn("your stop $54", rings[0]["message"])+ self.q["BAC"]["price"] = 55.0+ rings, st = alerts.evaluate(rules, self.q, self.open, st, self.now)+ self.assertEqual(rings, [])+ self.assertNotIn("bac-stop", st["rung"])+ self.q["BAC"]["price"] = 53.5+ rings, st = alerts.evaluate(rules, self.q, self.open, st, self.now)+ self.assertEqual(len(rings), 1)++ def test_pct_move_from_previous_close(self):+ big = [{"id": "bac-3", "symbol": "BAC", "type": "pct_move", "pct": 3}]+ self.assertEqual(alerts.evaluate(big, self.q, self.open, {}, self.now)[0], [])+ small = [{"id": "bac-1", "symbol": "BAC", "type": "pct_move", "pct": 1, "direction": "down"}]+ rings, st = alerts.evaluate(small, self.q, self.open, {}, self.now)+ self.assertIn("-1.14%", rings[0]["message"])+ self.assertEqual(alerts.evaluate(small, self.q, self.open, st, self.now)[0], [])+ up = [{"id": "bac-up", "symbol": "BAC", "type": "pct_move", "pct": 1, "direction": "up"}]+ self.assertEqual(alerts.evaluate(up, self.q, self.open, {}, self.now)[0], [])+ tsla = [{"id": "tsla-3", "symbol": "TSLA", "type": "pct_move", "pct": 3}]+ rings, _ = self.at("2026-10-19 10:52", tsla)+ self.assertIn("TSLA moved +3.31% to $366.48 (from $354.72)", rings[0]["message"])++ def test_opening_bell_once_per_trading_day(self):+ rules = [{"id": "bell", "type": "opening_bell"}]+ closed = alerts.market_status(ny("2026-10-13T08:00"))+ self.assertEqual(alerts.evaluate(rules, {}, closed, {}, ny("2026-10-13T08:00"))[0], [])+ rings, st = alerts.evaluate(rules, {}, self.open, {}, self.now)+ self.assertIn("Opening bell", rings[0]["message"])+ self.assertEqual(alerts.evaluate(rules, {}, self.open, st, ny("2026-10-13T11:00"))[0], [])+ nxt = alerts.market_status(ny("2026-10-14T09:31"))+ self.assertEqual(len(alerts.evaluate(rules, {}, nxt, st, ny("2026-10-14T09:31"))[0]), 1)++ def test_the_plan_gives_a_stop_a_target_and_flat_by_close(self):+ rules = plan_rules()+ self.assertEqual([(r["id"], r["type"]) for r in rules],+ [("tsla-plan-stop", "stop"), ("tsla-plan-target", "target"), ("tsla-flat-by", "time")])+ self.assertEqual((rules[0]["price"], rules[1]["price"]), (358.32, 370.04))+ self.assertEqual((rules[2]["at"], rules[2]["label"], rules[2]["before_close"]), ("15:55", "flat by close", True))+ self.assertTrue(all(r["date"] == "2026-10-19" for r in rules))+ rings, st = self.at("2026-10-19 10:52", rules) # the real 10:52 quote, 366.475+ self.assertEqual(rings, [])+ q = json.loads(json.dumps(self.q))+ q["TSLA"]["price"] = 358.10+ rings, st = self.at("2026-10-19 11:30", rules, st, q)+ self.assertEqual([r["id"] for r in rings], ["tsla-plan-stop"])+ self.assertIn("TSLA is $358.10: at or below your stop $358.32 (plan stop: opening-range midpoint)",+ rings[0]["message"])+ q["TSLA"]["price"] = 370.04+ self.assertEqual([r["id"] for r in self.at("2026-10-19 12:00", rules, st, q)[0]], ["tsla-plan-target"])++ def test_flat_by_close_rings_once_per_trading_day(self):+ rules = plan_rules()[2:]+ self.assertEqual(self.at("2026-10-19 15:54", rules)[0], [])+ rings, st = self.at("2026-10-19 15:55", rules)+ self.assertEqual(len(rings), 1)+ self.assertIn("Flat by close: it is 15:55 New York (set for 15:55), the market closes at 16:00", rings[0]["message"])+ self.assertIn("trader-broker flatten --symbol TSLA", rings[0]["message"])+ self.assertEqual(self.at("2026-10-19 15:59", rules, st)[0], [])+ rings, _ = self.at("2026-10-19 16:10", rules)+ self.assertIn("the market has closed", rings[0]["message"])+ self.assertEqual(self.at("2026-10-20 15:56", rules, st)[0], []) # plan rules: their day only++ def test_a_time_alert_moves_with_an_early_close(self):+ rule = [{"id": "flat", "type": "time", "at": "15:55", "label": "flat by close", "before_close": True}]+ self.assertEqual(self.at("2026-11-27 12:54", rule)[0], [])+ rings, _ = self.at("2026-11-27 12:55", rule)+ self.assertIn("set for 12:55), the market closes at 13:00", rings[0]["message"])+ plain = [{"id": "t", "type": "time", "at": "15:55", "label": "check"}]+ self.assertEqual(self.at("2026-11-27 12:55", plain)[0], [])+ self.assertEqual(self.at("2026-10-17 15:56", rule)[0], []) # Saturday: no session+ self.assertEqual(self.at("2026-11-26 15:56", rule)[0], []) # Thanksgiving+ rings, st = self.at("2026-12-01 15:55", rule) # standard time+ self.assertEqual(len(rings), 1)+ self.assertEqual(st["rung"]["flat"], "2026-12-01T20:55:00Z")++ def test_the_example_rules_are_valid(self):+ with open(os.path.join(ROOT, "trader-alerts", "alerts.example.json")) as fh:+ rules = json.load(fh)["rules"]+ for r in rules:+ alerts.validate(r)+ self.assertEqual([r for r in rules if r["id"].startswith("tsla-plan") or r["id"] == "tsla-flat-by"],+ [dict(r, date="2026-10-19") for r in plan_rules()])++ def test_bad_rules(self):+ with self.assertRaises(alerts.AlertError):+ alerts.evaluate([{"id": "x", "type": "moon"}], {}, self.open, {}, self.now)+ with self.assertRaises(alerts.AlertError):+ alerts.evaluate([{"id": "x", "type": "above", "symbol": "AAPL"}], {}, self.open, {}, self.now)+ with self.assertRaises(alerts.AlertError):+ alerts.evaluate([{"id": "x", "type": "time", "at": "4pm"}], {}, self.open, {}, self.now)+ with self.assertRaises(alerts.AlertError):+ alerts.rules_from_plan({"symbol": "TSLA", "stop": 358.32})+++class Cli(unittest.TestCase):+ def setUp(self):+ self.d = tempfile.mkdtemp()+ self.rules = os.path.join(self.d, "alerts.json")+ self.state = os.path.join(self.d, "state", "alerts.json")+ self.prices = os.path.join(self.d, "prices.json")++ def tearDown(self):+ shutil.rmtree(self.d)++ def check(self, now):+ return run(["check", "--rules", self.rules, "--state", self.state, "--prices-out", self.prices,+ "--offline", QDIR, "--now", now])++ def test_the_reel_trade_from_the_plan(self):+ code, text, _ = run(["add", "--from-plan", "--plan", PLAN, "--rules", self.rules, "--state", self.state,+ "--config", os.path.join(self.d, "none")])+ self.assertEqual(code, 0)+ self.assertIn("Added tsla-flat-by", text)+ self.assertEqual(run(["add", "--rules", self.rules, "--opening-bell"])[0], 0)++ code, text, _ = self.check("2026-10-19 10:52")+ self.assertEqual(code, 0) # the opening bell rings first+ code, text, _ = self.check("2026-10-19 10:53")+ self.assertEqual(code, 1)+ self.assertIn("Nothing hit. 4 rule(s) watched today, TSLA $366.48.", text)+ with open(self.prices) as fh:+ doc = json.load(fh)+ self.assertEqual(doc["prices"], {"TSLA": 366.475})+ self.assertEqual(doc["detail"]["TSLA"]["time"], "2026-10-19T14:52:13Z")+ self.assertEqual(doc["detail"]["TSLA"]["fetched"], "2026-10-19T14:53:00Z")++ code, text, _ = self.check("2026-10-19 15:55")+ self.assertEqual(code, 0)+ self.assertIn("ALERT Flat by close", text)+ self.assertIn("not an order", text)+ self.assertEqual(self.check("2026-10-19 15:57")[0], 1)+ code, text, _ = self.check("2026-10-20 10:00")+ self.assertIn("ALERT Opening bell", text)+ code, text, _ = self.check("2026-10-20 10:05")+ self.assertIn("Nothing hit. 1 rule(s) watched today.", text)++ # a new plan replaces the plan rules and re-arms them+ code, text, _ = run(["add", "--from-plan", "--plan", PLAN, "--rules", self.rules, "--state", self.state])+ with open(self.rules) as fh:+ ids = [r["id"] for r in json.load(fh)["rules"]]+ self.assertEqual(sorted(ids), ["opening-bell", "tsla-flat-by", "tsla-plan-stop", "tsla-plan-target"])+ with open(self.state) as fh:+ self.assertNotIn("tsla-flat-by", json.load(fh)["rung"])++ def test_the_v1_portfolio_evening_and_morning(self):+ for args in (["--opening-bell"], ["--symbol", "AAPL", "--above", "350"], ["--symbol", "BAC", "--stop", "50"]):+ code, _, _ = run(["add", "--rules", self.rules] + args)+ self.assertEqual(code, 0)+ code, _, err = run(["add", "--rules", self.rules, "--symbol", "AAPL", "--above", "350"])+ self.assertEqual(code, 1)+ self.assertIn("already exists", err)++ code, text, _ = self.check("2026-10-13T20:00")+ self.assertEqual(code, 1)+ self.assertIn("Nothing hit", text)+ with open(self.prices) as fh:+ doc = json.load(fh)+ self.assertEqual(doc["prices"], {"AAPL": 341.27, "BAC": 53.96})++ code, text, _ = self.check("2026-10-14T09:31")+ self.assertEqual(code, 0)+ self.assertIn("ALERT Opening bell", text)+ code, text, _ = self.check("2026-10-14T09:45")+ self.assertEqual(code, 1)++ code, text, _ = run(["list", "--rules", self.rules, "--state", self.state])+ self.assertIn("rang", text)+ self.assertEqual(run(["reset", "opening-bell", "--state", self.state])[0], 0)+ self.assertEqual(run(["reset", "opening-bell", "--state", self.state])[0], 1)++ def test_add_time_and_target(self):+ code, text, _ = run(["add", "--rules", self.rules, "--at", "15:55", "--label", "flat by close",+ "--before-close", "--symbol", "tsla"])+ self.assertEqual(code, 0)+ code, text, _ = run(["add", "--rules", self.rules, "--symbol", "TSLA", "--target", "370.04",+ "--date", "2026-10-19"])+ self.assertEqual(code, 0)+ with open(self.rules) as fh:+ rules = json.load(fh)["rules"]+ self.assertEqual(rules[0], {"id": "time-1555", "type": "time", "at": "15:55", "label": "flat by close",+ "symbol": "TSLA", "before_close": True})+ self.assertEqual(rules[1], {"id": "tsla-target-370.04", "symbol": "TSLA", "type": "target",+ "price": 370.04, "date": "2026-10-19"})+ self.assertEqual(run(["add", "--rules", self.rules, "--at", "4pm"])[0], 1)+ code, _, err = run(["add", "--rules", self.rules, "--from-plan", "--plan", os.path.join(self.d, "none")])+ self.assertEqual(code, 1)+ self.assertIn("no plan", err)++ def test_quote_write_merges(self):+ code, text, _ = run(["quote", "AAPL", "KO", "--offline", QDIR, "--write", self.prices,+ "--now", "2026-10-13T20:00:01Z"])+ self.assertEqual(code, 0)+ self.assertIn("AAPL $341.27", text)+ self.assertIn("delayed", text)+ run(["quote", "BAC", "--offline", QDIR, "--write", self.prices])+ with open(self.prices) as fh:+ doc = json.load(fh)+ self.assertEqual(sorted(doc["prices"]), ["AAPL", "BAC", "KO"])+ self.assertEqual(doc["detail"]["KO"]["prev_close"], 89.79)+ self.assertEqual(doc["detail"]["KO"]["fetched"], "2026-10-13T20:00:01Z")++ def test_quote_holdings_from_portfolio_and_plan(self):+ pf = os.path.join(self.d, "portfolio.json")+ with open(pf, "w") as fh:+ json.dump({"cash": 0, "positions": [{"ticker": "KO", "shares": 1}]}, fh)+ code, text, _ = run(["quote", "--holdings", "--portfolio", pf, "--plan", PLAN, "--offline", QDIR, "--json"])+ self.assertEqual(code, 0)+ self.assertEqual(sorted(json.loads(text)["quotes"]), ["KO", "TSLA"])++ def test_clock_exit_codes(self):+ self.assertEqual(run(["clock", "--now", "2026-10-19 10:15"])[0], 0)+ code, text, _ = run(["clock", "--now", "2026-12-25T10:00"])+ self.assertEqual(code, 1)+ self.assertIn("Christmas Day", text)++ def test_check_without_rules(self):+ code, _, err = run(["check", "--rules", self.rules, "--offline", QDIR])+ self.assertEqual(code, 1)+ self.assertIn("no rules", err)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_analyst.py b/tests/test_analyst.pynew file mode 100644index 0000000..b864b56--- /dev/null+++ b/tests/test_analyst.py@@ -0,0 +1,163 @@+import io+import json+import os+import tempfile+import unittest+from contextlib import redirect_stderr, redirect_stdout++from _load import FIX, load++facts = load("trader-analyst", "facts")+DIR = os.path.join(FIX, "trader-analyst")+++def companyfacts(cik):+ with open(os.path.join(DIR, "companyfacts-CIK%s.json" % cik)) as fh:+ return json.load(fh)+++def run(args):+ out, err = io.StringIO(), io.StringIO()+ with redirect_stdout(out), redirect_stderr(err):+ code = facts.main(args)+ return code, out.getvalue(), err.getvalue()+++class Apple(unittest.TestCase):+ def setUp(self):+ self.r = facts.analyse(companyfacts("0000320193"), quarters=8)++ def test_latest_quarter(self):+ q = self.r["rows"][0]+ self.assertEqual(q["end"], "2026-06-27")+ self.assertEqual(q["fiscal"], "Q3 2026")+ self.assertEqual(q["revenue"], 109417000000)+ self.assertEqual(q["net_income"], 29789000000)+ self.assertEqual(q["eps_diluted"], 2.02)+ self.assertEqual(q["revenue_yoy"], 16.4) # vs 94,036 a year earlier+ self.assertEqual(q["eps_yoy"], 28.7) # vs 1.57+ self.assertEqual(q["gross_margin"], 50.1)+ self.assertEqual(q["operating_margin"], 32.6)+ self.assertEqual(q["net_margin"], 27.2)+ self.assertFalse(q["derived"])++ def test_fiscal_labels_come_from_the_first_filing(self):+ labels = [r["fiscal"] for r in self.r["rows"][:6]]+ self.assertEqual(labels, ["Q3 2026", "Q2 2026", "Q1 2026", "Q4 2025", "Q3 2025", "Q2 2025"])++ def test_q4_is_derived_from_the_10k(self):+ q4 = next(r for r in self.r["rows"] if r["end"] == "2025-09-27")+ self.assertTrue(q4["derived"])+ # FY2025 416,161 minus Q1 124,300, Q2 95,359, Q3 94,036+ self.assertEqual(q4["revenue"], 102466000000)+ self.assertEqual(q4["revenue_yoy"], 7.9)++ def test_trailing_twelve_months(self):+ self.assertEqual(self.r["ttm"]["revenue"], 466823000000)+ self.assertEqual(self.r["ttm"]["net_income"], 128930000000)+ self.assertEqual(self.r["ttm"]["eps_diluted"], 8.71)++ def test_what_changed_in_words(self):+ lines = facts.changes(self.r)+ self.assertIn("revenue $109.42B (+16.4% vs a year earlier)", lines[0])+ self.assertIn("diluted EPS $2.02 (+28.7%)", lines[0])+ self.assertTrue(any(l.startswith("Gross margin 50.1% (+0.8 points") for l in lines))++ def test_restated_values_win_but_labels_stay(self):+ facts_ = [+ {"start": "2025-01-01", "end": "2025-03-31", "val": 100, "fy": 2025, "fp": "Q1",+ "form": "10-Q", "filed": "2025-05-01", "accn": "a"},+ {"start": "2025-01-01", "end": "2025-03-31", "val": 90, "fy": 2026, "fp": "Q1",+ "form": "10-Q", "filed": "2026-05-01", "accn": "b"},+ {"start": "2025-01-01", "end": "2025-03-31", "val": 1, "fy": 2025, "fp": "Q1",+ "form": "8-K", "filed": "2025-04-20", "accn": "c"},+ ]+ q = facts.quarterly(facts_)+ self.assertEqual(q["2025-03-31"]["value"], 90)+ self.assertEqual((q["2025-03-31"]["fy"], q["2025-03-31"]["fp"]), (2025, "Q1"))+++class Filings(unittest.TestCase):+ def test_latest_10q_and_earnings_press_release(self):+ with open(os.path.join(DIR, "submissions-CIK0000320193.json")) as fh:+ sub = json.load(fh)+ f = facts.latest_filings(sub, "0000320193", facts.Fetcher(offline=DIR))+ self.assertEqual(f["report"]["form"], "10-Q")+ self.assertEqual(f["report"]["period"], "2026-06-27")+ self.assertTrue(f["report"]["url"].endswith("/000032019326000020/aapl-20260627.htm"))+ e = f["earnings_8k"]+ self.assertEqual(e["filed"], "2026-07-30")+ self.assertEqual(e["exhibit"], "https://www.sec.gov/Archives/edgar/data/320193/"+ "000032019326000018/a8-kex991q3202606272026.htm")++ def test_exhibit_names_seen_on_edgar(self):+ pick = facts.exhibit_name+ self.assertEqual(pick(["axp-20260724.htm", "q226exhibit991.htm", "q226exhibit992.htm",+ "R1.htm"], "axp-20260724.htm"), "q226exhibit991.htm")+ self.assertEqual(pick(["goog-20260722.htm", "googexhibit991q22026.htm"],+ "goog-20260722.htm"), "googexhibit991q22026.htm")+ self.assertEqual(pick(["a2026q2earningsreleaseex-9.htm", "ko-20260728.htm"],+ "ko-20260728.htm"), "a2026q2earningsreleaseex-9.htm")+ self.assertEqual(pick(["bac-06302026ex993.htm", "bac-06302026ex991.htm"]),+ "bac-06302026ex991.htm")+ self.assertIsNone(pick(["only-8k.htm"], "only-8k.htm"))+++class LaggingData(unittest.TestCase):+ def test_says_when_sec_facts_trail_a_filed_10q(self):+ code, out, err = run(["KO", "--offline", DIR])+ self.assertEqual(code, 0, err)+ self.assertIn("COCA COLA CO (KO)", out)+ self.assertIn("NOTE: SEC's XBRL facts stop at 2026-04-03, but a 10-Q for the period "+ "ending 2026-07-03 was filed 2026-07-29", out)++ def test_one_offs_are_flagged(self):+ result = {"rows": [+ {"end": "2026-06-30", "derived": False, "revenue": 100.0, "net_income": 90.0,+ "operating_income": 30.0, "eps_diluted": 1.0, "revenue_yoy": 10.0,+ "net_income_yoy": 200.0, "eps_yoy": 200.0, "gross_margin": None,+ "operating_margin": 30.0, "net_margin": 90.0}]}+ self.assertTrue(any("above operating income" in l for l in facts.changes(result)))+++class Cli(unittest.TestCase):+ def test_metrics_file_for_the_screener(self):+ with tempfile.TemporaryDirectory() as tmp:+ path = os.path.join(tmp, "trader", "metrics.json")+ code, out, err = run(["AAPL", "KO", "--offline", DIR, "--metrics", path])+ self.assertEqual(code, 0, err)+ with open(path) as fh:+ data = json.load(fh)+ rows = {r["ticker"]: r for r in data["companies"]}+ self.assertEqual(sorted(rows), ["AAPL", "KO"])+ self.assertEqual(rows["AAPL"]["eps_ttm"], 8.71)+ self.assertEqual(rows["AAPL"]["revenue_growth_yoy"], 16.4)+ self.assertEqual(rows["KO"]["period_end"], "2026-04-03")+ self.assertIn("wrote", out)+ self.assertNotIn(chr(0x2014), out)++ def test_unknown_ticker_and_no_user_agent(self):+ code, _, err = run(["ZZZZ", "--offline", DIR])+ self.assertEqual(code, 2)+ self.assertIn("no SEC CIK for ZZZZ", err)+ old = os.environ.pop("SEC_USER_AGENT", None)+ try:+ code, _, err = run(["AAPL", "--config", "/nonexistent.json"])+ self.assertEqual(code, 2)+ self.assertIn("User-Agent", err)+ self.assertIsNone(facts.user_agent("Your Name [email protected]"))+ finally:+ if old is not None:+ os.environ["SEC_USER_AGENT"] = old++ def test_json_output(self):+ code, out, err = run(["AAPL", "--offline", DIR, "--json", "--quarters", "4"])+ self.assertEqual(code, 0, err)+ data = json.loads(out)+ self.assertEqual(len(data[0]["result"]["rows"]), 4)+ self.assertEqual(data[0]["result"]["concepts"]["revenue"],+ ["RevenueFromContractWithCustomerExcludingAssessedTax"])+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_broker.py b/tests/test_broker.pynew file mode 100644index 0000000..eae8dc4--- /dev/null+++ b/tests/test_broker.py@@ -0,0 +1,307 @@+import io+import json+import os+import shutil+import tempfile+import unittest+from contextlib import redirect_stdout, redirect_stderr++from _load import load, ROOT, FIX++ticket = load("trader-broker", "ticket")+check = load("trader-risk", "check")++CFG_PATH = os.path.join(ROOT, "trader-budget", "config.example.json")+ORDERS_PATH = os.path.join(FIX, "trader-risk", "orders-tsla.json")+PLAN_PATH = os.path.join(FIX, "trader-budget", "plan-tsla.json")+NOW = "2026-10-19 10:15"+TODAY = "2026-10-19"+AAPL = {"symbol": "AAPL", "side": "buy", "notional": "1250", "type": "market", "time_in_force": "day"}+BATCH = ["AAPL", "AXP", "GOOGL", "KO", "BAC"]+TSLA_CALL = {"symbol": "TSLA", "side": "buy", "qty": "8", "type": "market", "time_in_force": "day",+ "order_class": "bracket", "take_profit_limit_price": "370.04", "stop_loss_stop_price": "358.32"}+TSLA_PLAIN = ("BUY 8 TSLA, market, good for today / stop-loss 358.32 / take-profit 370.04 / max loss about "+ "$46.88 if the stop fills at 358.32 (it can fill worse in a fast market)")+++def tsla(**over):+ with open(ORDERS_PATH) as fh:+ o = json.load(fh)["orders"][0]+ o.update(over)+ return o+++def run(argv):+ out, err = io.StringIO(), io.StringIO()+ with redirect_stdout(out), redirect_stderr(err):+ code = ticket.main(argv)+ return code, out.getvalue(), err.getvalue()+++class ExplicitYes(unittest.TestCase):+ def yes(self, reply, order=AAPL, batch=BATCH):+ return ticket.parse_yes(reply, order, batch)[0]++ def test_plain_yes_counts(self):+ for r in ("yes", "Yes.", "YES", "y", "yes place it", "Yes, buy it", "yes AAPL", "yes $1,250 of AAPL",+ "yes 1250"):+ self.assertTrue(self.yes(r), r)++ def test_anything_else_does_not(self):+ for r in ("", "sure", "ok", "okay", "go", "do it", "yeah", "yep", "absolutely", "send it",+ "yes to all", "yes, all of them", "yes to the rest", "yes both",+ "yes AXP", "yes 1000", "yes but make it 1000", "yes?", "no", "not yes",+ "yes, wait", "yes if it is under 340"):+ self.assertFalse(self.yes(r), r)++ def test_amount_must_match_this_order(self):+ sell = {"symbol": "KO", "side": "sell", "qty": "3", "type": "market", "time_in_force": "day"}+ self.assertTrue(self.yes("yes sell 3 KO", sell))+ self.assertFalse(self.yes("yes sell 4", sell))++ def test_a_bracket_yes(self):+ o = tsla()+ for r in ("yes", "yes 8 TSLA", "yes 358.32", "yes max loss 46.88", "yes target 370.04"):+ self.assertTrue(self.yes(r, o, ["TSLA"]), r)+ for r in ("yes 9", "yes 10 TSLA", "yes but stop at 357", "yes, stop 358.32", "yes AAPL", "sure"):+ self.assertFalse(self.yes(r, o, ["TSLA", "AAPL"]), r)+++class TicketShape(unittest.TestCase):+ def test_tool_input_is_the_alpaca_call(self):+ o = dict(AAPL, why="from a list")+ self.assertEqual(ticket.tool_input(o), AAPL)+ self.assertEqual(ticket.tool_input({"symbol": "KO", "side": "buy", "qty": 3, "type": "limit",+ "limit_price": 89.5, "time_in_force": "day"}),+ {"symbol": "KO", "side": "buy", "qty": "3", "type": "limit", "limit_price": "89.5",+ "time_in_force": "day"})++ def test_the_bracket_call_leaves_out_why_and_plan(self):+ self.assertEqual(ticket.tool_input(tsla()), TSLA_CALL)+ self.assertEqual(ticket.fingerprint(tsla()), ticket.fingerprint(TSLA_CALL))++ def test_plain_english(self):+ self.assertEqual(ticket.plain(AAPL), "BUY $1,250 of AAPL, market order, good for today")+ self.assertEqual(ticket.plain({"symbol": "KO", "side": "sell", "qty": "1", "type": "limit",+ "limit_price": "95", "time_in_force": "gtc"}),+ "SELL 1 share of KO, limit order at $95, good until canceled")+ self.assertEqual(ticket.plain(tsla()), TSLA_PLAIN)+ lim = tsla(type="limit", limit_price="364.00")+ self.assertEqual(ticket.plain(lim).split(" / ")[0], "BUY 8 TSLA, limit 364.00, good for today")+ self.assertEqual(ticket.max_loss(lim), (45.44, 358.32))+ no_plan = dict(TSLA_CALL)+ self.assertEqual(ticket.max_loss(no_plan), (None, 358.32))+++class DesktopConfig(unittest.TestCase):+ def test_example_is_paper_with_placeholder_keys(self):+ with open(os.path.join(ROOT, "trader-broker", "claude_desktop_config.example.json")) as fh:+ server = json.load(fh)["mcpServers"]["alpaca"]+ self.assertEqual((server["command"], server["args"]), ("uvx", ["alpaca-mcp-server"]))+ self.assertEqual(server["env"]["ALPACA_PAPER_TRADE"], "true")+ for k in ("ALPACA_API_KEY", "ALPACA_SECRET_KEY"):+ self.assertIn("NEVER_IN_CHAT", server["env"][k])+++class Flow(unittest.TestCase):+ def setUp(self):+ self.d = tempfile.mkdtemp()+ self.orders = os.path.join(self.d, "orders.json")+ shutil.copy(ORDERS_PATH, self.orders)+ self.cfg = os.path.join(self.d, "config.json")+ shutil.copy(CFG_PATH, self.cfg)+ self.risk = os.path.join(self.d, "state", "risk.json")+ self.state = os.path.join(self.d, "state", "broker.json")+ self.pf = os.path.join(self.d, "portfolio.json")+ self.none = os.path.join(self.d, "none")++ def tearDown(self):+ shutil.rmtree(self.d)++ def args(self, *extra, **kw):+ return list(extra) + ["--orders", self.orders, "--config", self.cfg, "--risk", self.risk,+ "--state", self.state, "--now", kw.get("now", NOW)]++ def run_risk(self, now=NOW):+ with redirect_stdout(io.StringIO()):+ return check.main(["--orders", self.orders, "--config", self.cfg, "--portfolio", self.pf,+ "--prices", self.none, "--state", self.state, "--now", now, "--out", self.risk])++ def state_doc(self):+ with open(self.state) as fh:+ return json.load(fh)++ def test_nothing_is_ready_before_the_risk_check(self):+ code, text, _ = run(self.args("show"))+ self.assertEqual(code, 1)+ self.assertIn("NOT READY", text)+ self.assertNotIn("Reply \"yes\"", text)+ code, _, err = run(self.args("approve", "--index", "1", "--reply", "yes"))+ self.assertEqual(code, 1)+ self.assertIn("not ready", err)++ def test_the_full_two_yes_flow(self):+ self.assertEqual(self.run_risk(), 0)+ code, text, _ = run(self.args("show", "--index", "1"))+ self.assertEqual(code, 0)+ self.assertIn("ORDER 1 of 1, PAPER account, Alpaca", text)+ for part in TSLA_PLAIN.split(" / "):+ self.assertIn(" " + part + "\n", text)+ self.assertIn("READY: trader-risk PASS", text)+ self.assertIn('"order_class": "bracket"', text)+ self.assertIn('"stop_loss_stop_price": "358.32"', text)+ self.assertNotIn('"plan"', text)+ self.assertNotIn('"why"', text)+ self.assertIn("Allow once", text)++ code, text, _ = run(self.args("approve", "--index", "1", "--reply", "sure"))+ self.assertEqual(code, 1)+ self.assertIn("Not recorded", text)+ self.assertFalse(os.path.exists(self.state))++ code, text, _ = run(self.args("approve", "--index", "1", "--reply", "yes"))+ self.assertEqual(code, 0)+ self.assertIn("place_stock_order", text)+ self.assertEqual(json.loads(text[text.index("{"):text.rindex("}") + 1]), TSLA_CALL)+ code, _, err = run(self.args("approve", "--index", "1", "--reply", "yes"))+ self.assertEqual(code, 1)+ self.assertIn("APPROVED", err)++ code, text, _ = run(self.args("result", "--index", "1", "--status", "placed", "--broker-id", "abc123",+ "--filled-qty", "8", "--filled-price", "364.20", "--portfolio", self.pf,+ now="2026-10-19 10:16"))+ self.assertEqual(code, 0)+ st = self.state_doc()+ self.assertEqual([r["status"] for r in st["orders"]], ["approved", "placed", "filled"])+ appr, plc = st["orders"][0], st["orders"][1]+ self.assertEqual((appr["reply"], appr["kind"], appr["max_loss"], appr["date"]), ("yes", "entry", 46.88, TODAY))+ self.assertEqual(appr["at"], "2026-10-19T10:15:00-04:00")+ self.assertEqual((plc["broker_order_id"], plc["max_loss"], plc["kind"]), ("abc123", 46.88, "entry"))+ with open(self.pf) as fh:+ pf = json.load(fh)+ self.assertEqual(pf["cash"], 2086.4)+ self.assertEqual(pf["positions"][0]["shares"], 8)++ code, text, _ = run(self.args("show", "--index", "1"))+ self.assertIn("DONE: placed", text)+ code, text, _ = run(["log", "--state", self.state, "--now", NOW])+ self.assertIn("1 placed today", text)+ self.assertIn("max loss $46.88", text)++ # trader-risk now counts it: a second TSLA buy today is a duplicate, and $46.88 is used+ res = check.check([tsla()], {"budget": 5000}, state=st, now=check.parse_now("2026-10-19 10:30"))+ self.assertIn("already placed today", " ".join(res["results"][0]["reasons"]))+ self.assertEqual((res["today"]["entries_placed"], res["today"]["loss_at_risk"]), (1, 46.88))++ def test_flatten_by_the_close(self):+ self.run_risk()+ run(self.args("approve", "--index", "1", "--reply", "yes"))+ run(self.args("result", "--index", "1", "--status", "placed", "--broker-id", "abc",+ "--filled-qty", "8", "--filled-price", "364.20", "--portfolio", self.pf))+ late = "2026-10-19 15:55"+ code, text, _ = run(["flatten", "--symbol", "TSLA", "--orders", self.orders, "--portfolio", self.pf,+ "--plan", PLAN_PATH, "--config", self.cfg, "--now", late])+ self.assertEqual(code, 0)+ self.assertIn("SELL 8 shares of TSLA, market order, good for today (flat by 15:55 New York)", text)+ self.assertIn("replaced 1 earlier proposal", text)+ self.assertIn("cancel_order_by_id", text)+ with open(self.orders) as fh:+ doc = json.load(fh)+ self.assertEqual(ticket.tool_input(doc["orders"][0]),+ {"symbol": "TSLA", "side": "sell", "qty": "8", "type": "market", "time_in_force": "day"})+ self.assertEqual(self.run_risk(now=late), 0) # after the 15:30 entry cutoff: an exit still passes+ with open(self.risk) as fh:+ self.assertEqual(json.load(fh)["results"][0]["kind"], "exit")+ code, text, _ = run(self.args("show", now=late))+ self.assertEqual(code, 0)+ self.assertIn("READY", text)+ self.assertEqual(run(self.args("approve", "--index", "1", "--reply", "yes sell 8 TSLA", now=late))[0], 0)+ code, _, _ = run(self.args("result", "--index", "1", "--status", "placed", "--filled-qty", "8",+ "--filled-price", "366.10", "--portfolio", self.pf, now="2026-10-19 15:56"))+ self.assertEqual(code, 0)+ with open(self.pf) as fh:+ pf = json.load(fh)+ self.assertEqual((pf["cash"], pf["positions"]), (5015.2, []))+ self.assertEqual(check.day_trades(self.state_doc(), TODAY), (1, ["2026-10-19 TSLA"]))+ code, _, err = run(["flatten", "--symbol", "TSLA", "--orders", self.orders, "--portfolio", self.pf,+ "--now", late])+ self.assertEqual(code, 1)+ self.assertIn("nothing to flatten", err)++ def test_flatten_with_the_broker_qty(self):+ code, text, _ = run(["flatten", "--symbol", "tsla", "--qty", "8", "--orders", self.orders,+ "--portfolio", self.none, "--plan", self.none, "--config", self.cfg, "--now", NOW])+ self.assertEqual(code, 0)+ self.assertNotIn("Check it against get_open_position", text)+ self.assertEqual(run(["flatten", "--symbol", "TSLA", "--qty", "0", "--orders", self.orders])[0], 1)++ def test_an_edited_order_is_not_ready(self):+ self.run_risk()+ with open(self.orders) as fh:+ doc = json.load(fh)+ doc["orders"][0]["qty"] = "9"+ with open(self.orders, "w") as fh:+ json.dump(doc, fh)+ code, text, _ = run(self.args("show", "--index", "1"))+ self.assertEqual(code, 1)+ self.assertIn("was not in the last risk check", text)++ def test_yesterdays_check_does_not_count(self):+ self.run_risk(now="2026-10-16 10:15")+ code, text, _ = run(self.args("show", "--index", "1"))+ self.assertIn("not today", text)++ def test_blocked_orders_are_never_ready(self):+ self.assertEqual(self.run_risk(now="2026-10-19 09:40"), 1)+ code, text, _ = run(self.args("show", "--index", "1", now="2026-10-19 09:40"))+ self.assertIn("BLOCKED by trader-risk: window: no new entries before 09:45", text)+ code, _, _ = run(self.args("approve", "--index", "1", "--reply", "yes", now="2026-10-19 09:40"))+ self.assertEqual(code, 1)++ def test_result_needs_an_approval_and_decline_is_logged(self):+ self.run_risk()+ code, _, err = run(self.args("result", "--index", "1", "--status", "placed"))+ self.assertEqual(code, 1)+ self.assertIn("no yes recorded", err)+ code, text, _ = run(self.args("decline", "--index", "1", "--reply", "no thanks"))+ self.assertEqual(code, 0)+ code, text, _ = run(self.args("show", "--index", "1"))+ self.assertIn("DONE: declined", text)++ def test_ibkr_tickets_send_the_final_yes_to_ibkr(self):+ with open(self.cfg) as fh:+ c = json.load(fh)+ c["broker"] = "ibkr"+ with open(self.cfg, "w") as fh:+ json.dump(c, fh)+ self.run_risk()+ code, text, _ = run(self.args("show", "--index", "1"))+ self.assertIn("Interactive Brokers", text)+ self.assertIn("after you approve it there", text)+ self.assertNotIn("place_stock_order", text)++ def test_fill_sell_relieves_the_oldest_lot(self):+ pf = {"cash": 0, "positions": [{"ticker": "KO", "shares": 3, "lots": [+ {"id": "KO-1", "date": "2025-01-02", "shares": 2, "cost": 120.0},+ {"id": "KO-2", "date": "2026-01-02", "shares": 1, "cost": 70.0}]}]}+ with open(self.pf, "w") as fh:+ json.dump(pf, fh)+ code, text, _ = run(["fill", "--symbol", "KO", "--side", "sell", "--qty", "2.5", "--price", "90",+ "--date", TODAY, "--portfolio", self.pf, "--config", self.cfg, "--state", self.state])+ self.assertEqual(code, 0)+ with open(self.pf) as fh:+ pf = json.load(fh)+ self.assertEqual(pf["cash"], 225.0)+ lots = pf["positions"][0]["lots"]+ self.assertEqual([l["id"] for l in lots], ["KO-2"])+ self.assertEqual(lots[0]["shares"], 0.5)+ self.assertEqual(lots[0]["cost"], 35.0)+ self.assertEqual(self.state_doc()["orders"][-1]["status"], "filled")+ code, _, err = run(["fill", "--symbol", "KO", "--side", "sell", "--qty", "5", "--price", "90",+ "--portfolio", self.pf, "--config", self.cfg, "--state", self.state])+ self.assertEqual(code, 1)+ self.assertNotIn("Traceback", err)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_budget.py b/tests/test_budget.pynew file mode 100644index 0000000..8e85faa--- /dev/null+++ b/tests/test_budget.py@@ -0,0 +1,374 @@+import io+import json+import os+import tempfile+import unittest+from contextlib import redirect_stdout, redirect_stderr++from _load import load, ROOT, FIX++size = load("trader-budget", "size")++CFG = os.path.join(ROOT, "trader-budget", "config.example.json")+PLAN = os.path.join(FIX, "trader-budget", "plan-tsla.json")+TARGETS = os.path.join(ROOT, "trader-budget", "targets.example.json")+TOP5 = os.path.join(FIX, "trader-budget", "berkshire-q2-2026-top5.json")+NOW = "2026-10-19 10:15"+TODAY = "2026-10-19"+REEL_V1 = {"AAPL": 1250, "AXP": 1119, "GOOGL": 823, "KO": 708, "BAC": 600}+PRICES = {"AAPL": 341.27, "AXP": 309.84, "GOOGL": 353.78, "KO": 90.11, "BAC": 53.96}+# the contract's v2 config, key for key+CONTRACT_CFG = {+ "budget": 5000, "cash_buffer_pct": 10, "max_position_pct": 75, "max_order_usd": 4000, "min_order_usd": 5,+ "max_loss_per_trade_usd": 50, "max_daily_loss_usd": 150, "max_trades_per_day": 3, "max_orders_per_day": 10,+ "min_reward_risk": 1.0, "require_stop": True,+ "no_entries_before": "09:45", "no_entries_after": "15:30", "flat_by": "15:55",+ "fractional": False, "broker": "alpaca", "paper": True, "blocked": [],+ "allow_options": False, "allow_margin": False, "allow_short": False, "pdt_guard": False,+ "sec_user_agent": "Your Name [email protected]",+}+# v1's rules, for the weights mode tests+V1 = {"budget": 5000, "cash_buffer_pct": 10, "max_position_pct": 25, "max_order_usd": 2000, "min_order_usd": 5,+ "fractional": True, "paper": True, "blocked": []}+++def cfg(**over):+ with open(CFG) as fh:+ c = json.load(fh)+ c.update(over)+ return c+++def v1(**over):+ c = dict(V1)+ c.update(over)+ return c+++def plan(**over):+ with open(PLAN) as fh:+ p = json.load(fh)+ p.update(over)+ return p+++def rows(path):+ with open(path) as fh:+ return size.parse_weights(json.load(fh))+++def dollars(result):+ return {p["ticker"]: p["dollars"] for p in result["positions"]}+++def run(argv):+ out, err = io.StringIO(), io.StringIO()+ with redirect_stdout(out), redirect_stderr(err):+ code = size.main(argv)+ return code, out.getvalue(), err.getvalue()+++def prices_doc(price, quote_time="2026-10-19T14:52:13Z"):+ return {"as_of": quote_time, "source": "yahoo", "prices": {"TSLA": price},+ "detail": {"TSLA": {"prev_close": 354.72, "time": quote_time, "source": "yahoo"}}}+++class TheReel(unittest.TestCase):+ """$5,000, 10% buffer, $50 max loss, TSLA risk 5.86 -> 8 shares, $2,913.44, max loss $46.88."""++ def test_config_example_is_the_contract(self):+ with open(CFG) as fh:+ self.assertEqual(json.load(fh), CONTRACT_CFG)++ def test_tsla_is_8_shares_bound_by_the_max_loss(self):+ s = size.size_trade(plan(), cfg(), today=TODAY)+ self.assertEqual(s["qty"], 8)+ self.assertEqual(s["bound_by"], "max loss")+ self.assertEqual(s["risk_per_share"], 5.86)+ self.assertEqual(s["cost"], 2913.44)+ self.assertEqual(s["max_loss"], 46.88)+ self.assertEqual(s["reward_risk"], 1.0)+ self.assertEqual(s["cash_buffer"], 500)+ self.assertEqual([(l["name"], l["shares"]) for l in s["limits"]],+ [("max loss", 8), ("position cap", 10), ("max order", 10), ("cash", 12)])+ self.assertEqual([l["name"] for l in s["limits"] if l["binds"]], ["max loss"])+ self.assertIsNone(s["refusal"])++ def test_the_bracket_order(self):+ o = size.bracket_order(size.size_trade(plan(), cfg(), today=TODAY))+ why = o.pop("why")+ self.assertEqual(o, {+ "symbol": "TSLA", "side": "buy", "qty": "8", "type": "market", "time_in_force": "day",+ "order_class": "bracket", "take_profit_limit_price": "370.04", "stop_loss_stop_price": "358.32",+ "plan": {"entry": 364.18, "stop": 358.32, "target": 370.04, "risk_per_share": 5.86,+ "max_loss": 46.88, "setup": "orb", "entry_time": "10:15 AM", "flat_by": "15:55"}})+ self.assertIn("bound by your $50 max loss", why)+ self.assertIn("$46.88", why)++ def test_the_fixture_orders_file_is_what_it_writes(self):+ with open(os.path.join(FIX, "trader-risk", "orders-tsla.json")) as fh:+ fixture = json.load(fh)["orders"][0]+ self.assertEqual(size.bracket_order(size.size_trade(plan(), cfg(), today=TODAY)), fixture)++ def test_a_limit_order(self):+ o = size.bracket_order(size.size_trade(plan(), cfg(), limit=364.18, today=TODAY))+ self.assertEqual((o["type"], o["limit_price"], o["qty"]), ("limit", "364.18", "8"))+ s = size.size_trade(plan(), cfg(), limit=364.00, today=TODAY)+ self.assertEqual((s["risk_per_share"], s["qty"], s["max_loss"]), (5.68, 8, 45.44))+ self.assertEqual(size.bracket_order(s)["limit_price"], "364.00")++ def test_cli_writes_one_bracket_order(self):+ with tempfile.TemporaryDirectory() as d:+ out = os.path.join(d, "trader", "orders.json")+ code, text, _ = run(["--plan", PLAN, "--config", CFG, "--portfolio", os.path.join(d, "none"),+ "--now", NOW, "--write", out])+ self.assertEqual(code, 0)+ self.assertIn("Size: 8 shares of TSLA = $2,913.44 at 364.18", text)+ self.assertIn("8 x 5.86 = $46.88", text)+ self.assertIn("<- binds", text)+ self.assertIn("not financial advice", text)+ with open(out) as fh:+ doc = json.load(fh)+ self.assertEqual(doc["status"], "proposed")+ self.assertIs(doc["paper"], True)+ self.assertEqual(doc["created_at"], "2026-10-19T14:15:00Z")+ self.assertEqual(len(doc["orders"]), 1)+ self.assertEqual(doc["orders"][0]["plan"]["max_loss"], 46.88)++ def test_cli_json_and_limit(self):+ code, text, _ = run(["--plan", PLAN, "--config", CFG, "--portfolio", "/nonexistent", "--now", NOW,+ "--limit", "--json"])+ self.assertEqual(code, 0)+ out = json.loads(text)+ self.assertEqual(out["sizing"]["qty"], 8)+ self.assertEqual(out["orders"][0]["limit_price"], "364.18")+++class PlanRules(unittest.TestCase):+ def test_zero_shares_is_a_plain_refusal(self):+ s = size.size_trade(plan(stop=300.0), cfg(), today=TODAY)+ self.assertEqual(s["qty"], 0)+ self.assertIn("more than your $50 max loss per trade", s["refusal"])+ self.assertIsNone(size.bracket_order(s))+ with tempfile.TemporaryDirectory() as d:+ p = os.path.join(d, "plan.json")+ with open(p, "w") as fh:+ json.dump(plan(stop=300.0), fh)+ out = os.path.join(d, "orders.json")+ code, text, _ = run(["--plan", p, "--config", CFG, "--portfolio", os.path.join(d, "none"),+ "--now", NOW, "--write", out])+ self.assertEqual(code, 1)+ self.assertIn("No order:", text)+ self.assertFalse(os.path.exists(out))++ def test_each_limit_can_bind(self):+ self.assertEqual(size.size_trade(plan(), cfg(max_order_usd=1000), today=TODAY)["bound_by"], "max order")+ s = size.size_trade(plan(), cfg(max_position_pct=20), today=TODAY)+ self.assertEqual((s["qty"], s["bound_by"]), (2, "position cap"))+ s = size.size_trade(plan(), cfg(), cash=1200, today=TODAY)+ self.assertEqual((s["qty"], s["bound_by"], s["cash_available"]), (1, "cash", 700))+ s = size.size_trade(plan(), cfg(max_loss_per_trade_usd=100), today=TODAY)+ self.assertEqual((s["qty"], s["bound_by"]), (10, "position cap"))++ def test_a_fresh_higher_price_means_a_bigger_risk(self):+ s = size.size_trade(plan(), cfg(min_reward_risk=0), price=366.475, today=TODAY)+ self.assertEqual((s["entry"], s["entry_from"], s["risk_per_share"]), (366.48, "price", 8.16))+ self.assertEqual((s["qty"], s["max_loss"], s["reward_risk"]), (6, 48.96, 0.44))+ self.assertIsNone(s["refusal"])+ s = size.size_trade(plan(), cfg(), price=366.475, today=TODAY)+ self.assertIn("reward:risk 0.44 (target 370.04, entry 366.48, stop 358.32) is under your minimum 1",+ s["refusal"])+ self.assertIsNone(size.bracket_order(s))+ lower = size.size_trade(plan(), cfg(), price=363.00, today=TODAY)+ self.assertEqual((lower["entry"], lower["qty"]), (364.18, 8))++ def test_prices_file_is_used_only_when_fresh(self):+ with tempfile.TemporaryDirectory() as d:+ pp = os.path.join(d, "prices.json")+ with open(pp, "w") as fh:+ json.dump(prices_doc(366.475), fh)+ base = ["--plan", PLAN, "--config", CFG, "--portfolio", os.path.join(d, "none"), "--prices", pp, "--json"]+ code, text, _ = run(base + ["--now", "2026-10-19 10:55"])+ out = json.loads(text)+ self.assertEqual((code, out["sizing"]["qty"], out["orders"]), (1, 6, []))+ self.assertIn("above the plan's entry", out["notes"][0])+ out = json.loads(run(base + ["--now", "2026-10-19 11:30"])[1])+ self.assertEqual(out["sizing"]["qty"], 8)+ self.assertIn("not used", out["notes"][0])++ def test_the_portfolio_cash_caps_the_size(self):+ with tempfile.TemporaryDirectory() as d:+ pf = os.path.join(d, "portfolio.json")+ with open(pf, "w") as fh:+ json.dump({"cash": 1200, "positions": []}, fh)+ out = json.loads(run(["--plan", PLAN, "--config", CFG, "--portfolio", pf, "--now", NOW, "--json"])[1])+ self.assertEqual((out["sizing"]["qty"], out["sizing"]["bound_by"]), (1, "cash"))++ def test_bad_plans(self):+ for p, word in ((plan(stop=365.0), "not below the entry"),+ (plan(target=360.0), "already happened"),+ (plan(target=None), "positive target"),+ (plan(side="sell"), "long (buy) day trades only"),+ (plan(symbol=""), "no symbol")):+ with self.assertRaises(size.SizeError) as e:+ size.size_trade(p, cfg(), today=TODAY)+ self.assertIn(word, str(e.exception))+ with self.assertRaises(size.SizeError) as e:+ size.size_trade(plan(), cfg(), price=371.00, today=TODAY)+ self.assertIn("already happened", str(e.exception))+ with self.assertRaises(size.SizeError) as e:+ size.size_trade(plan(), cfg(blocked=["tsla"]), today=TODAY)+ self.assertIn("blocked list", str(e.exception))+ with self.assertRaises(size.SizeError) as e:+ size.size_trade(plan(), cfg(), today="2026-10-20")+ self.assertIn("make a new plan", str(e.exception))++ def test_under_the_minimum_order(self):+ cheap = plan(symbol="ABC", entry=4.0, stop=3.0, target=5.0)+ s = size.size_trade(cheap, cfg(max_loss_per_trade_usd=1), today=TODAY)+ self.assertEqual(s["qty"], 1)+ self.assertIn("under your $5 minimum order", s["refusal"])+ self.assertIsNone(size.bracket_order(s))++ def test_missing_plan_and_weights_only_flags(self):+ code, _, err = run(["--plan", "/nonexistent/plan.json", "--config", CFG, "--now", NOW])+ self.assertEqual(code, 1)+ self.assertIn("no plan", err)+ code, _, err = run(["--plan", PLAN, "--config", CFG, "--now", NOW, "--top", "2"])+ self.assertEqual(code, 1)+ self.assertIn("--weights", err)+ code, _, err = run(["--plan", PLAN, "--config", CFG, "--now", "tomorrow"])+ self.assertEqual(code, 1)+ self.assertNotIn("Traceback", err)+++class WeightsMode(unittest.TestCase):+ """v1's split, kept behind --weights / --targets: $5,000, 10% cash, 25% cap."""++ def check_reel(self, r):+ self.assertEqual(dollars(r), REEL_V1)+ self.assertEqual(r["cash_buffer"], 500)+ self.assertEqual(r["invested"], 4500)+ self.assertEqual(r["idle"], 0)+ self.assertEqual(r["cap"], 1250)+ self.assertEqual([p["ticker"] for p in r["positions"] if p["capped"]], ["AAPL"])++ def test_from_the_raw_weights(self):+ self.check_reel(size.size(rows(TOP5), v1()))++ def test_from_the_renormalised_weights_file(self):+ self.check_reel(size.size(rows(TARGETS), v1()))++ def test_from_inline_weights(self):+ w = size.parse_weights(size.weights_from_arg("AAPL=22.04,AXP=17.14,GOOGL=12.62,KO=10.86,BAC=9.20"))+ self.check_reel(size.size(w, v1()))++ def test_renormalised_weights(self):+ r = size.size(rows(TOP5), v1())+ shown = {p["ticker"]: round(p["weight"], 1) for p in r["positions"]}+ self.assertEqual(shown, {"AAPL": 30.7, "AXP": 23.9, "GOOGL": 17.6, "KO": 15.1, "BAC": 12.8})++ def test_one_decimal_weights_stay_within_a_dollar(self):+ w = size.parse_weights({"AAPL": 30.7, "AXP": 23.9, "GOOGL": 17.6, "KO": 15.1, "BAC": 12.8})+ r = size.size(w, v1())+ self.assertEqual(r["invested"], 4500)+ self.assertEqual(dollars(r)["AAPL"], 1250)+ for t, v in dollars(r).items():+ self.assertLessEqual(abs(v - REEL_V1[t]), 1.0, t)++ def test_orders_are_place_stock_order_shaped(self):+ r = size.size(rows(TOP5), v1())+ orders = size.orders_from(r, "a 13F")+ self.assertEqual(orders[0], {"symbol": "AAPL", "side": "buy", "notional": "1250", "type": "market",+ "time_in_force": "day", "why": orders[0]["why"]})+ self.assertIn("capped at 25%", orders[0]["why"])+ for o in orders:+ self.assertIsInstance(o["notional"], str)+ self.assertNotIn("qty", o)+ self.assertEqual([o["notional"] for o in orders], ["1250", "1119", "823", "708", "600"])++ def test_cents_mode_keeps_the_total(self):+ r = size.size(rows(TOP5), v1(), cents=True)+ d = dollars(r)+ self.assertEqual(d["AAPL"], 1250)+ self.assertAlmostEqual(sum(d.values()), 4500, places=2)+ self.assertAlmostEqual(d["AXP"], 1118.13, places=2)+ self.assertEqual(size.orders_from(r)[1]["notional"], "1118.13")++ def test_cap_redistributes_until_nobody_is_over(self):+ w = size.parse_weights({"A": 60, "B": 30, "C": 10})+ r = size.size(w, {"budget": 1000, "cash_buffer_pct": 0, "max_position_pct": 40, "min_order_usd": 1})+ self.assertEqual(dollars(r), {"A": 400, "B": 400, "C": 200})+ self.assertEqual(sorted(p["ticker"] for p in r["positions"] if p["capped"]), ["A", "B"])++ def test_everything_capped_leaves_money_idle(self):+ w = size.parse_weights({"AAPL": 50, "KO": 50})+ r = size.size(w, v1())+ self.assertEqual(dollars(r), {"AAPL": 1250, "KO": 1250})+ self.assertEqual(r["idle"], 2000)+ self.assertIn("every stock is at its cap", size.report(r, size.orders_from(r)))++ def test_slices_under_the_minimum_are_dropped_and_shared_out(self):+ w = size.parse_weights({"A": 90, "B": 7, "C": 3})+ r = size.size(w, {"budget": 100, "cash_buffer_pct": 10, "max_position_pct": 100, "min_order_usd": 5})+ self.assertNotIn("C", dollars(r))+ self.assertEqual(sum(dollars(r).values()), 90)+ self.assertTrue(all(v >= 5 for v in dollars(r).values()))+ self.assertEqual(r["dropped"][0]["ticker"], "C")++ def test_blocked_tickers_are_dropped_first(self):+ r = size.size(rows(TOP5), v1(blocked=["ko"]))+ self.assertNotIn("KO", dollars(r))+ self.assertEqual(r["invested"], 4500)+ self.assertIn("blocked", r["dropped"][0]["reason"])++ def test_top_n(self):+ r = size.size(rows(TOP5), v1(max_position_pct=100), top=2)+ self.assertEqual(sorted(dollars(r)), ["AAPL", "AXP"])++ def test_whole_shares_need_prices(self):+ with self.assertRaises(size.SizeError):+ size.size(rows(TOP5), v1(fractional=False))+ with self.assertRaises(size.SizeError):+ size.size(rows(TOP5), cfg()) # the v2 example config is whole shares++ def test_whole_shares_with_prices(self):+ r = size.size(rows(TOP5), v1(fractional=False), prices=PRICES)+ self.assertTrue(r["whole_shares"])+ for p in r["positions"]:+ self.assertEqual(p["shares"], int(p["shares"]))+ self.assertAlmostEqual(p["dollars"], p["shares"] * PRICES[p["ticker"]], places=2)+ self.assertLessEqual(p["dollars"], 1250)+ self.assertAlmostEqual(r["invested"] + r["idle"], 4500, places=2)+ self.assertLess(r["idle"], min(PRICES.values()) * 2)+ orders = size.orders_from(r)+ self.assertTrue(all("qty" in o and "notional" not in o for o in orders))++ def test_no_budget_and_duplicates_are_errors(self):+ with self.assertRaises(size.SizeError):+ size.size(rows(TOP5), {"cash_buffer_pct": 10})+ with self.assertRaises(size.SizeError):+ size.size([{"ticker": "KO", "name": "", "weight": 1}, {"ticker": "KO", "name": "", "weight": 2}], v1())++ def test_cli(self):+ with tempfile.TemporaryDirectory() as d:+ c = os.path.join(d, "config.json")+ with open(c, "w") as fh:+ json.dump(v1(), fh)+ out = os.path.join(d, "trader", "orders.json")+ code, text, _ = run(["--targets", TARGETS, "--config", c, "--write", out])+ self.assertEqual(code, 0)+ self.assertIn("left idle", text)+ self.assertIn("require_stop", text)+ with open(out) as fh:+ doc = json.load(fh)+ self.assertEqual([o["symbol"] for o in doc["orders"]], ["AAPL", "AXP", "GOOGL", "KO", "BAC"])+ code, text, _ = run(["--targets", TARGETS, "--config", c, "--json"])+ self.assertEqual(json.loads(text)["result"]["idle"], 0)+ code, _, err = run(["--targets", "/nonexistent/targets.json", "--config", c])+ self.assertEqual(code, 1)+ self.assertIn("no weights file", err)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_entry.py b/tests/test_entry.pynew file mode 100644index 0000000..7fd1413--- /dev/null+++ b/tests/test_entry.py@@ -0,0 +1,605 @@+"""trader-entry tests. Fixtures in tests/fixtures/trader-entry/:++TSLA-2026-10-19-5m.json TSLA's Oct 19 2026 five-minute bars, cut from the reel's+ TSLA-60d5m.json (Yahoo chart JSON v8, fetched 10:49:45 ET).+ It ends with the in-progress 10:45 bar and Yahoo's live tick+ at 10:49:45. meta trimmed to one day, like a range=1d answer.+DEMO-1m-synthetic.json SYNTHETIC one-minute bars (not market data): a wick above the+ range high, a close AT the high, a null bar, a live tick.+"""++import copy+import datetime+import gzip+import io+import json+import os+import shutil+import tempfile+import unittest+import urllib.error+from contextlib import redirect_stdout, redirect_stderr++from _load import load, FIX, ROOT++entry = load("trader-entry", "entry")++EDIR = os.path.join(FIX, "trader-entry")+TSLA = os.path.join(EDIR, "TSLA-2026-10-19-5m.json")+DEMO = os.path.join(EDIR, "DEMO-1m-synthetic.json")+OPEN_TS = 1792416600 # 2026-10-19 09:30 EDT+DT = datetime.datetime+++def ny(text):+ return entry.parse_now(text)+++def doc(path=TSLA):+ with open(path) as fh:+ return json.load(fh)+++def chart(d=None, sym="TSLA"):+ return entry.parse_chart(json.dumps(d if d is not None else doc()), sym)+++def at(text, d=None, **kw):+ return entry.evaluate(chart(d), ny(text), **kw)+++def shift_to(d, day, edt):+ """The same session moved to another date: 9:30 New York is 13:30 UTC in EDT, 14:30 in EST."""+ d = copy.deepcopy(d)+ r = d["chart"]["result"][0]+ new_open = int((DT.combine(day, datetime.time(13 if edt else 14, 30)) - DT(1970, 1, 1)).total_seconds())+ delta = new_open - OPEN_TS+ r["timestamp"] = [t + delta for t in r["timestamp"]]+ r["meta"]["regularMarketTime"] += delta+ r["meta"]["timezone"] = "EDT" if edt else "EST"+ return d+++def no_breakout(d=None):+ """Every bar after the range stays under the 362.18 high."""+ d = copy.deepcopy(d if d is not None else doc())+ q = d["chart"]["result"][0]["indicators"]["quote"][0]+ for i in range(3, len(q["close"])):+ q["close"][i] = min(q["close"][i], 362.00)+ q["high"][i] = min(q["high"][i], 362.10)+ q["open"][i] = min(q["open"][i], 362.00)+ return d+++def run(argv):+ out, err = io.StringIO(), io.StringIO()+ with redirect_stdout(out), redirect_stderr(err):+ code = entry.main(argv)+ return code, out.getvalue(), err.getvalue()+++class TheReel(unittest.TestCase):+ def test_triggers_at_1015_on_the_1010_bar(self):+ r = at("2026-10-19 10:15")+ self.assertEqual(r["status"], "triggered")+ self.assertEqual(r["opening_range"]["high"], 362.18)+ self.assertEqual(r["opening_range"]["low"], 354.47)+ self.assertEqual(r["opening_range"]["bars"], 3)+ t = r["trigger"]+ self.assertEqual(t["time"], "10:15 AM")+ self.assertEqual(t["bar_start"], "10:10")+ self.assertEqual(t["bar_index"], 8)+ self.assertEqual(t["price"], 364.18)+ self.assertEqual(t["close"], 364.1759948730469)+ self.assertEqual(t["pct_over"], 0.55)+ self.assertEqual(r["level"], 362.18)+ self.assertEqual(r["prev_close"], 354.72)++ def test_at_1012_the_1010_bar_is_still_forming(self):+ r = at("2026-10-19 10:12")+ self.assertEqual(r["status"], "waiting")+ self.assertIsNone(r["trigger"])+ self.assertEqual(r["last"]["bar_start"], "10:05")+ self.assertEqual(r["last"]["close"], 361.68)+ self.assertEqual(r["forming"]["bar_start"], "10:10")+ self.assertIn("$0.50 under the range high $362.18", r["reason"])+ self.assertEqual(at("2026-10-19 10:14:59")["status"], "waiting")++ def test_before_the_open_and_while_the_range_forms(self):+ r = at("2026-10-19 09:20")+ self.assertEqual((r["status"], r["phase"]), ("waiting", "pre-open"))+ r = at("2026-10-19 09:44")+ self.assertEqual((r["status"], r["phase"]), ("waiting", "forming"))+ self.assertEqual(r["opening_range"]["bars"], 2)+ self.assertFalse(r["opening_range"]["complete"])+ r = at("2026-10-19 09:46")+ self.assertEqual((r["status"], r["phase"]), ("waiting", "open"))+ self.assertEqual(r["opening_range"]["bars"], 3)++ def test_the_live_tick_and_the_in_progress_bar_are_dropped(self):+ c = chart()+ self.assertEqual(c["bars"][-1]["t"], 1792421385) # 10:49:45 is in the file+ r = entry.evaluate(c, entry.utc_of(c["data_time"])) # read as of the file's own time+ self.assertEqual(r["now"], "2026-10-19 10:49:45")+ self.assertEqual(r["_bars"][-1]["slot"], 14) # the 10:40 bar+ self.assertEqual(r["forming"]["bar_start"], "10:45")+ self.assertEqual(r["bars_closed"], 15)+ # 10:50: closed by the clock, but Yahoo's last trade (10:49:45) is before its close+ r = at("2026-10-19 10:50")+ self.assertEqual(r["_bars"][-1]["slot"], 14)+ self.assertIn("Yahoo's last trade is 10:49:45", r["lag_note"])+ # a minute later with no newer trade it counts; the 10:49:45 tick never becomes a bar+ r = at("2026-10-19 10:51")+ self.assertEqual(r["_bars"][-1]["slot"], 15)+ self.assertEqual(r["bars_closed"], 16)+ self.assertTrue(all(b["t"] % 300 == 0 for b in r["_bars"]))++ def test_after_the_close_it_stays_triggered_and_says_it_is_late(self):+ r = at("2026-10-19 16:05")+ self.assertEqual((r["status"], r["phase"]), ("triggered", "after-close"))+ self.assertEqual(r["trigger"]["time"], "10:15 AM")+ text = "\n".join(entry.describe(r))+ self.assertIn("minutes ago", text)+ self.assertNotIn("This is the moment", text)+++class Rules(unittest.TestCase):+ def test_volume_confirmation_moves_the_trigger(self):+ r = at("2026-10-19 10:49", min_volume_x=1)+ self.assertEqual(r["opening_range"]["avg_volume"], 1658945)+ t = r["trigger"]+ self.assertEqual((t["time"], t["bar_index"], t["price"]), ("10:35 AM", 12, 365.75))+ self.assertEqual(t["volume_x"], 7.98)+ r = at("2026-10-19 10:16", min_volume_x=1)+ self.assertEqual(r["status"], "waiting")+ self.assertIn("0.60x the range's volume, under your 1.00x", r["reason"])++ def test_level_setup(self):+ r = at("2026-10-19 10:30", setup="level", level=365.5)+ self.assertEqual(r["trigger"]["time"], "10:25 AM")+ self.assertEqual(r["trigger"]["bar_index"], 10)+ self.assertEqual(r["trigger"]["price"], 365.75)+ # a level under the open: the first eligible close is the 9:40 bar's, at 9:45 (no_entries_before)+ r = at("2026-10-19 10:30", setup="level", level=350)+ self.assertEqual((r["trigger"]["time"], r["trigger"]["bar_index"]), ("9:45 AM", 2))+ with self.assertRaises(entry.EntryError):+ at("2026-10-19 10:30", setup="level")++ def test_no_breakout_waits_then_expires_at_the_cutoff(self):+ d = no_breakout()+ r = at("2026-10-19 10:49", d)+ self.assertEqual(r["status"], "waiting")+ self.assertEqual(at("2026-10-19 15:29", d)["status"], "waiting")+ r = at("2026-10-19 15:30", d)+ self.assertEqual(r["status"], "expired")+ self.assertIn("by 15:30", r["reason"])+ self.assertEqual(at("2026-10-19 16:30", d)["phase"], "after-close")++ def test_the_bar_closing_at_the_cutoff_still_counts_when_yahoo_lags(self):+ d = no_breakout()+ r0 = d["chart"]["result"][0]+ keep = [i for i, t in enumerate(r0["timestamp"]) if t <= OPEN_TS + 14 * 300] # live: up to the 10:40 bar+ r0["timestamp"] = [r0["timestamp"][i] for i in keep]+ q = r0["indicators"]["quote"][0]+ for k in q:+ q[k] = [q[k][i] for i in keep]+ r0["meta"]["regularMarketTime"] = OPEN_TS + 74 * 60 + 40 # last trade 10:44:40+ cfg = {"no_entries_before": "09:45", "no_entries_after": "10:45"}+ r = at("2026-10-19 10:45:10", d, cfg=cfg) # the 10:40 bar closed by the clock only+ self.assertEqual(r["status"], "waiting")+ self.assertIn("Yahoo's last trade is 10:44:40", r["lag_note"])+ self.assertEqual(at("2026-10-19 10:46", d, cfg=cfg)["status"], "expired")++ def test_config_cutoff(self):+ cfg = {"no_entries_before": "09:45", "no_entries_after": "10:10"}+ r = at("2026-10-19 10:15", cfg=cfg)+ self.assertEqual(r["status"], "expired")+ cfg = {"no_entries_before": "10:20", "no_entries_after": "15:30"}+ r = at("2026-10-19 10:30", cfg=cfg)+ self.assertEqual(r["trigger"]["time"], "10:20 AM") # the 10:15 bar, first to close at or after 10:20++ def test_bad_inputs(self):+ with self.assertRaises(entry.EntryError):+ at("2026-10-19 10:15", or_minutes=7)+ with self.assertRaises(entry.EntryError):+ at("2026-10-19 10:15", interval="15m")+ with self.assertRaises(entry.EntryError):+ entry.parse_now("tomorrow")+ with self.assertRaises(entry.EntryError):+ entry.parse_hhmm("25:00", "x")+ self.assertEqual(entry.parse_now("2026-10-19 10:15"), DT(2026, 10, 19, 14, 15))+ self.assertEqual(entry.parse_now("2026-10-19T14:15:00Z"), DT(2026, 10, 19, 14, 15))+ self.assertEqual(entry.parse_now("2026-10-19 10:15 ET"), DT(2026, 10, 19, 14, 15))++ def test_or_minutes_30(self):+ r = at("2026-10-19 10:49", or_minutes=30)+ self.assertEqual(r["opening_range"]["bars"], 6)+ self.assertEqual(r["opening_range"]["high"], 362.92)+ self.assertEqual(r["trigger"]["time"], "10:15 AM")+++class OneMinute(unittest.TestCase):+ def c(self):+ return entry.parse_chart(json.dumps(doc(DEMO)), "DEMO")++ def test_wick_and_close_at_the_high_do_not_trigger(self):+ c = self.c()+ r = entry.evaluate(c, entry.utc_of(c["data_time"]), interval="1m")+ self.assertEqual(r["now"], "2026-10-19 10:06:30")+ self.assertEqual(r["opening_range"], {"high": 100.5, "low": 99.0, "minutes": 15, "bars": 15, "of": 15,+ "complete": True, "avg_volume": 10667})+ t = r["trigger"]+ self.assertEqual((t["time"], t["bar_start"], t["bar_index"], t["price"]), ("9:59 AM", "09:58", 28, 100.62))+ r = entry.evaluate(c, ny("2026-10-19 09:58:59"), interval="1m")+ self.assertEqual(r["status"], "waiting")+ self.assertEqual(r["forming"]["bar_start"], "09:58")+ self.assertEqual(r["last"]["close"], 100.5) # the 9:57 bar closed AT the high++ def test_null_bar_tick_and_volume(self):+ c = self.c()+ r = entry.evaluate(c, entry.utc_of(c["data_time"]), interval="1m", min_volume_x=2)+ self.assertEqual((r["trigger"]["time"], r["trigger"]["bar_index"]), ("10:02 AM", 31))+ slots = [b["slot"] for b in r["_bars"]]+ self.assertNotIn(19, slots) # 9:49 came as nulls+ self.assertEqual(slots[-1], 35) # 10:06 still forming, 10:06:30 tick dropped+ self.assertEqual(r["forming"]["bar_start"], "10:06")++ def test_the_file_and_the_interval_must_agree(self):+ code, _, err = run(["check", "DEMO", "--offline", DEMO])+ self.assertEqual(code, 1)+ self.assertIn("1m bars, not 5m", err)+++class Calendar(unittest.TestCase):+ def test_dst_both_sides(self):+ for day, edt in ((datetime.date(2026, 12, 7), False), (datetime.date(2026, 11, 2), False),+ (datetime.date(2026, 10, 30), True), (datetime.date(2026, 3, 9), True)):+ d = shift_to(doc(), day, edt)+ r = entry.evaluate(chart(d), ny("%s 10:15" % day))+ self.assertEqual(r["status"], "triggered", day)+ self.assertEqual(r["trigger"]["time"], "10:15 AM", day)+ self.assertEqual(r["trigger"]["bar_index"], 8, day)+ self.assertEqual(entry.evaluate(chart(d), ny("%s 10:12" % day))["status"], "waiting", day)+ # Dec 7 at 10:15 New York is 15:15 UTC+ self.assertEqual(ny("2026-12-07 10:15"), DT(2026, 12, 7, 15, 15))++ def test_half_day_moves_the_cutoff_up(self):+ d = shift_to(no_breakout(), datetime.date(2026, 11, 27), False)+ r = entry.evaluate(chart(d), ny("2026-11-27 12:29"))+ self.assertEqual(r["status"], "waiting")+ self.assertEqual((r["closes"], r["no_entries_after"]), ("13:00", "12:30"))+ r = entry.evaluate(chart(d), ny("2026-11-27 12:30"))+ self.assertEqual(r["status"], "expired")+ self.assertIn("early close", r["reason"])+ r = entry.evaluate(chart(shift_to(doc(), datetime.date(2026, 11, 27), False)), ny("2026-11-27 10:15"))+ self.assertEqual(r["trigger"]["time"], "10:15 AM")+ self.assertIn("Early close today", "\n".join(entry.describe(r)))+ # a cutoff already before the early close stays put+ cfg = {"no_entries_before": "09:45", "no_entries_after": "12:00"}+ self.assertEqual(entry.evaluate(chart(d), ny("2026-11-27 11:00"), cfg=cfg)["no_entries_after"], "12:00")++ def test_weekend_holiday_and_empty_data(self):+ r = at("2026-10-17 10:30")+ self.assertEqual((r["status"], r["phase"]), ("no-data", "closed"))+ self.assertEqual(r["next_open"], "2026-10-19 09:30")+ r = at("2026-11-26 10:30")+ self.assertIn("Thanksgiving", r["reason"])+ empty = copy.deepcopy(doc())+ res = empty["chart"]["result"][0]+ del res["timestamp"]+ res["indicators"] = {"quote": [{}]}+ r = at("2026-10-19 10:15", empty)+ self.assertEqual((r["status"], r["phase"]), ("no-data", "open"))+ r = at("2026-10-20 10:15") # Yahoo sent yesterday's bars only+ self.assertEqual(r["status"], "no-data")+ self.assertFalse(at("2028-03-01 10:30")["calendar_known"])++ def test_yahoo_errors(self):+ bad = json.dumps({"chart": {"result": None, "error": {"code": "Not Found",+ "description": "No data found, symbol may be delisted"}}})+ with self.assertRaises(entry.EntryError) as cm:+ entry.parse_chart(bad, "ZZZZ")+ self.assertIn("No data found", str(cm.exception))+ with self.assertRaises(entry.EntryError):+ entry.parse_chart("<html>", "TSLA")+++class Network(unittest.TestCase):+ """Yahoo is never called: _open_url and _sleep are swapped for fakes."""++ def setUp(self):+ self.calls, self.sleeps = [], []+ self._open, self._sleep = entry._open_url, entry._sleep+ entry._sleep = lambda s: self.sleeps.append(s)+ with open(TSLA) as fh:+ self.body = fh.read()++ def tearDown(self):+ entry._open_url, entry._sleep = self._open, self._sleep++ def answers(self, *codes):+ seq = list(codes)++ def fake(url, timeout=20):+ self.calls.append(url)+ code = seq.pop(0)+ if code == 200:+ return self.body+ raise urllib.error.HTTPError(url, code, "x", {}, io.BytesIO(b'{"chart":{"result":null,'+ b'"error":{"description":"No data found"}}}'))+ entry._open_url = fake++ def test_url_and_429_retry_once_after_a_pause(self):+ self.answers(429, 200)+ c = entry.get_chart("TSLA", "5m", datetime.date(2026, 10, 19), today=datetime.date(2026, 10, 19))+ self.assertEqual(len(c["bars"]), 17)+ self.assertEqual(self.calls, ["https://query2.finance.yahoo.com/v8/finance/chart/TSLA?range=1d&interval=5m"] * 2)+ self.assertEqual(self.sleeps, [entry.BACKOFF])++ def test_429_twice_falls_back_to_query1(self):+ self.answers(429, 429, 200)+ entry.get_chart("TSLA", "5m", datetime.date(2026, 10, 19), today=datetime.date(2026, 10, 19))+ self.assertEqual([u.split("/")[2] for u in self.calls],+ ["query2.finance.yahoo.com", "query2.finance.yahoo.com", "query1.finance.yahoo.com"])++ def test_5xx_falls_back_without_waiting(self):+ self.answers(503, 200)+ entry.get_chart("TSLA", "5m", datetime.date(2026, 10, 19), today=datetime.date(2026, 10, 19))+ self.assertEqual(self.sleeps, [])+ self.assertIn("query1", self.calls[1])++ def test_still_busy_is_one_plain_error(self):+ self.answers(429, 429, 429, 429)+ code, out, err = run(["check", "TSLA", "--now", "2026-10-19 10:15"])+ self.assertEqual(code, 1)+ self.assertIn("HTTP 429", err)+ self.assertNotIn("Traceback", err)++ def test_unknown_ticker_404(self):+ self.answers(404)+ with self.assertRaises(entry.EntryError) as cm:+ entry.get_chart("ZZZZ", "5m", datetime.date(2026, 10, 19), today=datetime.date(2026, 10, 19))+ self.assertIn("No data found", str(cm.exception))++ def test_ranges_for_past_sessions(self):+ today = datetime.date(2026, 10, 20)+ self.assertEqual(entry.chart_range(today, today, "5m"), "1d")+ self.assertEqual(entry.chart_range(datetime.date(2026, 10, 19), today, "5m"), "5d")+ self.assertEqual(entry.chart_range(datetime.date(2026, 10, 1), today, "5m"), "1mo")+ self.assertEqual(entry.chart_range(datetime.date(2026, 8, 31), today, "5m"), "60d")+ with self.assertRaises(entry.EntryError):+ entry.chart_range(datetime.date(2026, 10, 1), today, "1m")+ self.assertIn("/chart/BRK-B?", entry.chart_path("brk.b", "1d", "5m"))+++def live_provider(d, lag_until=None, calls=None):+ """Bars the way Yahoo serves them at `now`: closed bars final, the in-progress bar+ showing a spike to 363.00 (above the high, then it closes under), plus a live tick.+ lag_until: before this UTC time Yahoo's last trade lags 30 seconds behind."""+ base = chart(d)++ def provider(now):+ if calls is not None:+ calls.append(now)+ nts = entry.ts_of(now)+ lagging = lag_until is not None and now < lag_until+ data_ts = nts - 30 if lagging else nts+ bars = []+ for b in base["bars"]:+ if b["t"] % 300 or b["t"] > data_ts:+ continue+ b = dict(b)+ if b["t"] + 300 > data_ts:+ b["c"], b["h"] = 363.00, max(b["h"], 363.00)+ bars.append(b)+ if data_ts % 300:+ bars.append({"t": data_ts, "o": 363.0, "h": 363.0, "l": 363.0, "c": 363.0, "v": 0})+ return {"symbol": "TSLA", "meta": {}, "bars": bars, "prev_close": 354.72, "data_time": data_ts}+ return provider+++class Watch(unittest.TestCase):+ OPTS = {"setup": "orb", "or_minutes": 15, "interval": "5m", "level": None, "min_volume_x": None, "cfg": None}++ def loop(self, provider, start, **kw):+ clock = entry.SimClock(ny(start))+ lines, fired = [], []+ code, res = entry.watch_loop(provider, clock.now, clock.sleep, lines.append, dict(self.OPTS),+ on_trigger=lambda r, now: fired.append((r, now)), **kw)+ return code, res, lines, fired, clock++ def test_fires_on_the_first_closed_bar_not_the_spike_in_progress(self):+ calls = []+ code, res, lines, fired, clock = self.loop(live_provider(doc(), calls=calls), "2026-10-19 10:07", every=60)+ self.assertEqual(code, 0)+ self.assertEqual(len(fired), 1)+ self.assertEqual(fired[0][0]["trigger"]["time"], "10:15 AM")+ self.assertEqual(fired[0][0]["trigger"]["price"], 364.18)+ # it looked at 10:07 (10:05 bar spiking to 363 in progress) and at 10:10:02 (that bar closed 361.68)+ self.assertEqual([entry.to_eastern(c).strftime("%H:%M:%S") for c in calls], ["10:07:00", "10:10:02", "10:15:02"])+ text = "\n".join(lines)+ self.assertIn("10:05 bar closed $361.68 $0.50 under $362.18", text)+ self.assertIn("10:10 bar closed $364.18 TRIGGERED", text)+ self.assertEqual(text.count("TRIGGERED"), 1)++ def test_waits_for_yahoo_to_catch_up(self):+ lag = ny("2026-10-19 10:15:30")+ calls = []+ code, res, lines, fired, clock = self.loop(live_provider(doc(), lag_until=lag, calls=calls),+ "2026-10-19 10:12", every=30)+ self.assertEqual(code, 0)+ times = [entry.to_eastern(c).strftime("%H:%M:%S") for c in calls]+ self.assertEqual(times, ["10:12:00", "10:15:02", "10:15:32"]) # 10:15:02: Yahoo still at 10:14:32+ self.assertEqual(fired[0][0]["trigger"]["time"], "10:15 AM")++ def test_from_before_the_open_prints_the_range_bar_by_bar(self):+ code, res, lines, fired, clock = self.loop(live_provider(doc()), "2026-10-19 09:00", every=30)+ self.assertEqual(code, 0)+ text = "\n".join(lines)+ self.assertIn("not open yet", lines[0])+ self.assertIn(" 9:40 bar closed $360.39 opening range set: high $362.18, low $354.47", text)+ self.assertEqual(sum(1 for x in lines if " bar closed " in x), 9) # 9:30 ... 10:10, one line each++ def test_a_computer_that_dozes_off_catches_up_when_it_wakes(self):+ class Dozing(entry.SimClock):+ naps = 0++ def sleep(self, seconds):+ entry.SimClock.sleep(self, seconds)+ self.naps += 1+ if self.naps == 3: # the laptop sleeps for 17 minutes mid-wait+ self.t += datetime.timedelta(minutes=17)+ clock = Dozing(ny("2026-10-19 09:46"))+ calls, lines = [], []+ code, res = entry.watch_loop(live_provider(doc(), calls=calls), clock.now, clock.sleep, lines.append,+ dict(self.OPTS), every=30)+ self.assertEqual(code, 0)+ times = [entry.to_eastern(c).strftime("%H:%M:%S") for c in calls]+ self.assertEqual(times[:2], ["09:46:00", "10:04:30"]) # straight after waking, not a long sleep later+ text = "\n".join(lines)+ for start in (" 9:45", " 9:50", " 9:55", "10:00"):+ self.assertIn(start + " bar closed", text) # the bars it slept through, one line each+ self.assertEqual(res["trigger"]["time"], "10:15 AM")++ def test_expires_and_until(self):+ code, res, lines, fired, clock = self.loop(live_provider(no_breakout()), "2026-10-19 15:00", every=300)+ self.assertEqual(code, 1)+ self.assertEqual(res["status"], "expired")+ self.assertEqual(fired, [])+ self.assertEqual(entry.to_eastern(clock.now()).strftime("%H:%M"), "15:30")+ until = DT(2026, 10, 19, 11, 0)+ code, res, lines, fired, clock = self.loop(live_provider(no_breakout()), "2026-10-19 10:30", every=300,+ until=until)+ self.assertEqual(code, 1)+ self.assertIn("--until 11:00", lines[-1])++ def test_closed_day_and_repeated_errors(self):+ code, _, lines, _, _ = self.loop(live_provider(doc()), "2026-10-17 10:00")+ self.assertEqual(code, 1)+ self.assertIn("weekend", lines[0])++ def broken(now):+ raise entry.EntryError("Yahoo did not answer")+ code, _, lines, _, _ = self.loop(broken, "2026-10-19 10:00", every=30)+ self.assertEqual(code, 1)+ self.assertIn("Stopping after 5 failed reads", lines[-1])+++class Cli(unittest.TestCase):+ def setUp(self):+ self.d = tempfile.mkdtemp()+ self.cwd = os.getcwd()+ os.chdir(self.d)++ def tearDown(self):+ os.chdir(self.cwd)+ shutil.rmtree(self.d)++ def test_check_write_is_the_contract_shape(self):+ code, text, _ = run(["check", "TSLA", "--offline", TSLA, "--now", "2026-10-19 10:15", "--write"])+ self.assertEqual(code, 0)+ self.assertIn("TRIGGERED 10:15 AM at $364.18", text)+ self.assertIn("/trader-exit", text)+ with open(os.path.join("trader", "entry.json")) as fh:+ e = json.load(fh)+ want = {"created_by": "trader-entry", "symbol": "TSLA", "setup": "orb", "side": "buy", "date": "2026-10-19",+ "status": "triggered", "time": "10:15 AM", "bar_start": "10:10", "bar_index": 8, "price": 364.18,+ "level": 362.18, "interval": "5m", "opening_range": {"high": 362.18, "low": 354.47, "minutes": 15},+ "source": "yahoo", "checked_at": "2026-10-19T14:15:00Z"}+ for k, v in want.items():+ self.assertEqual(e[k], v, k)++ def test_check_waiting_json_and_exit_codes(self):+ code, text, _ = run(["check", "TSLA", "--offline", TSLA, "--now", "2026-10-19 10:12", "--json"])+ self.assertEqual(code, 1)+ r = json.loads(text)+ self.assertEqual(r["status"], "waiting")+ self.assertNotIn("_bars", r)+ code, text, _ = run(["check", "TSLA", "--offline", TSLA, "--now", "2026-10-19 10:12", "--write", "e.json"])+ with open("e.json") as fh:+ self.assertEqual(json.load(fh)["status"], "waiting")+ self.assertIn("still forming", text)++ def test_offline_gz_folder_and_mismatch(self):+ os.mkdir("charts")+ with open(TSLA, "rb") as src, gzip.open(os.path.join("charts", "TSLA.json.gz"), "wb") as dst:+ dst.write(src.read())+ code, text, _ = run(["check", "tsla", "--offline", "charts", "--now", "2026-10-19 10:15"])+ self.assertEqual(code, 0)+ code, _, err = run(["check", "NVDA", "--offline", TSLA])+ self.assertEqual(code, 1)+ self.assertIn("holds TSLA, not NVDA", err)++ def test_longs_only_and_flag_errors(self):+ code, _, err = run(["check", "TSLA", "--offline", TSLA, "--side", "short"])+ self.assertEqual(code, 1)+ self.assertIn("v2 plans longs only", err)+ code, _, err = run(["check", "TSLA", "--offline", TSLA, "--level", "300"])+ self.assertIn("--level is for --setup level", err)+ code, _, err = run(["check", "TSLA", "--offline", TSLA, "--setup", "level"])+ self.assertIn("needs --level", err)++ def test_config_is_read(self):+ os.mkdir("trader")+ with open(os.path.join("trader", "config.json"), "w") as fh:+ json.dump({"no_entries_after": "10:10"}, fh)+ code, text, _ = run(["check", "TSLA", "--offline", TSLA, "--now", "2026-10-19 10:15"])+ self.assertEqual(code, 1)+ self.assertIn("EXPIRED", text)+ with open(os.path.join("trader", "config.json"), "w") as fh:+ fh.write("{nope")+ code, _, err = run(["check", "TSLA", "--offline", TSLA])+ self.assertIn("not valid JSON", err)++ def test_watch_replays_the_file_and_writes_the_entry(self):+ code, text, _ = run(["watch", "TSLA", "--offline", TSLA, "--now", "2026-10-19 09:50", "--every", "30"])+ self.assertEqual(code, 0)+ self.assertIn("10:10 bar closed $364.18 TRIGGERED", text)+ with open(os.path.join("trader", "entry.json")) as fh:+ self.assertEqual(json.load(fh)["bar_index"], 8)+ code, text, _ = run(["watch", "TSLA", "--offline", TSLA, "--now", "2026-10-19 09:50", "--until", "10:00",+ "--out", "x.json"])+ self.assertEqual(code, 1)+ self.assertFalse(os.path.exists("x.json"))++ def test_watchlist(self):+ os.mkdir("charts")+ shutil.copy(TSLA, os.path.join("charts", "TSLA.json"))+ shutil.copy(DEMO, os.path.join("charts", "DEMO.json"))+ os.mkdir("trader")+ with open(os.path.join("trader", "watchlist.json"), "w") as fh:+ json.dump({"created_by": "trader-scanner", "hits": [+ {"symbol": "TSLA", "setups": ["orb"], "or_high": 362.18, "or_low": 354.47},+ {"symbol": "ZZZZ", "setups": ["orb"]}, {"symbol": "DEMO", "setups": ["orb"]}]}, fh)+ code, text, _ = run(["watchlist", "--offline", "charts", "--now", "2026-10-19 10:15"])+ self.assertEqual(code, 0)+ rows = text.splitlines()+ self.assertTrue(rows[1].startswith("TSLA triggered 10:15 AM $364.18 $362.18"), rows[1])+ self.assertIn("ZZZZ error: no offline file", rows[2])+ self.assertIn("DEMO error: DEMO has 1m bars", rows[3])+ self.assertIn("1 of 3 triggered", text)+ code, text, _ = run(["watchlist", "--offline", "charts", "--now", "2026-10-19 10:12", "--json"])+ self.assertEqual(code, 1)+ self.assertEqual(json.loads(text)[0]["result"]["status"], "waiting")+ code, _, err = run(["watchlist", "--watchlist", "missing.json"])+ self.assertIn("run /trader-scanner first", err)+++class SkillDoc(unittest.TestCase):+ def test_skill_md(self):+ with open(os.path.join(ROOT, "trader-entry", "SKILL.md"), encoding="utf-8") as fh:+ text = fh.read()+ with open(os.path.join(ROOT, "trader-risk", "SKILL.md"), encoding="utf-8") as fh:+ risk = fh.read()+ self.assertTrue(text.startswith("---\nname: trader-entry\n"))+ self.assertGreater(len(text.splitlines()), 60)+ self.assertEqual(text[text.index("## Safety"):], risk[risk.index("## Safety"):])+ low = " ".join(text.lower().split())+ for must in ("bar by bar", "can lag", "day trading loses most people money", "/trader-exit", "longs only", "in the background", "/loop", "nothing was placed", "10:15 am", "$364.18", "bar 8"):+ self.assertIn(must, low)+ for never in ("\u2014", "tick " + "by tick", "real " + "time", "pro" + "fit"):+ self.assertNotIn(never, low)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_exit.py b/tests/test_exit.pynew file mode 100644index 0000000..dcee434--- /dev/null+++ b/tests/test_exit.py@@ -0,0 +1,290 @@+"""trader-exit tests. Bars for the ATR stop reuse tests/fixtures/trader-entry/+(TSLA's real Oct 19 2026 five-minute bars, see test_entry.py)."""++import io+import json+import os+import shutil+import tempfile+import unittest+from contextlib import redirect_stdout, redirect_stderr+from decimal import Decimal++from _load import load, FIX, ROOT++exitp = load("trader-exit", "exit")+entry = load("trader-entry", "entry")++TSLA = os.path.join(FIX, "trader-entry", "TSLA-2026-10-19-5m.json")++# trader/plan.json for the reel, exactly as the contract writes it+REEL_PLAN = {"created_by": "trader-exit", "symbol": "TSLA", "side": "buy", "date": "2026-10-19", "setup": "orb",+ "entry": 364.18, "entry_time": "10:15 AM", "entry_bar": 8, "interval": "5m",+ "opening_range": {"high": 362.18, "low": 354.47, "minutes": 15},+ "stop": 358.32, "stop_rule": "or_mid", "stop_label": "opening-range midpoint",+ "target": 370.04, "target_r": 1.0, "target_label": "1R (one times the risk)",+ "risk_per_share": 5.86, "reward_risk": 1.0, "flat_by": "15:55"}+REEL_ENTRY = {"created_by": "trader-entry", "symbol": "TSLA", "setup": "orb", "side": "buy", "date": "2026-10-19",+ "status": "triggered", "time": "10:15 AM", "bar_start": "10:10", "bar_index": 8, "price": 364.18,+ "level": 362.18, "interval": "5m", "opening_range": {"high": 362.18, "low": 354.47, "minutes": 15},+ "source": "yahoo", "checked_at": "2026-10-19T14:15:00Z"}+++def run(mod, argv):+ out, err = io.StringIO(), io.StringIO()+ with redirect_stdout(out), redirect_stderr(err):+ code = mod.main(argv)+ return code, out.getvalue(), err.getvalue()+++def c(entry_px, stop, target="2R", oh=362.18, ol=354.47, atr=None, n=None):+ sr, sp = exitp.parse_stop(stop)+ tr, tp = exitp.parse_target(target)+ return exitp.compute(entry_px, sr, sp, tr, tp, oh, ol, atr, n)+++class Math(unittest.TestCase):+ def test_the_reel_or_mid_1r(self):+ p = c(364.18, "or-mid", "1R")+ self.assertEqual(p["stop"], Decimal("358.32")) # floor(358.325)+ self.assertEqual(p["risk"], Decimal("5.86"))+ self.assertEqual(p["target"], Decimal("370.04"))+ self.assertEqual(p["reward_risk"], Decimal("1.00"))+ self.assertEqual(p["target_label"], "1R (one times the risk)")+ self.assertIn("rounded down", p["stop_detail"])++ def test_the_default_2r(self):+ p = c(364.18, "or-mid")+ self.assertEqual(p["target"], Decimal("375.90"))+ self.assertEqual(p["target_label"], "2R (two times the risk)")++ def test_raw_yahoo_floats_give_the_same_cents(self):+ p = c(364.1759948730469, "or-mid", "1R", 362.17999267578125, 354.4700012207031)+ self.assertEqual((p["entry"], p["stop"], p["target"]), (Decimal("364.18"), Decimal("358.32"), Decimal("370.04")))++ def test_other_stops(self):+ p = c(364.18, "or-low")+ self.assertEqual((p["stop"], p["risk"], p["target"]), (Decimal("354.47"), Decimal("9.71"), Decimal("383.60")))+ p = c(364.18, "price:358.329")+ self.assertEqual(p["stop"], Decimal("358.32")) # rounds away from the entry+ p = c(364.18, "pct:1")+ self.assertEqual((p["stop"], p["risk"], p["target"]), (Decimal("360.53"), Decimal("3.65"), Decimal("371.48")))+ p = c(364.18, "atr:1.5", atr=3.2181, n=9)+ self.assertEqual(p["stop"], Decimal("359.35")) # 364.18 - 4.82715 = 359.35285+ self.assertEqual(p["stop_label"], "1.5 x ATR(9) under the entry")++ def test_target_rounds_half_up_and_price_targets(self):+ p = c(100, "price:99.01", "1.5R", None, None)+ self.assertEqual(p["target"], Decimal("101.49")) # 100 + 1.485+ self.assertEqual(p["target_label"], "1.5R (1.5 times the risk)")+ p = c(364.18, "or-mid", "price:372")+ self.assertEqual(p["reward_risk"], Decimal("1.33"))+ self.assertEqual(p["target_label"], "your price (1.33R)")+ self.assertEqual(p["target_r"], Decimal("1.33"))++ def test_refusals_say_why(self):+ cases = [("price:364.18", "2R", "at or above the entry"),+ ("price:365", "2R", "at or above the entry"),+ ("or-mid", "price:364", "at or below the entry"),+ ("price:364.01", "2R", "too tight to survive the spread"),+ ("pct:0.04", "2R", "too tight to survive the spread")]+ for stop, target, why in cases:+ with self.assertRaises(exitp.PlanError) as cm:+ c(364.18, stop, target)+ self.assertIn(why, str(cm.exception), stop)+ # 0.05% of 364.18 is 0.182: a $0.19 risk is allowed, $0.18 is not+ self.assertEqual(c(364.18, "price:363.99")["risk"], Decimal("0.19"))+ with self.assertRaises(exitp.PlanError):+ c(364.18, "price:364.00")+ with self.assertRaises(exitp.PlanError):+ c(358.00, "or-mid") # the midpoint is above this entry+ for bad in ("mid-ish", "pct:100", "price:0", "atr:-1"):+ with self.assertRaises(exitp.PlanError):+ exitp.parse_stop(bad)+ for bad in ("0R", "R", "lots", "price:x"):+ with self.assertRaises(exitp.PlanError):+ exitp.parse_target(bad)+ with self.assertRaises(exitp.PlanError):+ c(364.18, "or-mid", oh=None, ol=None)+ with self.assertRaises(exitp.PlanError):+ c(364.18, "or-mid", oh=354.47, ol=362.18)++ def test_atr_on_the_session_bars(self):+ ch = exitp.load_chart("TSLA", "5m", None, TSLA)+ day = exitp.datetime.date(2026, 10, 19)+ bars = exitp.session_bars(ch, day, "5m", upto_slot=8)+ self.assertEqual(len(bars), 9) # 9:30 ... the 10:10 entry bar+ # by hand: the true range of each bar, the first one without the overnight gap+ trs, prev = [], None+ for b in bars:+ r = b["h"] - b["l"]+ if prev is not None:+ r = max(r, abs(b["h"] - prev), abs(b["l"] - prev))+ trs.append(r)+ prev = b["c"]+ self.assertAlmostEqual(trs[0], 362.18 - 354.47, places=4)+ atr, n = exitp.atr_of(bars)+ self.assertEqual(n, 9)+ self.assertAlmostEqual(atr, sum(trs) / 9, places=9)+ self.assertAlmostEqual(atr, 3.2182, places=4)+ # later in the day it uses the last 14 bars; the file's in-progress 10:45 bar and tick never count+ all_bars = exitp.session_bars(ch, day, "5m")+ self.assertEqual(len(all_bars), 15)+ self.assertEqual(exitp.atr_of(all_bars)[1], 14)+++class Cli(unittest.TestCase):+ def setUp(self):+ self.d = tempfile.mkdtemp()+ self.cwd = os.getcwd()+ os.chdir(self.d)+ os.mkdir("trader")++ def tearDown(self):+ os.chdir(self.cwd)+ shutil.rmtree(self.d)++ def write(self, path, doc):+ with open(path, "w") as fh:+ json.dump(doc, fh)++ def plan(self, *args):+ return run(exitp, ["plan", "--now", "2026-10-19 10:16"] + list(args))++ def read_plan(self):+ with open(os.path.join("trader", "plan.json")) as fh:+ return json.load(fh)++ def test_entry_to_plan_end_to_end(self):+ code, _, _ = run(entry, ["check", "TSLA", "--offline", TSLA, "--now", "2026-10-19 10:15", "--write"])+ self.assertEqual(code, 0)+ code, text, err = self.plan("--stop", "or-mid", "--target", "1R", "--write")+ self.assertEqual(code, 0, err)+ p = self.read_plan()+ for k, v in REEL_PLAN.items():+ self.assertEqual(p[k], v, k)+ self.assertIn("Stop $358.32 opening-range midpoint", text)+ self.assertIn("Target $370.04 1R (one times the risk)", text)+ self.assertIn("Risk a share $5.86 (1.61% of the entry)", text)+ self.assertIn("Reward:risk 1.0", text)+ self.assertIn("Flat by 15:55", text)+ self.assertIn("not a guarantee", text)+ self.assertIn("/trader-timemachine", text)+ self.assertNotIn("pro" + "fit", text.lower()) # never on screen+ code, text, _ = self.plan("--write") # the defaults: or-mid, 2R+ self.assertEqual(self.read_plan()["target"], 375.90)+ self.assertEqual(self.read_plan()["target_r"], 2.0)+ code, text, _ = run(exitp, ["show", "--now", "2026-10-19 10:20"])+ self.assertEqual(code, 0)+ self.assertIn("$375.90", text)+ self.assertNotIn("not today", text)+ code, text, _ = run(exitp, ["show", "--now", "2026-10-20 10:20"])+ self.assertIn("not today", text)++ def test_manual_flags_and_json(self):+ code, text, _ = self.plan("--symbol", "tsla", "--entry", "364.18", "--or-high", "362.18", "--or-low", "354.47",+ "--time", "10:15", "--entry-bar", "8", "--date", "2026-10-19", "--target", "1R",+ "--json")+ self.assertEqual(code, 0)+ p = json.loads(text)+ for k, v in REEL_PLAN.items():+ self.assertEqual(p[k], v, k)+ self.assertEqual(p["warnings"], [])++ def test_atr_stop_reads_bars(self):+ self.write(os.path.join("trader", "entry.json"), REEL_ENTRY)+ code, text, err = self.plan("--stop", "atr:1.5", "--offline", TSLA, "--json")+ self.assertEqual(code, 0, err)+ p = json.loads(text)+ self.assertEqual((p["stop"], p["risk_per_share"], p["target"]), (359.35, 4.83, 373.84))+ self.assertEqual((p["stop_rule"], p["atr_bars"]), ("atr", 9))+ self.assertAlmostEqual(p["atr"], 3.2182, places=4)+ code, _, err = self.plan("--stop", "atr:1.5", "--offline", TSLA, "--entry-bar", "1")+ self.assertEqual(code, 1)+ self.assertIn("at least 3 closed", err)++ def test_refusals_from_the_cli(self):+ self.write(os.path.join("trader", "entry.json"), dict(REEL_ENTRY, status="waiting", time=None, price=None,+ bar_index=None, bar_start=None))+ code, _, err = self.plan()+ self.assertEqual(code, 1)+ self.assertIn("TSLA is waiting, not triggered", err)+ code, text, _ = self.plan("--entry", "362.19", "--json") # plan ahead at the level+ self.assertEqual(code, 0)+ p = json.loads(text)+ self.assertEqual((p["entry"], p["stop"], p["entry_time"]), (362.19, 358.32, None))++ self.write(os.path.join("trader", "entry.json"), dict(REEL_ENTRY, setup="level", level=362.0))+ code, _, err = self.plan()+ self.assertIn("level setup has no opening-range stop", err)+ self.assertEqual(self.plan("--stop", "pct:1")[0], 0)++ code, _, err = self.plan("--side", "sell")+ self.assertIn("v2 plans longs only", err)+ self.write(os.path.join("trader", "entry.json"), dict(REEL_ENTRY, side="sell"))+ code, _, err = self.plan()+ self.assertIn("longs only", err)+ code, _, err = self.plan("--stop", "price:364.10")+ self.assertIn("longs only", err)+ os.remove(os.path.join("trader", "entry.json"))+ code, _, err = self.plan()+ self.assertIn("no entry", err)+ code, _, err = self.plan("--symbol", "TSLA")+ self.assertIn("needs --entry", err)+ code, _, err = self.plan("--symbol", "TSLA", "--from", "x.json", "--entry", "1")+ self.assertIn("not both", err)+ code, _, err = self.plan("--symbol", "TSLA", "--entry", "364.18", "--or-high", "362.18")+ self.assertIn("both --or-high and --or-low", err)+ self.assertNotIn("Traceback", err)++ def test_flat_by_config_half_day_and_late_entries(self):+ self.write(os.path.join("trader", "entry.json"), REEL_ENTRY)+ self.write(os.path.join("trader", "config.json"), {"flat_by": "15:45", "min_reward_risk": 1.5})+ code, text, _ = self.plan("--target", "1R", "--json")+ p = json.loads(text)+ self.assertEqual(p["flat_by"], "15:45")+ self.assertIn("under your min_reward_risk 1.5", p["warnings"][0])+ os.remove(os.path.join("trader", "config.json"))++ half = dict(REEL_ENTRY, date="2026-11-27")+ self.write(os.path.join("trader", "entry.json"), half)+ code, text, _ = run(exitp, ["plan", "--now", "2026-11-27 10:16"])+ self.assertEqual(code, 0)+ self.assertIn("Flat by 12:55 ET", text)+ self.assertIn("early close", text)+ code, _, err = run(exitp, ["plan", "--now", "2026-11-27 10:16", "--flat-by", "14:00"])+ self.assertEqual(code, 1)+ self.assertIn("after the 1:00 PM close", err)++ self.write(os.path.join("trader", "entry.json"), REEL_ENTRY)+ code, _, err = self.plan("--flat-by", "16:30")+ self.assertIn("after the 4:00 PM close", err)+ self.write(os.path.join("trader", "entry.json"), dict(REEL_ENTRY, time="3:58 PM"))+ code, _, err = self.plan()+ self.assertEqual(code, 1)+ self.assertIn("no time left to hold it", err)++ def test_show_without_a_plan(self):+ code, text, _ = run(exitp, ["show"])+ self.assertEqual(code, 1)+ self.assertIn("No plan", text)+++class SkillDoc(unittest.TestCase):+ def test_skill_md(self):+ with open(os.path.join(ROOT, "trader-exit", "SKILL.md"), encoding="utf-8") as fh:+ text = fh.read()+ with open(os.path.join(ROOT, "trader-risk", "SKILL.md"), encoding="utf-8") as fh:+ risk = fh.read()+ self.assertTrue(text.startswith("---\nname: trader-exit\n"))+ self.assertGreater(len(text.splitlines()), 60)+ self.assertEqual(text[text.index("## Safety"):], risk[risk.index("## Safety"):])+ low = " ".join(text.lower().split())+ for must in ("before the entry", "a stop is a plan, not a guarantee", "day trading loses most people money", "/trader-timemachine", "/trader-budget", "longs only", "$358.32", "$370.04", "$5.86", "375.90", "too tight to survive the spread"):+ self.assertIn(must, low)+ for never in ("\u2014", "tick " + "by tick", "real " + "time", "pro" + "fit"):+ self.assertNotIn(never, low)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_news.py b/tests/test_news.pynew file mode 100644index 0000000..93800f4--- /dev/null+++ b/tests/test_news.py@@ -0,0 +1,208 @@+import datetime+import io+import json+import os+import tempfile+import unittest+from contextlib import redirect_stderr, redirect_stdout++from _load import FIX, load++news = load("trader-news", "news")+DIR = os.path.join(FIX, "trader-news")+NOW = "2026-10-14T00:00:00+00:00"+++def raw(name):+ with open(os.path.join(DIR, name), "rb") as fh:+ return fh.read()+++def run(args):+ out, err = io.StringIO(), io.StringIO()+ with redirect_stdout(out), redirect_stderr(err):+ code = news.main(args)+ return code, out.getvalue(), err.getvalue()+++class Feeds(unittest.TestCase):+ def test_yahoo_rss(self):+ items = news.parse_rss(raw("yahoo-AAPL.xml"), "AAPL")+ self.assertEqual(len(items), 6)+ first = items[0]+ self.assertEqual(first["title"], "Apple may have a way to dominate the smart home space")+ self.assertEqual(first["time"], datetime.datetime(2026, 10, 13, 19, 46, 52,+ tzinfo=datetime.timezone.utc))+ self.assertTrue(first["link"].startswith("https://finance.yahoo.com/"))+ self.assertTrue(first["id"].startswith("rss:"))++ def test_sec_atom_8k(self):+ items = news.parse_sec_atom(raw("sec-8-K-0000320193.xml"), "AAPL")+ self.assertEqual([i["form"] for i in items], ["8-K/A", "8-K", "8-K"])+ earn = items[1]+ self.assertEqual(earn["items"], ["2.02", "9.01"])+ self.assertTrue(earn["important"])+ self.assertEqual(earn["title"], "Apple Inc. filed a 8-K: earnings results")+ self.assertEqual(earn["id"], "sec:0000320193-26-000018")+ self.assertIn("000032019326000018", earn["link"])+ # 16:30:28 New York time is 20:30:28 UTC+ self.assertEqual(earn["time"].isoformat(), "2026-07-30T20:30:28+00:00")+ self.assertEqual(items[0]["title"], "Apple Inc. filed a 8-K/A: director or officer change")++ def test_times(self):+ self.assertEqual(news.parse_time("Tue, 13 Oct 2026 20:02:03 +0000").hour, 20)+ self.assertEqual(news.parse_time("2026-09-01T16:30:35-04:00").hour, 20)+ self.assertIsNone(news.parse_time("soon"))++ def test_yahoo_symbols(self):+ self.assertEqual(news.yahoo_symbol("BRK.B"), "BRK-B")+++class Tagging(unittest.TestCase):+ def test_touches_and_tags(self):+ items = news.parse_rss(raw("yahoo-KO.xml"), "KO")+ watch = {"KO": "Coca-Cola", "CVX": "Chevron", "AAPL": "Apple"}+ news.tag(items, watch)+ by = {i["title"][:20]: i for i in items}+ chevron = by["Coca-Cola or Chevron"]+ self.assertEqual(chevron["touches"], ["CVX", "KO"])+ self.assertIn("capital", chevron["tags"]) # dividend+ self.assertEqual(by["Is Coca-Cola (KO) St"]["touches"], ["KO"])++ def test_earnings_filings_are_tagged(self):+ items = news.tag(news.parse_sec_atom(raw("sec-8-K-0000021344.xml"), "KO"), {"KO": None})+ self.assertEqual(items[0]["tags"][0], "earnings")+ self.assertFalse(items[1]["important"]) # 8.01 other events++ def test_dedupe_merges_the_same_story(self):+ a = news.parse_rss(raw("yahoo-AAPL.xml"), "AAPL")+ b = news.parse_rss(raw("yahoo-AAPL.xml"), "GOOGL")+ items = news.dedupe(news.tag(a + b, {"AAPL": None, "GOOGL": None}))+ self.assertEqual(len(items), 6)+ self.assertEqual(items[0]["touches"], ["AAPL", "GOOGL"])+++class Check(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.state = os.path.join(self.tmp.name, "state", "news.json")+ self.base = ["--offline", DIR, "--state", self.state, "--now", NOW,+ "--portfolio", os.path.join(self.tmp.name, "none.json"),+ "--watchlist", os.path.join(self.tmp.name, "none.json"),+ "--plan", os.path.join(self.tmp.name, "none.json")]++ def tearDown(self):+ self.tmp.cleanup()++ def test_new_items_once_newest_first(self):+ code, out, err = run(["--tickers", "AAPL", "KO", "--hours", "24", "--json"] + self.base)+ self.assertEqual(code, 0, err)+ data = json.loads(out)+ times = [i["time"] for i in data["items"]]+ self.assertEqual(times, sorted(times, reverse=True))+ self.assertEqual(len(data["items"]), 10) # 6 Apple + 4 Coca-Cola headlines, filings are older+ code, out, _ = run(["--tickers", "AAPL", "KO", "--hours", "24"] + self.base)+ self.assertEqual(code, 1)+ self.assertIn("Nothing new.", out)++ def test_filings_show_in_a_wider_window(self):+ code, out, err = run(["--tickers", "AAPL", "--hours", "2400"] + self.base)+ self.assertEqual(code, 0, err)+ self.assertIn("! 2026-07-30 16:30 ET AAPL", out) # 20:30 UTC, New York time+ self.assertIn("earnings results", out)+ self.assertIn("Not financial advice", out)+ self.assertNotIn(chr(0x2014), out)++ def test_tickers_from_watchlist_and_plan(self):+ wl = os.path.join(self.tmp.name, "watchlist.json")+ with open(wl, "w") as fh:+ json.dump({"created_by": "trader-scanner", "hits": [{"symbol": "KO", "setups": ["orb"]}]}, fh)+ plan = os.path.join(self.tmp.name, "plan.json")+ with open(plan, "w") as fh:+ json.dump({"created_by": "trader-exit", "symbol": "AAPL"}, fh)+ self.assertEqual(sorted(news.watch_from_files("/nonexistent.json", wl, plan)), ["AAPL", "KO"])+ args = list(self.base)+ args[args.index("--watchlist") + 1] = wl+ code, out, err = run(["--json", "--dry-run", "--hours", "24"] + args)+ self.assertEqual(code, 0, err)+ tickers = {t for i in json.loads(out)["items"] for t in i["touches"]}+ self.assertEqual(tickers, {"KO"})+ self.assertFalse(os.path.exists(self.state))++ def test_no_tickers_is_an_error(self):+ code, _, err = run(self.base)+ self.assertEqual(code, 2)+ self.assertIn("no tickers", err)++ def test_sec_needs_a_user_agent(self):+ old = os.environ.pop("SEC_USER_AGENT", None)+ try:+ self.assertIsNone(news.sec_user_agent(None, "/nonexistent.json"))+ self.assertIsNone(news.sec_user_agent("Your Name [email protected]"))+ self.assertEqual(news.sec_user_agent("Ada [email protected]"), "Ada [email protected]")+ with self.assertRaises(news.NewsError):+ news.Fetcher(None).get("https://www.sec.gov/x", "x", sec=True)+ finally:+ if old is not None:+ os.environ["SEC_USER_AGENT"] = old++ def test_the_reel_tsla_morning(self):+ # The reel's real feed: Yahoo Finance headlines for TSLA, Monday Oct 19 2026, checked at 10:15 AM ET+ code, out, err = run(["--tickers", "TSLA", "--hours", "6", "--no-sec", "--no-moves",+ "--now", "2026-10-19T10:15:00-04:00"] + self.base[:4])+ self.assertEqual(code, 0, err)+ self.assertIn("2026-10-19 08:04 ET TSLA", out)+ self.assertNotIn("10:32 ET", out) # published after the pinned 10:15 clock+ self.assertIn("Tesla-SpaceX Merger Mania Strikes Wall Street Ahead of Earnings", out)+ merger = [l for l in out.splitlines() if "Merger Mania" in l]+ tags = out.splitlines()[out.splitlines().index(merger[0]) + 1]+ self.assertIn("earnings", tags)+ self.assertIn("deal", tags)+ self.assertIn("Checked 2026-10-19 10:15 ET", out)+ self.assertEqual(len([l for l in out.splitlines() if l.startswith(" 2026-10-19")]), 16) # 18 in the feed, 2 after 10:15+ # the price line, from the chart fetched at 10:52+ code, out, err = run(["--tickers", "TSLA", "--hours", "6", "--no-sec", "--dry-run",+ "--now", "2026-10-19T10:52:00-04:00"] + self.base[:4])+ self.assertRegex(out, r"TSLA\s+366\.4[78] \+3\.31% vs yesterday's close 354\.72 at 10:52 ET MOVING")++ def test_moves(self):+ m = news.parse_chart(raw("chart-TSLA.json"), "TSLA")+ self.assertEqual(m["prev_close"], 354.72)+ self.assertEqual(m["pct"], 3.31)+ self.assertEqual(news.to_eastern(m["time"]).strftime("%H:%M"), "10:52")+ quiet = dict(m, pct=1.2)+ self.assertNotIn("MOVING", news.render_moves([quiet])[0])+ self.assertIn("MOVING", news.render_moves([quiet], move_pct=1.0)[0])+ with self.assertRaises(news.NewsError):+ news.parse_chart(b'{"chart": {"result": null}}', "ZZZZ")+ # no chart file offline: no move line, no error note+ code, out, _ = run(["--tickers", "KO", "--hours", "24", "--dry-run"] + self.base)+ self.assertNotIn("vs yesterday's close", out)+ self.assertNotIn("note:", out)++ def test_new_york_time_follows_daylight_saving(self):+ utc = datetime.datetime(2026, 1, 15, 15, 0, tzinfo=datetime.timezone.utc)+ self.assertEqual(news.to_eastern(utc).hour, 10) # EST, UTC-5+ utc = datetime.datetime(2026, 10, 19, 14, 15, tzinfo=datetime.timezone.utc)+ self.assertEqual(news.to_eastern(utc).hour, 10) # EDT, UTC-4+ utc = datetime.datetime(2026, 11, 1, 6, 30) # 1:30 EST, just after the switch back+ self.assertEqual(news.to_eastern(utc).hour, 1)++ def test_day_trading_tags(self):+ items = [{"id": "x", "source": "Yahoo Finance", "kind": "headline", "ticker": "TSLA",+ "title": "Trading halted in XYZ after FDA approval; futures rise before CPI",+ "summary": "", "link": "", "time": None}]+ tags = news.tag(items, {"TSLA": None})[0]["tags"]+ for t in ("halt", "regulatory", "macro"):+ self.assertIn(t, tags)++ def test_state_forgets_after_30_days(self):+ state = {"seen": {"old": "2026-08-01T00:00:00+00:00"}}+ now = news.parse_time(NOW)+ news.remember([], state, now)+ self.assertNotIn("old", state["seen"])+ self.assertEqual(state["last_check"], now.isoformat())+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_pelosi.py b/tests/test_pelosi.pynew file mode 100644index 0000000..267ae6f--- /dev/null+++ b/tests/test_pelosi.py@@ -0,0 +1,200 @@+import datetime+import io+import json+import os+import tempfile+import unittest+from contextlib import redirect_stderr, redirect_stdout++from _load import FIX, load++ptr = load("trader-pelosi", "ptr")+DIR = os.path.join(FIX, "trader-pelosi")+ZIP = os.path.join(DIR, "2026FD.zip")+++def text(name):+ with open(os.path.join(DIR, name), encoding="utf-8") as fh:+ return fh.read()+++def run(args):+ out, err = io.StringIO(), io.StringIO()+ with redirect_stdout(out), redirect_stderr(err):+ code = ptr.main(args)+ return code, out.getvalue(), err.getvalue()+++class Index(unittest.TestCase):+ def setUp(self):+ self.rows = ptr.load_index(2026, offline=ZIP)++ def test_finds_her_four_2026_ptrs(self):+ hers = ptr.select(self.rows, ["pelosi"])+ self.assertEqual([r["doc_id"] for r in hers],+ ["20035553", "20035143", "20034836", "20033725"])+ self.assertEqual([r["filed"] for r in hers],+ ["2026-10-02", "2026-08-21", "2026-06-23", "2026-01-23"])+ self.assertEqual(hers[1]["url"],+ "https://disclosures-clerk.house.gov/public_disc/ptr-pdfs/2026/20035143.pdf")+ self.assertEqual(hers[0]["district"], "CA11")+ self.assertEqual(hers[0]["name"], "Hon. Nancy Pelosi")++ def test_member_names_in_any_order(self):+ for m in ("pelosi", "Nancy Pelosi", "Pelosi, Nancy", "PELOSI"):+ self.assertEqual(len(ptr.select(self.rows, [m])), 4, m)+ self.assertEqual(ptr.select(self.rows, ["Paul Pelosi"]), [])+ both = ptr.select(self.rows, ["pelosi", "gottheimer"])+ self.assertEqual(len(both), 5)++ def test_only_ptrs_unless_asked(self):+ ptrs = ptr.select(self.rows)+ self.assertTrue(all(r["type"] == "P" for r in ptrs))+ everything = ptr.select(self.rows, kind=None)+ self.assertGreater(len(everything), len(ptrs))+ other = next(r for r in everything if r["type"] == "C")+ self.assertIn("/financial-pdfs/2026/", other["url"])++ def test_since_and_newest_first(self):+ recent = ptr.select(self.rows, since="2026-10-07")+ self.assertEqual({r["filed"] for r in recent} <= {"2026-10-07", "2026-10-12"}, True)+ self.assertEqual(recent[0]["filed"], "2026-10-12")+ self.assertIn("Salazar", [r["last"] for r in recent])++ def test_reads_the_xml_inside_or_alone(self):+ import zipfile+ with zipfile.ZipFile(ZIP) as z:+ raw = z.read("2026FD.xml")+ self.assertTrue(raw.startswith(b"\xef\xbb\xbf")) # the Clerk's file has a BOM+ self.assertEqual(len(ptr.parse_index(ptr.read_index_bytes(raw), 2026)), len(self.rows))+ with self.assertRaises(ptr.PtrError):+ ptr.parse_index(b"not xml", 2026)+++class NewSinceLastCheck(unittest.TestCase):+ def test_alerts_once(self):+ with tempfile.TemporaryDirectory() as tmp:+ state = os.path.join(tmp, "state", "pelosi.json")+ base = ["new", "--member", "pelosi", "--offline", ZIP, "--year", "2026",+ "--state", state, "--portfolio", os.path.join(tmp, "none.json")]+ code, out, _ = run(base + ["--today", "2026-10-13"])+ self.assertEqual(code, 0)+ # first run: the last 45 days only+ self.assertIn("doc 20035553", out)+ self.assertNotIn("doc 20035143", out)+ with open(state) as fh:+ saved = json.load(fh)+ self.assertEqual(saved["seen"], ["20033725", "20034836", "20035143", "20035553"])+ code, out, _ = run(base + ["--today", "2026-10-13"])+ self.assertEqual(code, 1)+ self.assertIn("Nothing new", out)++ def test_a_new_doc_id_is_new(self):+ rows = ptr.select(ptr.load_index(2026, offline=ZIP), ["pelosi"])+ state = {"seen": ["20033725", "20034836", "20035553"], "last_check": "2026-08-01T09:00:00"}+ fresh = ptr.new_since(rows, state, datetime.date(2026, 10, 13))+ self.assertEqual([r["doc_id"] for r in fresh], ["20035143"])++ def test_dry_run_keeps_state(self):+ with tempfile.TemporaryDirectory() as tmp:+ state = os.path.join(tmp, "pelosi.json")+ run(["new", "--offline", ZIP, "--state", state, "--today", "2026-10-13",+ "--dry-run", "--portfolio", os.path.join(tmp, "none.json")])+ self.assertFalse(os.path.exists(state))+++class ParseReport(unittest.TestCase):+ def test_the_reel_alert_bloom_energy_calls(self):+ rep = ptr.parse_ptr_text(text("ptr-20035143.txt"))+ self.assertEqual(rep["name"], "Hon. Nancy Pelosi")+ self.assertEqual(rep["status"], "Member")+ self.assertEqual(rep["district"], "CA11")+ self.assertEqual(rep["doc_id"], "20035143")+ self.assertEqual(rep["filed"], "2026-08-21")+ self.assertEqual(len(rep["rows"]), 7)+ calls = [r for r in rep["rows"] if r["ticker"] == "BE" and r["asset_type"] == "OP"]+ self.assertEqual(len(calls), 2)+ big = calls[0]+ self.assertEqual(big["owner"], "SP")+ self.assertEqual(big["owner_name"], "spouse")+ self.assertEqual(big["type"], "P")+ self.assertEqual(big["date"], "2026-07-24")+ self.assertEqual(big["notified"], "2026-07-24")+ self.assertEqual(big["amount"], "$1,000,001 - $5,000,000")+ self.assertEqual((big["amount_low"], big["amount_high"]), (1000001, 5000000))+ self.assertEqual(big["option"], {"contracts": 100, "kind": "call", "strike": 100.0,+ "expires": "2027-06-17", "exercised": False})+ self.assertEqual(big["days_to_disclose"], 28)+ self.assertFalse(big["late"])+ self.assertEqual(big["asset"], "Bloom Energy Corporation Class A Common Stock")+ shares = [r for r in rep["rows"] if r["ticker"] == "BE" and r["asset_type"] == "ST"]+ self.assertEqual([r["shares"] for r in shares], [10000, 5000])+ llc = rep["rows"][-1]+ self.assertIsNone(llc["ticker"])+ self.assertEqual(llc["asset_type"], "AB")+ self.assertIn("luxury hotel", llc["description"])++ def test_render_says_public_and_flags_your_stocks(self):+ rep = ptr.parse_ptr_text(text("ptr-20035143.txt"))+ out = ptr.render_report(rep, watch={"INTC"})+ self.assertIn("100 call options, $100 strike, expires 2027-06-17", out)+ self.assertIn("INTC is on your list", out)+ self.assertIn("Not inside information", out)+ self.assertIn("45 days", out)+ self.assertNotIn(chr(0x2014), out)++ def test_joint_owner_and_account(self):+ rep = ptr.parse_ptr_text(text("ptr-20035590.txt"))+ self.assertEqual([(r["ticker"], r["owner"], r["type"]) for r in rep["rows"]],+ [("AMAT", "JT", "S"), ("MCD", "JT", "S (partial)")])+ self.assertEqual(rep["rows"][0]["account"], "Morgan Stanley - Select UMA Account # 1")+ self.assertEqual(rep["rows"][0]["notified"], "2026-10-06")++ def test_self_owned_partial_sales_and_crowded_columns(self):+ rep = ptr.parse_ptr_text(text("ptr-20035562-excerpt.txt"))+ tickers = [r["ticker"] for r in rep["rows"]]+ self.assertEqual(tickers, ["BRK.B", "BIIB", "BA", "BEP", "CVX", "CB", "GLW", "IBM"])+ self.assertTrue(all(r["owner"] == "" and r["owner_name"] == "self" for r in rep["rows"]))+ brk = rep["rows"][0]+ self.assertEqual(brk["type_name"], "partial sale")+ self.assertEqual(brk["account"], "UBS IRA Account")+ # "Corning Incorporated Common Stock P" : the type touches the asset text+ glw = rep["rows"][6]+ self.assertEqual((glw["type"], glw["asset"]), ("P", "Corning Incorporated Common Stock"))+ # the asset name runs over three lines+ self.assertEqual(rep["rows"][7]["asset"],+ "International Business Machines Corporation Common Stock")++ def test_page_breaks_exercises_and_exchanges(self):+ rep = ptr.parse_ptr_text(text("ptr-20033725-excerpt.txt"))+ by = {r["ticker"]: r for r in rep["rows"]}+ self.assertEqual(sorted(by), ["NVDA", "PYPL", "TEM", "VSNT", "VST"])+ tem = by["TEM"] # the row is split by a page header+ self.assertEqual(tem["asset"], "Tempus AI, Inc. - Class A Common Stock")+ self.assertEqual(tem["amount"], "$50,001 - $100,000")+ self.assertTrue(tem["option"]["exercised"])+ self.assertEqual(tem["option"]["strike"], 20.0)+ self.assertEqual(by["PYPL"]["date"], "2025-12-30")+ self.assertEqual(by["PYPL"]["shares"], 5000)+ self.assertEqual(by["VSNT"]["type_name"], "exchange")++ def test_late_filings_are_flagged(self):+ rep = ptr.parse_ptr_text(text("ptr-20035590.txt"), filed="2026-11-15")+ self.assertTrue(all(r["late"] for r in rep["rows"]))++ def test_parse_cli(self):+ path = os.path.join(DIR, "ptr-20035143.txt")+ code, out, _ = run(["parse", path, "--tickers", "BE", "--portfolio", "/nonexistent"])+ self.assertEqual(code, 0)+ self.assertIn("PTR 20035143, filed 2026-08-21", out)+ code, out, _ = run(["parse", path, "--json"])+ self.assertEqual(len(json.loads(out)["rows"]), 7)++ def test_dates(self):+ self.assertEqual(ptr.iso("8/21/2026"), "2026-08-21")+ self.assertEqual(ptr.iso("6/17/27"), "2027-06-17")+ self.assertIsNone(ptr.iso("13/45/2026"))+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_repo.py b/tests/test_repo.pynew file mode 100644index 0000000..502a3bd--- /dev/null+++ b/tests/test_repo.py@@ -0,0 +1,139 @@+import json+import os+import re+import unittest++from _load import ROOT++# v2, the day-trading pack: the eleven folders the reel's repo card shows+SKILLS = ["trader-scanner", "trader-news", "trader-entry", "trader-exit", "trader-timemachine",+ "trader-risk", "trader-budget", "trader-broker", "trader-alerts", "trader-analyst",+ "trader-pelosi"]+ABOUT = ("11 Claude skills for day trading: scan thousands of charts, track breaking news, time every "+ "entry and exit, and replay every outcome before you risk a dollar.")+# skills on the way to an order carry the safety block+ORDER_PATH = ["trader-scanner", "trader-entry", "trader-exit", "trader-timemachine", "trader-budget",+ "trader-pelosi", "trader-risk", "trader-broker", "trader-alerts"]+V1_ONLY = ["trader-copycat", "trader-screener", "trader-tax", "trader-rebalance"]+++def frontmatter(path):+ with open(path, encoding="utf-8") as fh:+ text = fh.read()+ m = re.match(r"^---\n(.*?)\n---\n", text, re.S)+ return (m.group(1) if m else ""), text+++def every_text_file():+ for base, dirs, files in os.walk(ROOT):+ dirs[:] = [d for d in dirs if d not in (".git", "__pycache__")]+ for f in files:+ if f.endswith((".md", ".py", ".json", ".csv", ".txt", ".xml")) or f == "LICENSE":+ yield os.path.join(base, f)+++class Repo(unittest.TestCase):+ def test_eleven_skill_folders_at_the_root(self):+ found = sorted(d for d in os.listdir(ROOT)+ if os.path.isfile(os.path.join(ROOT, d, "SKILL.md")))+ self.assertEqual(found, sorted(SKILLS))++ def test_root_matches_the_reel(self):+ root = sorted(d for d in os.listdir(ROOT) if not d.startswith(".git"))+ self.assertEqual(root, sorted([".claude-plugin", "LICENSE", "README.md", "tests"] + SKILLS))++ def test_frontmatter_name_and_description(self):+ for s in SKILLS:+ fm, text = frontmatter(os.path.join(ROOT, s, "SKILL.md"))+ self.assertIn("name: %s\n" % s, fm + "\n", s)+ self.assertRegex(fm, r"description: ", s)+ self.assertGreater(len(fm), 200, "%s description is too thin" % s)+ self.assertGreater(len(text.splitlines()), 60, s)++ def test_order_path_skills_carry_the_safety_rule(self):+ for s in ORDER_PATH:+ _, text = frontmatter(os.path.join(ROOT, s, "SKILL.md"))+ low = " ".join(text.lower().split())+ self.assertIn("not financial advice", low, s)+ self.assertIn("yes", low, s)++ def test_plugin_manifest_points_at_the_root_skills(self):+ with open(os.path.join(ROOT, ".claude-plugin", "plugin.json")) as fh:+ plugin = json.load(fh)+ self.assertEqual(plugin["name"], "day-trader-skill")+ self.assertEqual(plugin["skills"], "./")+ self.assertEqual(plugin["description"], ABOUT)+ with open(os.path.join(ROOT, ".claude-plugin", "marketplace.json")) as fh:+ market = json.load(fh)+ self.assertEqual(market["name"], "day-trader-skill")+ self.assertEqual(market["plugins"][0]["name"], "day-trader-skill")++ def test_readme_carries_the_reel_copy(self):+ with open(os.path.join(ROOT, "README.md"), encoding="utf-8") as fh:+ readme = " ".join(fh.read().split())+ self.assertTrue(readme.startswith("# The Day Trader skill"))+ for line in (ABOUT,+ "https://github.com/Jakeschincariol/day-trader-skill install skill",+ "/plugin marketplace add Jakeschincariol/day-trader-skill",+ "/plugin install day-trader-skill@day-trader-skill",+ "## Fine print"):+ self.assertIn(line, readme)+ for s in SKILLS:+ self.assertIn("/" + s, readme, s)++ def test_no_em_dashes_and_no_personal_email(self):+ for path in every_text_file():+ with open(path, encoding="utf-8", errors="replace") as fh:+ text = fh.read()+ rel = os.path.relpath(path, ROOT)+ if not rel.startswith(os.path.join("tests", "fixtures")): # fixtures are real data, kept as published+ self.assertNotIn("\u2014", text, rel)+ self.assertNotIn("jakeschincariol" + "@" + "gmail.com", text, rel) # built, so this file passes too++ def test_no_v1_only_skill_is_left_behind(self):+ for path in every_text_file():+ rel = os.path.relpath(path, ROOT)+ if rel.startswith("tests" + os.sep) or rel == "README.md":+ continue # the README points v1 users to the v1 commit+ with open(path, encoding="utf-8", errors="replace") as fh:+ text = fh.read()+ for old in V1_ONLY:+ self.assertNotIn(old, text, rel)++ def test_every_tool_runs_on_python_3_8(self):+ # no 3.9+ only modules or syntax in the tools (the README promises 3.8)+ for s in SKILLS:+ folder = os.path.join(ROOT, s)+ for f in os.listdir(folder):+ if not f.endswith(".py"):+ continue+ with open(os.path.join(folder, f), encoding="utf-8") as fh:+ src = fh.read()+ for bad in ("import zoneinfo", "from zoneinfo", ".removeprefix(", ".removesuffix(",+ "match ", "list[", "dict[", "tuple["):+ if bad == "match ":+ self.assertNotRegex(src, r"(?m)^\s+match \w+.*:$", "%s/%s" % (s, f))+ elif bad.endswith("["):+ self.assertNotRegex(src, r"(?<![\w.])%s" % re.escape(bad), "%s/%s" % (s, f))+ else:+ self.assertNotIn(bad, src, "%s/%s" % (s, f))++ def test_day_trading_limits_ship_in_the_example_config(self):+ with open(os.path.join(ROOT, "trader-budget", "config.example.json")) as fh:+ cfg = json.load(fh)+ for k in ("max_loss_per_trade_usd", "max_daily_loss_usd", "max_trades_per_day",+ "min_reward_risk", "require_stop", "no_entries_after", "flat_by"):+ self.assertIn(k, cfg, k)+ self.assertIs(cfg["require_stop"], True)+ self.assertIs(cfg.get("allow_short", False), False)+ self.assertIs(cfg.get("allow_margin", False), False)++ def test_paper_trading_is_the_default(self):+ with open(os.path.join(ROOT, "trader-budget", "config.example.json")) as fh:+ cfg = json.load(fh)+ self.assertIs(cfg["paper"], True)+ self.assertIs(cfg.get("allow_options", False), False)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_risk.py b/tests/test_risk.pynew file mode 100644index 0000000..6e2e470--- /dev/null+++ b/tests/test_risk.py@@ -0,0 +1,523 @@+import datetime+import io+import json+import os+import tempfile+import unittest+from contextlib import redirect_stdout, redirect_stderr++from _load import load, ROOT, FIX++check = load("trader-risk", "check")+ticket = load("trader-broker", "ticket")++CFG_PATH = os.path.join(ROOT, "trader-budget", "config.example.json")+TSLA_PATH = os.path.join(FIX, "trader-risk", "orders-tsla.json")+V1_ORDERS_PATH = os.path.join(FIX, "trader-risk", "orders-reel.json")+NOW = "2026-10-19 10:15"+TODAY = "2026-10-19"+V1_TODAY = "2026-10-13"+PRICES = {"AAPL": 341.27, "AXP": 309.84, "GOOGL": 353.78, "KO": 90.11, "BAC": 53.96}+QUOTE_TIME = datetime.datetime(2026, 10, 19, 14, 52, 13) # Yahoo's TSLA quote 366.475, 10:52:13 New York+# v1's rules with every day-trade check switched off: the long-term checks still hold+V1 = {"budget": 5000, "cash_buffer_pct": 10, "max_position_pct": 25, "max_order_usd": 2000, "min_order_usd": 5,+ "max_orders_per_day": 10, "require_stop": False, "no_entries_before": None, "no_entries_after": None,+ "max_trades_per_day": 0, "max_daily_loss_usd": 0, "max_loss_per_trade_usd": 0, "min_reward_risk": 0}+++def at(text):+ return check.parse_now(text)+++def cfg(**over):+ with open(CFG_PATH) as fh:+ c = json.load(fh)+ c.update(over)+ return c+++def v1(**over):+ c = dict(V1)+ c.update(over)+ return c+++def tsla(**over):+ with open(TSLA_PATH) as fh:+ o = json.load(fh)["orders"][0]+ o.update(over)+ return o+++def bracket(sym, qty, entry, stop, target):+ return {"symbol": sym, "side": "buy", "qty": str(qty), "type": "market", "time_in_force": "day",+ "order_class": "bracket", "take_profit_limit_price": "%.2f" % target,+ "stop_loss_stop_price": "%.2f" % stop,+ "plan": {"entry": entry, "stop": stop, "target": target}}+++def v1_orders():+ with open(V1_ORDERS_PATH) as fh:+ return json.load(fh)["orders"]+++def buy(sym, usd):+ return {"symbol": sym, "side": "buy", "notional": str(usd), "type": "market", "time_in_force": "day"}+++def placed(sym, side="buy", day=TODAY, max_loss=46.88, kind=None, status="placed"):+ r = {"symbol": sym, "side": side, "status": status, "date": day, "at": day + "T10:20:00-04:00"}+ if max_loss is not None:+ r["max_loss"] = max_loss+ if kind:+ r["kind"] = kind+ return r+++def verdicts(res):+ return [r["verdict"] for r in res["results"]]+++def reasons(res, i=0):+ return " | ".join(res["results"][i]["reasons"])+++def warnings(res, i=0):+ return " | ".join(res["results"][i]["warnings"])+++class TheReel(unittest.TestCase):+ def test_the_tsla_bracket_passes_every_check(self):+ res = check.check([tsla()], cfg(), now=at(NOW))+ r = res["results"][0]+ self.assertEqual(r["verdict"], "PASS", r["reasons"])+ self.assertEqual(r["reasons"], [])+ self.assertEqual(r["warnings"], [])+ self.assertEqual((r["kind"], r["entry_ref"], r["stop"], r["target"]), ("entry", 364.18, 358.32, 370.04))+ self.assertEqual((r["risk_per_share"], r["max_loss"], r["reward_risk"]), (5.86, 46.88, 1.0))+ self.assertEqual(r["value_usd"], 2913.44)+ self.assertEqual(res["cash_after"], 2086.56)+ self.assertEqual(res["date"], TODAY)+ self.assertIs(res["paper"], True)++ def test_nine_shares_is_blocked_by_the_max_loss_only(self):+ res = check.check([tsla(qty="9")], cfg(), now=at(NOW))+ self.assertEqual(verdicts(res), ["BLOCK"])+ self.assertEqual(res["results"][0]["reasons"],+ ["loss: 9 shares x 5.86 risk a share = $52.74 at the stop, over your $50 max loss per trade"])++ def test_fingerprint_is_shared_with_the_broker(self):+ o = tsla()+ self.assertEqual(check.fingerprint(o), ticket.fingerprint(o))+ self.assertEqual(check.fingerprint(dict(o, why="anything", plan={})), check.fingerprint(o))+ self.assertNotEqual(check.fingerprint(dict(o, qty="9")), check.fingerprint(o))+ self.assertNotEqual(check.fingerprint(dict(o, stop_loss_stop_price="358.00")), check.fingerprint(o))+ self.assertEqual(check.ALPACA_FIELDS, ticket.ALPACA_FIELDS)++ def test_cli(self):+ with tempfile.TemporaryDirectory() as d:+ out = os.path.join(d, "state", "risk.json")+ none = os.path.join(d, "none")+ buf = io.StringIO()+ with redirect_stdout(buf):+ code = check.main(["--orders", TSLA_PATH, "--config", CFG_PATH, "--portfolio", none,+ "--prices", none, "--state", none, "--now", NOW, "--out", out])+ text = buf.getvalue()+ self.assertEqual(code, 0)+ self.assertIn("PASS #1 buy TSLA 8 shares, entry", text)+ self.assertIn("entry 364.18 (the plan's entry), stop 358.32, target 370.04: risk 5.86 a share", text)+ self.assertIn("max loss $46.88 (limit $50), reward:risk 1.00 (min 1)", text)+ self.assertIn("1 passed, 0 blocked at 2026-10-19 10:15 New York", text)+ self.assertIn("not financial advice", text)+ with open(out) as fh:+ rec = json.load(fh)+ self.assertEqual(rec["date"], TODAY)+ self.assertEqual(rec["results"][0]["kind"], "entry")+ self.assertEqual(rec["results"][0]["fingerprint"], check.fingerprint(tsla()))+++class DayTradeChecks(unittest.TestCase):+ def one(self, order, now=NOW, **over):+ return check.check([order], cfg(**over), now=at(now))++ def test_a_stop_is_required(self):+ o = tsla()+ for k in ("order_class", "take_profit_limit_price", "stop_loss_stop_price", "plan"):+ o.pop(k)+ o["plan"] = {"entry": 364.18}+ res = self.one(o)+ self.assertIn("stop: no stop", reasons(res))+ res = self.one(o, require_stop=False, min_reward_risk=0)+ self.assertEqual(verdicts(res), ["PASS"])+ self.assertIn("no stop", warnings(res))++ def test_a_plan_stop_counts_but_warns(self):+ o = tsla()+ for k in ("order_class", "take_profit_limit_price", "stop_loss_stop_price"):+ o.pop(k)+ res = self.one(o)+ self.assertEqual(verdicts(res), ["PASS"])+ self.assertIn("in the plan only", warnings(res))+ self.assertEqual(res["results"][0]["max_loss"], 46.88)++ def test_stop_and_target_on_the_right_side(self):+ self.assertIn("must be below the entry 364.18", reasons(self.one(tsla(stop_loss_stop_price="365.00"))))+ res = self.one(tsla(take_profit_limit_price="364.00"))+ self.assertIn("target: the target 364.00 must be above the entry 364.18", reasons(res))++ def test_reward_risk(self):+ res = self.one(tsla(take_profit_limit_price="368.00"))+ self.assertIn("reward:risk: 0.65", reasons(res))+ self.assertEqual(verdicts(self.one(tsla(take_profit_limit_price="368.00"), min_reward_risk=0.5)), ["PASS"])++ def test_a_fresh_higher_price_is_the_entry(self):+ later = at("2026-10-19 10:55")+ res = check.check([tsla()], cfg(), prices={"TSLA": 366.475}, now=later, price_times={"TSLA": QUOTE_TIME})+ r = res["results"][0]+ self.assertEqual((r["entry_ref"], r["entry_ref_from"], r["risk_per_share"]), (366.48, "price", 8.16))+ self.assertIn("loss: 8 shares x 8.16 risk a share = $65.28", reasons(res))++ def test_a_stale_or_future_price_is_not_used(self):+ for now in ("2026-10-19 11:30", "2026-10-19 10:15"):+ res = check.check([tsla()], cfg(), prices={"TSLA": 366.475}, now=at(now),+ price_times={"TSLA": QUOTE_TIME})+ self.assertEqual(verdicts(res), ["PASS"], now)+ self.assertEqual(res["results"][0]["entry_ref"], 364.18)+ self.assertIn("older than 15 minutes", warnings(res))++ def test_a_lower_price_does_not_shrink_the_risk(self):+ res = check.check([tsla()], cfg(), prices={"TSLA": 360.00}, now=at(NOW))+ self.assertEqual(res["results"][0]["entry_ref"], 364.18)++ def test_a_limit_order_uses_its_limit_price(self):+ o = tsla(type="limit", limit_price="364.00")+ res = check.check([o], cfg(), prices={"TSLA": 366.475}, now=at(NOW))+ r = res["results"][0]+ self.assertEqual((r["entry_ref"], r["max_loss"], r["verdict"]), (364.0, 45.44, "PASS"))++ def test_daily_loss_and_trades_per_day(self):+ two = {"orders": [placed("AAPL"), placed("AMD")]}+ res = check.check([tsla()], cfg(), state=two, now=at(NOW))+ self.assertEqual(verdicts(res), ["PASS"])+ self.assertIn("today before this: 2 of 3 trades, $93.76 of $150 daily loss", res["results"][0]["info"][-1])+ three = {"orders": [placed("AAPL"), placed("AMD"), placed("NVDA")]}+ res = check.check([tsla()], cfg(), state=three, now=at(NOW))+ why = reasons(res)+ self.assertIn("trades: 3 entries placed today", why)+ self.assertIn("daily loss: $140.64 already at risk today plus $46.88 for this one = $187.52, over your $150",+ why)+ yesterday = {"orders": [placed(s, day="2026-10-16") for s in ("AAPL", "AMD", "NVDA")]}+ self.assertEqual(verdicts(check.check([tsla()], cfg(), state=yesterday, now=at(NOW))), ["PASS"])++ def test_exits_and_declines_do_not_count_as_trades(self):+ st = {"orders": [placed("AAPL"), placed("AAPL", side="sell", kind="exit", max_loss=None),+ placed("AMD", status="declined"), placed("NVDA", status="failed")]}+ res = check.check([tsla()], cfg(), state=st, now=at(NOW))+ self.assertEqual(verdicts(res), ["PASS"])+ self.assertEqual(res["today"]["entries_placed"], 1)++ def test_the_batch_counts_toward_the_daily_limits(self):+ orders = [bracket(s, 1, 50.0, 10.0, 90.0) for s in ("AAA", "BBB", "CCC", "DDD")]+ res = check.check(orders, cfg(), now=at(NOW))+ self.assertEqual(verdicts(res), ["PASS", "PASS", "PASS", "BLOCK"])+ why = reasons(res, 3)+ self.assertIn("trades: 0 entries placed today plus 3 passed earlier", why)+ self.assertIn("daily loss: $120 already at risk today plus $40 for this one = $160", why)++ def test_entry_window_new_york_time(self):+ cases = [("2026-10-19 09:44", "no new entries before 09:45 New York (it is 09:44)"),+ ("2026-10-19 15:31", "no new entries after 15:30 New York (it is 15:31)"),+ ("2026-10-19 08:00", "the market is closed (Mon 2026-10-19 08:00"),+ ("2026-10-19 16:05", "the market is closed"),+ ("2026-10-17 10:15", "the market is closed today (weekend"),+ ("2026-11-26 10:15", "the market is closed today (NYSE holiday: Thanksgiving Day"),+ ("2026-11-27 12:31", "no new entries after 12:30 New York"),+ ("2026-11-27 13:05", "the market is closed"),+ ("2026-11-02T14:40:00Z", "no new entries before 09:45 New York (it is 09:40)")]+ for now, want in cases:+ res = self.one(tsla(), now=now)+ self.assertIn("window: " + want, reasons(res), now)+ for now in ("2026-10-19 09:45", "2026-10-19 15:30", "2026-11-27 12:30", "2026-11-02T15:15:00Z",+ "2026-10-30T14:40:00Z", "2026-03-09T13:50:00Z"):+ self.assertEqual(verdicts(self.one(tsla(), now=now)), ["PASS"], now)+ self.assertIn("early close", " ".join(self.one(tsla(), now="2026-11-27 12:30")["warnings"]))+ res = self.one(tsla(), now="2026-10-17 10:15", no_entries_before=None, no_entries_after=None)+ self.assertEqual(verdicts(res), ["PASS"])+ with self.assertRaises(check.RiskError):+ self.one(tsla(), no_entries_before="9.45am")++ def test_the_window_uses_new_york_time_not_the_machine(self):+ self.assertEqual(check.to_eastern(at("2026-10-19 10:15")), datetime.datetime(2026, 10, 19, 10, 15))+ self.assertEqual(at("2026-10-19 10:15"), datetime.datetime(2026, 10, 19, 14, 15))+ self.assertEqual(at("2026-12-01 10:15"), datetime.datetime(2026, 12, 1, 15, 15))++ def test_pdt_guard(self):+ def trade(day):+ return [placed("X" + day[-2:], day=day), placed("X" + day[-2:], side="sell", day=day, kind="exit",+ status="filled", max_loss=None)]+ st = {"orders": trade("2026-10-13") + trade("2026-10-14") + trade("2026-10-15")}+ self.assertEqual(verdicts(self.one(tsla())), ["PASS"])+ res = check.check([tsla()], cfg(pdt_guard=True), state=st, now=at(NOW))+ self.assertIn("pdt: 3 day trades in the last 5 business days", reasons(res))+ self.assertEqual(verdicts(check.check([tsla()], cfg(), state=st, now=at(NOW))), ["PASS"])+ old = {"orders": trade("2026-10-12") + trade("2026-10-14") + trade("2026-10-15")}+ self.assertEqual(verdicts(check.check([tsla()], cfg(pdt_guard=True), state=old, now=at(NOW))), ["PASS"])+ pending = {"orders": trade("2026-10-14") + trade("2026-10-15") + [placed("AMD")]}+ res = check.check([tsla()], cfg(pdt_guard=True), state=pending, now=at(NOW))+ self.assertIn("pdt: 3 day trades", reasons(res))+ buy_only = {"orders": [placed("AMD", day="2026-10-15"), placed("NVDA", day="2026-10-16")]}+ self.assertEqual(check.day_trades(buy_only, TODAY)[0], 0)++ def test_a_short_entry_when_allowed(self):+ short = {"symbol": "TSLA", "side": "sell", "qty": "8", "type": "market", "time_in_force": "day",+ "order_class": "bracket", "take_profit_limit_price": "358.32", "stop_loss_stop_price": "370.04",+ "plan": {"entry": 364.18}}+ res = self.one(short)+ self.assertIn("short: selling more TSLA than you hold", reasons(res))+ res = self.one(short, allow_short=True)+ r = res["results"][0]+ self.assertEqual((r["verdict"], r["kind"], r["max_loss"], r["reward_risk"]), ("PASS", "entry", 46.88, 1.0))+ res = self.one(dict(short, stop_loss_stop_price="360.00"), allow_short=True)+ self.assertIn("must be above the entry 364.18 for a sell", reasons(res))++ def test_bracket_format(self):+ self.assertIn("whole-share qty", reasons(self.one(dict(tsla(qty=None), notional="2900"))))+ self.assertIn("whole shares only", reasons(self.one(tsla(qty="8.5"))))+ self.assertIn("time_in_force day or gtc", reasons(self.one(tsla(time_in_force="ioc"))))+ self.assertEqual(verdicts(self.one(tsla(time_in_force="gtc"))), ["PASS"])+ o = tsla()+ o.pop("take_profit_limit_price")+ self.assertIn("needs both take_profit_limit_price and stop_loss_stop_price", reasons(self.one(o)))+ self.assertIn("needs a stop_loss_stop_price", reasons(self.one(dict(tsla(), stop_loss_stop_price=None,+ stop_loss_limit_price="357.00"))))+ self.assertIn("as a string", warnings(self.one(tsla(stop_loss_stop_price=358.32))))++ def test_extended_hours(self):+ lim = {"symbol": "KO", "side": "buy", "qty": "1", "type": "limit", "limit_price": "90",+ "time_in_force": "gtc", "extended_hours": True}+ res = check.check([lim], v1(), prices=PRICES, today=V1_TODAY)+ self.assertEqual(verdicts(res), ["PASS"])+ res = check.check([dict(lim, type="market", limit_price=None)], v1(), prices=PRICES, today=V1_TODAY)+ self.assertIn("extended hours needs a limit order", reasons(res))+++class Exits(unittest.TestCase):+ PF = {"cash": 2086.56, "positions": [{"ticker": "TSLA", "shares": 8,+ "lots": [{"date": TODAY, "shares": 8, "cost": 2913.44}]}]}+ SELL = {"symbol": "TSLA", "side": "sell", "qty": "8", "type": "market", "time_in_force": "day"}++ def test_getting_out_is_never_blocked_by_the_day_limits(self):+ full = {"orders": [placed("TSLA"), placed("AMD"), placed("NVDA")] ++ [placed("T%d" % i, max_loss=1) for i in range(6)] ++ [placed("TSLA", side="sell", kind="exit", max_loss=None)]}+ c = cfg(blocked=["TSLA"], max_order_usd=100, max_daily_loss_usd=50)+ res = check.check([self.SELL], c, portfolio=self.PF, state=full, now=at("2026-10-19 15:58"))+ r = res["results"][0]+ self.assertEqual((r["verdict"], r["kind"]), ("PASS", "exit"), r["reasons"])+ why = warnings(res)+ for word in ("blocked:", "duplicate:", "daily limit:"):+ self.assertIn("exit, not blocked: " + word, why)+ self.assertNotIn("price", why)+ res = check.check([self.SELL], cfg(), portfolio=self.PF, now=at("2026-10-17 12:00"))+ self.assertEqual(verdicts(res), ["PASS"])++ def test_a_partial_exit_and_the_rest(self):+ half = dict(self.SELL, qty="4")+ res = check.check([half, half], cfg(), portfolio=self.PF, prices={"TSLA": 366.0}, now=at(NOW))+ self.assertEqual(verdicts(res), ["PASS", "PASS"])+ self.assertEqual([r["kind"] for r in res["results"]], ["exit", "exit"])+ self.assertIn("exit, not blocked: duplicate", warnings(res, 1))+ res = check.check([half, half, half], cfg(), portfolio=self.PF, prices={"TSLA": 366.0}, now=at(NOW))+ self.assertEqual(verdicts(res), ["PASS", "PASS", "BLOCK"])+ self.assertIn("short:", reasons(res, 2))++ def test_format_asset_and_short_still_apply_to_a_sell(self):+ res = check.check([dict(self.SELL, type="limit")], cfg(), portfolio=self.PF, now=at(NOW))+ self.assertIn("needs a limit_price", reasons(res))+ res = check.check([dict(self.SELL, qty="9")], cfg(), portfolio=self.PF, now=at(NOW))+ self.assertIn("short: selling more TSLA than you hold (8 shares)", reasons(res))+ res = check.check([self.SELL], cfg(), now=at(NOW))+ self.assertIn("record the fill first", reasons(res))++ def test_buy_then_sell_in_one_batch(self):+ res = check.check([tsla(), self.SELL], cfg(), now=at(NOW))+ self.assertEqual(verdicts(res), ["PASS", "PASS"])+ self.assertEqual(res["results"][1]["kind"], "exit")+++class V1Checks(unittest.TestCase):+ """v1's long-term checks still hold (day-trade checks off)."""++ def one(self, order, **over):+ return check.check([order], v1(**over), prices=PRICES, today=V1_TODAY)["results"][0]++ def test_the_five_buys_pass_on_a_fresh_5000_paper_account(self):+ res = check.check(v1_orders(), v1(), today=V1_TODAY)+ self.assertEqual(verdicts(res), ["PASS"] * 5)+ self.assertEqual(res["cash_after"], 500)+ self.assertEqual(res["results"][0]["value_usd"], 1250)+ self.assertEqual(res["results"][0]["amount"], "$1,250")++ def test_a_sixth_buy_is_blocked_three_ways(self):+ res = check.check(v1_orders() + [buy("AAPL", 100)], v1(), today=V1_TODAY)+ self.assertEqual(verdicts(res), ["PASS"] * 5 + ["BLOCK"])+ why = reasons(res, 5)+ self.assertIn("cash:", why)+ self.assertIn("position:", why)+ self.assertIn("duplicate:", why)++ def test_the_v2_config_blocks_buys_without_a_stop(self):+ res = check.check(v1_orders(), cfg(), now=at(NOW))+ self.assertEqual(verdicts(res)[0], "BLOCK")+ self.assertIn("stop: no stop", reasons(res))++ def test_max_and_min_order(self):+ self.assertIn("over your $2,000 max order", " ".join(self.one(buy("KO", 2500), max_position_pct=100)["reasons"]))+ self.assertIn("under your $5 minimum", " ".join(self.one(buy("KO", 2))["reasons"]))++ def test_blocked_list(self):+ r = self.one(buy("KO", 100), blocked=["KO"])+ self.assertEqual(r["verdict"], "BLOCK")+ self.assertIn("blocked list", r["reasons"][0])++ def test_options_off_unless_allowed(self):+ opt = {"symbol": "BE270617C00100000", "side": "buy", "qty": "1", "type": "limit",+ "limit_price": "12.50", "time_in_force": "day"}+ r = self.one(opt)+ self.assertEqual(r["verdict"], "BLOCK")+ self.assertIn("option", " ".join(r["reasons"]))+ r = self.one(opt, allow_options=True)+ self.assertEqual(r["verdict"], "PASS")+ self.assertTrue(r["warnings"])++ def test_crypto_and_junk_symbols(self):+ crypto = {"symbol": "BTC/USD", "side": "buy", "notional": "50", "type": "market", "time_in_force": "day"}+ self.assertIn("stocks and ETFs only", " ".join(self.one(crypto)["reasons"]))++ def test_format_rules(self):+ both = dict(buy("KO", 100), qty="1")+ self.assertIn("exactly one of qty or notional", " ".join(self.one(both)["reasons"]))+ lim = dict(buy("KO", 100), type="limit", limit_price="90")+ self.assertIn("market order with time_in_force day", " ".join(self.one(lim)["reasons"]))+ nolimit = {"symbol": "KO", "side": "buy", "qty": "1", "type": "limit", "time_in_force": "day"}+ self.assertIn("needs a limit_price", " ".join(self.one(nolimit)["reasons"]))+ bad = {"symbol": "KO", "side": "hold", "notional": "100"}+ self.assertIn("side must be buy or sell", " ".join(self.one(bad)["reasons"]))++ def test_numbers_should_be_strings(self):+ r = self.one({"symbol": "KO", "side": "buy", "notional": 100, "type": "market", "time_in_force": "day"})+ self.assertEqual(r["verdict"], "PASS")+ self.assertIn("as a string", r["warnings"][0])++ def test_share_orders_need_a_price(self):+ q = {"symbol": "ZZZZ", "side": "buy", "qty": "2", "type": "market", "time_in_force": "day"}+ self.assertIn("no price for ZZZZ", " ".join(self.one(q)["reasons"]))+ q["symbol"] = "KO"+ r = self.one(q)+ self.assertEqual(r["verdict"], "PASS")+ self.assertAlmostEqual(r["value_usd"], 180.22)++ def test_margin(self):+ r = check.check([buy("KO", 1500)], v1(cash_buffer_pct=0, max_position_pct=100),+ portfolio={"cash": 1000, "positions": []}, today=V1_TODAY)["results"][0]+ self.assertIn("margin", " ".join(r["reasons"]))++ PF = {"cash": 500.0, "positions": [{"ticker": "KO", "shares": 7.8571,+ "lots": [{"date": "2026-10-13", "shares": 7.8571, "cost": 708.0}]}]}++ def test_short_sales_are_blocked(self):+ sell = {"symbol": "KO", "side": "sell", "qty": "10", "type": "market", "time_in_force": "day"}+ r = check.check([sell], v1(), portfolio=self.PF, prices=PRICES, today=V1_TODAY)["results"][0]+ self.assertIn("short:", " ".join(r["reasons"]))+ sell["qty"] = "3"+ r = check.check([sell], v1(), portfolio=self.PF, prices=PRICES, today=V1_TODAY)["results"][0]+ self.assertEqual(r["verdict"], "PASS")++ def test_a_sell_frees_cash_for_a_later_buy(self):+ orders = [{"symbol": "KO", "side": "sell", "qty": "5", "type": "market", "time_in_force": "day"},+ buy("BAC", 450)]+ res = check.check(orders, v1(max_position_pct=100), portfolio=self.PF, prices=PRICES, today=V1_TODAY)+ self.assertEqual(verdicts(res), ["PASS", "PASS"])+ res = check.check([buy("BAC", 450)], v1(max_position_pct=100), portfolio=self.PF, prices=PRICES,+ today=V1_TODAY)+ self.assertEqual(verdicts(res), ["BLOCK"])++ def test_daily_limit_and_already_placed_today(self):+ st = {"orders": [{"symbol": "T%d" % i, "side": "buy", "status": "placed", "at": V1_TODAY + "T10:00:00"}+ for i in range(10)]}+ res = check.check([buy("KO", 100)], v1(), state=st, today=V1_TODAY)+ self.assertIn("daily limit", reasons(res))+ res = check.check([buy("KO", 100)], v1(), state=st, today="2026-10-14")+ self.assertEqual(verdicts(res), ["PASS"])+ ko = {"orders": [{"symbol": "KO", "side": "buy", "status": "placed", "at": V1_TODAY + "T10:00:00"}]}+ res = check.check([buy("KO", 100)], v1(), state=ko, today=V1_TODAY)+ self.assertIn("already placed today", reasons(res))+ declined = {"orders": [{"symbol": "KO", "side": "buy", "status": "declined", "at": V1_TODAY + "T10:00:00"}]}+ self.assertEqual(verdicts(check.check([buy("KO", 100)], v1(), state=declined, today=V1_TODAY)), ["PASS"])++ def test_live_account_warns(self):+ res = check.check([buy("KO", 100)], v1(paper=False), today=V1_TODAY)+ self.assertIn("LIVE", res["warnings"][0])+++class Cli(unittest.TestCase):+ def test_prices_file_freshness(self):+ with tempfile.TemporaryDirectory() as d:+ pp = os.path.join(d, "prices.json")+ with open(pp, "w") as fh:+ json.dump({"as_of": "2026-10-19T14:55:00Z", "prices": {"TSLA": 366.475},+ "detail": {"TSLA": {"time": "2026-10-19T14:52:13Z", "fetched": "2026-10-19T14:55:00Z"}}},+ fh)+ none = os.path.join(d, "none")+ base = ["--orders", TSLA_PATH, "--config", CFG_PATH, "--portfolio", none, "--prices", pp,+ "--state", none, "--no-write"]+ buf = io.StringIO()+ with redirect_stdout(buf):+ self.assertEqual(check.main(base + ["--now", "2026-10-19 10:55"]), 1)+ self.assertIn("8 shares x 8.16 risk a share = $65.28", buf.getvalue())+ with redirect_stdout(io.StringIO()):+ self.assertEqual(check.main(base + ["--now", "2026-10-19 11:30"]), 0)++ def test_v1_orders_with_a_v1_config_file(self):+ with tempfile.TemporaryDirectory() as d:+ c = os.path.join(d, "config.json")+ with open(c, "w") as fh:+ json.dump(v1(), fh)+ none = os.path.join(d, "none")+ out = os.path.join(d, "state", "risk.json")+ buf = io.StringIO()+ with redirect_stdout(buf):+ code = check.main(["--orders", V1_ORDERS_PATH, "--config", c, "--portfolio", none, "--prices", none,+ "--state", none, "--today", V1_TODAY, "--out", out])+ self.assertEqual(code, 0)+ self.assertIn("5 passed, 0 blocked", buf.getvalue())+ with open(out) as fh:+ rec = json.load(fh)+ self.assertEqual(rec["date"], V1_TODAY)+ self.assertTrue(all(len(r["fingerprint"]) == 16 for r in rec["results"]))+ bad = os.path.join(d, "orders.json")+ with open(bad, "w") as fh:+ json.dump({"orders": v1_orders() + [buy("AAPL", 100)]}, fh)+ with redirect_stdout(io.StringIO()):+ code = check.main(["--orders", bad, "--config", c, "--portfolio", none, "--prices", none,+ "--state", none, "--today", V1_TODAY, "--no-write"])+ self.assertEqual(code, 1)++ def test_errors_are_one_line(self):+ err = io.StringIO()+ with redirect_stderr(err):+ self.assertEqual(check.main(["--orders", "/nonexistent.json", "--no-write"]), 1)+ self.assertIn("no orders file", err.getvalue())+ err = io.StringIO()+ with redirect_stderr(err):+ self.assertEqual(check.main(["--orders", TSLA_PATH, "--now", "noon", "--no-write"]), 1)+ self.assertIn("--now wants", err.getvalue())+ self.assertNotIn("Traceback", err.getvalue())+ err = io.StringIO()+ with redirect_stderr(err):+ self.assertEqual(check.main(["--orders", TSLA_PATH, "--today", "monday", "--no-write"]), 1)+ self.assertIn("--today wants", err.getvalue())+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_scanner.py b/tests/test_scanner.pynew file mode 100644index 0000000..393ed61--- /dev/null+++ b/tests/test_scanner.py@@ -0,0 +1,646 @@+import datetime+import io+import json+import os+import shutil+import tempfile+import unittest+import urllib.error+from contextlib import redirect_stdout, redirect_stderr++from _load import load, FIX++scan = load("trader-scanner", "scan")++SDIR = os.path.join(FIX, "trader-scanner")+WALL = os.path.join(SDIR, "wall5m-2026-10-19.json.gz") # 234 real 5-min charts, Oct 19 2026+DAILY = os.path.join(SDIR, "daily-spark-2026-10-19.json") # 19 real daily charts as one spark answer+LIVE = os.path.join(SDIR, "spark-3mo-live-2026-10-20.json") # a real 20-symbol spark answer+SYMDIR = os.path.join(SDIR, "symdir") # trimmed Nasdaq Trader files of Oct 19+SPARK5 = os.path.join(SDIR, "spark-5m-live-2026-10-20-1001.json") # real, fetched 10:01:47 AM ET Oct 20+TSLA5 = os.path.join(SDIR, "TSLA-5m-live-2026-10-20-1001.json") # real v8, fetched with it+DT = datetime.datetime+D = datetime.date+++def run(argv):+ out, err = io.StringIO(), io.StringIO()+ with redirect_stdout(out), redirect_stderr(err):+ code = scan.main(argv)+ return code, out.getvalue(), err.getvalue()+++def ts(et_text):+ """New York wall-clock text -> unix seconds (through the tool's own DST rule)."""+ utc = scan.eastern_to_utc(DT.strptime(et_text, "%Y-%m-%d %H:%M:%S" if et_text.count(":") == 2+ else "%Y-%m-%d %H:%M"))+ return int((utc - DT(1970, 1, 1)).total_seconds())+++def bars_series(day, closes, highs=None, lows=None, start="09:30", extra=None):+ """A v8-like series of 5-min bars from `start` on `day` (YYYY-MM-DD)."""+ t0 = DT.strptime(day + " " + start, "%Y-%m-%d %H:%M")+ t = [ts((t0 + datetime.timedelta(minutes=5 * i)).strftime("%Y-%m-%d %H:%M")) for i in range(len(closes))]+ s = {"t": t, "c": list(closes), "h": list(highs or [c + 0.1 if c is not None else None for c in closes]),+ "l": list(lows or [c - 0.1 if c is not None else None for c in closes]), "o": None,+ "v": [1000] * len(closes), "meta": {}}+ for when, c in (extra or []):+ s["t"].append(ts(when))+ for k in ("c", "h", "l"):+ s[k].append(c)+ s["v"].append(10)+ return s+++class Universe(unittest.TestCase):+ def setUp(self):+ texts = {}+ for f in scan.NASDAQ_FILES:+ with open(os.path.join(SYMDIR, f), encoding="utf-8") as fh:+ texts[f] = fh.read()+ self.kept, self.counts, self.created = scan.build_universe(texts)+ self.rows = {}+ for f in scan.NASDAQ_FILES:+ rows, _ = scan.parse_symdir(texts[f])+ for r in rows:+ self.rows[(r.get("Symbol") or r.get("ACT Symbol"))] = r++ def why(self, sym):+ return scan.classify(self.rows[sym])++ def test_the_kept_list(self):+ self.assertEqual([s for s, _ in self.kept],+ ["A", "AACG", "AACI", "AAPL", "AME", "AMX", "ARLP", "BEP", "BF.B", "BRK.B", "IRS",+ "KO", "OBAI", "ORGO", "PFBC", "PRT", "TSLA"])+ self.assertEqual(self.counts["rows"], 36)+ self.assertEqual(self.created, "2026-10-19 10:01")+ self.assertEqual(dict(self.kept)["TSLA"], "Tesla, Inc. - Common Stock")++ def test_one_case_per_rule(self):+ cases = {+ "ZAZZT": "test issue", "ZZZTX": "test issue", # 1. test issues+ "AAAP": "ETF", "SPY": "ETF", # 1. ETFs+ "ABR$D": "not a plain ticker", # 2. $ preferred+ "AAC.U": "unit / warrant / right suffix", # 2. .U unit+ "AAC.W": "unit / warrant / right suffix", # 2. .W warrant+ "AACIW": "warrant", # 3. warrants+ "HAVAR": "unit or right", # 3. SPAC rights "Rights that convert..."+ "ATMP": "note", # 3. an ETN with the ETF flag at N+ "GJH": "coupon", "EAI": "coupon", # 3. a % coupon (bonds too)+ "CDZIP": "depositary", # 3. depositary shares that carry a preferred+ "AACIU": "unit", "ARCIU": "unit", # 5. "- Units", "- Unit"+ "AACPR": "right", "GENVR": "right", # 5. rights, contingent value rights+ "BHK": "bond", # 5. a bond fund with no share wording+ "CHTRP": "preferred", # 5. preferred stock+ "AAPL": "keep", "AACI": "keep", "AACG": "keep", # 4. common, ordinary, ADS+ "PFBC": "keep", "OBAI": "keep", # 4. "Preferred Bank", "Our Bond": common stock+ "AMX": "keep", "IRS": "keep", # 4. ADS "the right to receive", Global depositary+ "ARLP": "keep", "BEP": "keep", "PRT": "keep", # 4. partnership and trust units+ "BRK.B": "keep", "BF.B": "keep", # 2. one class letter after a dot+ "AME": "keep", "ORGO": "keep", # 6. plain names+ }+ for sym, want in cases.items():+ self.assertEqual(self.why(sym), want, sym)++ def test_nextshares_rule(self):+ row = {"Symbol": "ZXYZ", "Security Name": "Some Fund - NextShares", "Test Issue": "N",+ "ETF": "N", "NextShares": "Y"}+ self.assertEqual(scan.classify(row), "NextShares")++ def test_not_a_symbol_file(self):+ with self.assertRaises(scan.ScanError):+ scan.parse_symdir("<html>maintenance</html>")+++class Time(unittest.TestCase):+ def test_dst_and_clock(self):+ self.assertEqual(scan.eastern_offset(DT(2026, 3, 8, 6, 59)), -5)+ self.assertEqual(scan.eastern_offset(DT(2026, 3, 8, 7, 0)), -4)+ self.assertEqual(scan.eastern_offset(DT(2026, 11, 1, 5, 59)), -4)+ self.assertEqual(scan.eastern_offset(DT(2026, 11, 1, 6, 0)), -5)+ self.assertEqual(scan.ts_to_eastern(1792416600), DT(2026, 10, 19, 9, 30)) # TSLA's first bar+ self.assertEqual(scan.ts_to_eastern(ts("2026-12-01 09:30")), DT(2026, 12, 1, 9, 30))+ self.assertEqual(scan.parse_now("2026-10-19 10:15"), DT(2026, 10, 19, 14, 15))+ self.assertEqual(scan.parse_now("2026-12-01 10:15"), DT(2026, 12, 1, 15, 15))+ self.assertEqual(scan.parse_now("2026-10-19T14:15:00Z"), DT(2026, 10, 19, 14, 15))+ self.assertEqual(scan.clock_label(DT(2026, 10, 19, 10, 15)), "10:15 AM")+ self.assertEqual(scan.clock_label(datetime.time(12, 5)), "12:05 PM")+ with self.assertRaises(scan.ScanError):+ scan.parse_now("tomorrow")+ with self.assertRaises(scan.ScanError):+ scan.parse_hhmm("25:00")+++class Spark(unittest.TestCase):+ def test_a_real_spark_answer(self):+ with open(LIVE, encoding="utf-8") as fh:+ text = fh.read()+ wanted = {scan.to_yahoo(s): s for s in ["AAPL", "TSLA", "BRK.B", "ZZZZQX"]}+ data = scan.parse_spark(text, wanted)+ self.assertEqual(len(data), 19) # 20 asked; Yahoo silently drops the made-up ZZZZQX+ self.assertNotIn("ZZZZQX", data)+ self.assertIn("BRK.B", data) # BRK-B comes back as ours+ t = data["TSLA"]+ self.assertEqual(len(t["t"]), 65)+ self.assertIsNone(t["h"]) # spark is closes only+ self.assertEqual(t["c"][-1], 368.06)+ self.assertEqual(t["meta"]["regularMarketVolume"], 38651173)+ self.assertEqual(data["AMC"]["meta"]["regularMarketPrice"], 2.98)+ closes = scan.daily_closes(t, scan.parse_now("2026-10-20 09:14"))+ self.assertEqual(closes[-1], (D(2026, 10, 19), 368.06))+ # the same answer read during Monday's session: Monday's bar is still in progress+ closes = scan.daily_closes(t, scan.parse_now("2026-10-19 12:00"))+ self.assertEqual(closes[-1][0], D(2026, 10, 16))++ def test_spark_errors(self):+ too_many = '{"spark":{"result":null,"error":{"code":"Bad Request",' \+ '"description":"Number of symbols needs to be less than or equal to 20"}}}'+ with self.assertRaises(scan.ScanError) as cm:+ scan.parse_spark(too_many)+ self.assertIn("less than or equal to 20", str(cm.exception))+ self.assertEqual(scan.parse_spark('{"spark":{"result":[],"error":null}}'), {})+ with self.assertRaises(scan.ScanError):+ scan.parse_spark('{"chart":{}}')++ def test_urls(self):+ self.assertEqual(scan.spark_path(["BRK.B", "tsla"], "3mo", "1d"),+ "/v7/finance/spark?symbols=BRK-B,TSLA&range=3mo&interval=1d")+ self.assertEqual(scan.chart_path("TSLA", "1d", "5m"), "/v8/finance/chart/TSLA?range=1d&interval=5m")+++class Network(unittest.TestCase):+ """429s and 5xx without the network."""++ def setUp(self):+ self.calls, self.sleeps = [], []+ self._get, self._sleep = scan.http_get, scan.SLEEP+ scan.SLEEP = self.sleeps.append+ with open(LIVE, encoding="utf-8") as fh:+ self.body = fh.read()++ def tearDown(self):+ scan.http_get, scan.SLEEP = self._get, self._sleep++ def answers(self, codes):+ codes = list(codes)++ def fake(url, timeout=20):+ self.calls.append(url.split("/v")[0])+ code = codes.pop(0) if codes else 200+ if code != 200:+ raise urllib.error.HTTPError(url, code, "x", {}, io.BytesIO(b""))+ return self.body+ scan.http_get = fake++ def test_429_falls_back_then_waits_once(self):+ self.answers([429, 429, 200])+ text = scan.yahoo_get("/v7/finance/spark?symbols=TSLA&range=3mo&interval=1d")+ self.assertEqual(text, self.body)+ self.assertEqual(self.calls, ["https://query2.finance.yahoo.com", "https://query1.finance.yahoo.com",+ "https://query2.finance.yahoo.com"])+ self.assertEqual(self.sleeps, [scan.BACKOFF])++ def test_5xx_goes_to_query1_without_waiting(self):+ self.answers([503, 200])+ scan.yahoo_get("/v8/finance/chart/TSLA?range=1d&interval=5m")+ self.assertEqual(len(self.calls), 2)+ self.assertEqual(self.sleeps, [])++ def test_429_for_good_is_reported_as_partial(self):+ self.answers([200] + [429] * 10)+ syms = ["AAPL", "TSLA", "NVDA", "BRK.B", "AMC", "ZZZZQX", "MSFT", "AMZN", "META", "GOOGL", "PLTR", "AMD",+ "INTC", "F", "BAC", "KO", "PLUG", "SOFI", "RIVN", "LCID"] + ["X%02d" % i for i in range(20)]+ data, failed = scan.fetch_spark(syms, "3mo", "1d", 0.3)+ self.assertEqual(len(data), 19)+ self.assertEqual(failed["ZZZZQX"], "no data from Yahoo")+ self.assertEqual(len(failed), 21)+ self.assertIn("HTTP 429", failed["X00"])+ self.assertEqual(self.sleeps, [0.3, scan.BACKOFF]) # a pause between batches, one backoff+ hits, counts, _ = scan.scan_daily(data, syms, scan.parse_now("2026-10-20 09:14"), 5, 1000000)+ self.assertEqual(counts["requested"], 40)+ self.assertEqual(counts["fetched"], 19)++ def test_a_404_is_final(self):+ self.answers([404])+ with self.assertRaises(scan.ScanError):+ scan.yahoo_get("/v8/finance/chart/NOPE?range=1d&interval=5m")+ self.assertEqual(len(self.calls), 1)+++class Daily(unittest.TestCase):+ # Hand-checked from the closes (see the numbers in the comments): through Fri Oct 16 2026.+ EXPECT = {+ "BLK": ["breakout_20d"], # 1134.38 > 1120.78, the best close of the 20 before+ "CI": ["breakout_20d"], # 302.30 > 298.81+ "XOM": ["breakout_20d"], # 178.98 > 177.01+ "HD": ["breakout_20d"], # 309.63 > 308.24+ "KO": ["breakout_20d"], # 93.90 > 92.00 (a closing high; its intraday high was not taken out)+ "CCL": ["bull_flag"], # up 18.4 % over the 10 sessions, last 5 closes in a 3.2 % range+ "RCL": ["bull_flag"], # up 16.3 %, 2.6 % range+ "F": ["reclaim_ma20"], # 12.31 under 12.41, then 12.43 over 12.37+ "JPM": ["reclaim_ma20"], # 335.53 under 336.15, then 339.72 over 335.65+ "GE": ["reclaim_ma20"], # 312.00 under 312.90, then 313.83 over 312.88+ "BAC": ["oversold"], # RSI 24.0+ "PLUG": ["oversold"], # RSI 21.0+ "MS": ["oversold"], # RSI 25.5+ "RIVN": ["oversold"], # RSI 22.7+ "PNC": ["oversold_bounce"], # RSI 27.1 on Thursday, closed up Friday (214.94 -> 217.39), RSI 34.0+ }+ # The reel's refs/scan.py tags for the same charts (it used highs and lows): all reproduced.+ REEL = {"BLK": "breakout_20d", "CI": "breakout_20d", "XOM": "breakout_20d", "HD": "breakout_20d",+ "CCL": "bull_flag", "F": "reclaim_ma20", "JPM": "reclaim_ma20", "GE": "reclaim_ma20",+ "BAC": "oversold", "PLUG": "oversold", "MS": "oversold", "RIVN": "oversold"}++ def setUp(self):+ self.data, self.errors = scan.load_offline(DAILY)+ self.syms = sorted(self.data)++ def test_setups_before_the_open(self):+ self.assertEqual(len(self.syms), 19)+ hits, counts, last = scan.scan_daily(self.data, self.syms, scan.parse_now("2026-10-19 09:00"), 0, 0)+ self.assertEqual({h["symbol"]: h["setups"] for h in hits}, self.EXPECT)+ self.assertEqual(last, D(2026, 10, 16))+ self.assertEqual(counts, {"requested": 19, "fetched": 19, "illiquid": 0, "short": 0, "scanned": 19,+ "hits": 15})+ for sym, tag in self.REEL.items():+ self.assertIn(tag, self.EXPECT[sym], sym)+ blk = [h for h in hits if h["symbol"] == "BLK"][0]+ self.assertEqual((blk["price"], blk["rsi"], blk["close_date"]), (1134.38, 63.7, "2026-10-16"))++ def test_the_in_progress_bar_is_dropped(self):+ before = scan.scan_daily(self.data, self.syms, scan.parse_now("2026-10-19 09:00"), 0, 0)+ during = scan.scan_daily(self.data, self.syms, scan.parse_now("2026-10-19 10:50"), 0, 0)+ self.assertEqual(before, during)+ bars = scan.daily_closes(self.data["TSLA"], scan.parse_now("2026-10-19 15:59"))+ self.assertEqual(bars[-1], (D(2026, 10, 16), 354.7200012207031))+ bars = scan.daily_closes(self.data["TSLA"], scan.parse_now("2026-10-19 16:00"))+ self.assertEqual(bars[-1], (D(2026, 10, 19), 365.7950134277344))++ def test_half_day_bar_completes_at_one(self):+ s = {"t": [ts("2026-11-25 09:30"), ts("2026-11-27 09:30")], "c": [10.0, 11.0], "meta": {}}+ self.assertEqual(len(scan.daily_closes(s, scan.parse_now("2026-11-27 12:59"))), 1)+ self.assertEqual(len(scan.daily_closes(s, scan.parse_now("2026-11-27 13:00"))), 2)++ def test_liquidity_filter(self):+ # meta is Yahoo's as of 10:50 AM Monday, so the volume is the day's so far+ hits, counts, _ = scan.scan_daily(self.data, self.syms, scan.parse_now("2026-10-19 10:50"), 5, 1000000)+ self.assertEqual(sorted(h["symbol"] for h in hits), ["BAC", "CCL", "F", "JPM", "KO", "RIVN", "XOM"])+ self.assertEqual(counts["illiquid"], 8) # PLUG under $5; BLK, CI, HD, RCL, GE, MS, PNC under 1M so far+ self.assertEqual(counts["scanned"], 11)++ def test_short_and_empty_charts(self):+ s = {"t": [ts("2026-10-%02d 09:30" % d) for d in range(1, 11)], "c": [10.0] * 10,+ "meta": {"regularMarketPrice": 10, "regularMarketVolume": 5000000}}+ hits, counts, last = scan.scan_daily({"X": s, "E": {"t": [], "c": [], "meta": {}}}, ["X", "E", "GONE"],+ scan.parse_now("2026-10-20 09:00"), 5, 1000000)+ self.assertEqual(hits, [])+ self.assertEqual((counts["fetched"], counts["short"], counts["illiquid"], counts["scanned"]), (2, 1, 1, 0))+ self.assertIsNone(last)++ def test_rsi_matches_the_reel_math(self):+ self.assertIsNone(scan.rsi([1.0] * 10))+ self.assertEqual(scan.rsi([float(x) for x in range(1, 40)]), 100.0)+ closes = [44.34, 44.09, 44.15, 43.61, 44.33, 44.83, 45.10, 45.42, 45.84, 46.08, 45.89, 46.03, 45.61,+ 46.28, 46.28]+ self.assertAlmostEqual(scan.rsi(closes), 70.46, places=1) # Wilder's textbook example+++class Orb(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.data, cls.errors = scan.load_offline(WALL)+ cls.syms = sorted(set(cls.data) | set(cls.errors))++ def scan_at(self, now, min_price=0, syms=None, or_minutes=15):+ day, cutoff = scan.orb_window(scan.parse_now(now), None, or_minutes, datetime.time(15, 30))+ return scan.scan_orb(self.data, syms or self.syms, day, cutoff, or_minutes, min_price, 0)++ def test_the_reel_scan_at_1015(self):+ hits, counts, failed = self.scan_at("2026-10-19 10:15")+ self.assertEqual(len(self.syms), 234)+ self.assertEqual(counts["scanned"], 231) # usable charts+ self.assertEqual(len(hits), 42)+ self.assertEqual(self.errors, {"SQ": "no data for SQ: No data found, symbol may be delisted"})+ self.assertEqual(counts["unusable"], 2) # WBD (no bars), PARA (missing bars)+ tsla = [h for h in hits if h["symbol"] == "TSLA"][0]+ self.assertEqual(tsla, {"symbol": "TSLA", "setups": ["orb"], "price": 364.18, "at": "10:15 AM",+ "bar_start": "10:10", "bar_index": 8, "or_high": 362.18, "or_low": 354.47,+ "pct_over": 0.55})+ self.assertEqual(hits[0]["symbol"], "AMC") # sorted by time, then symbol+ self.assertEqual([h["at"] for h in hits], sorted([h["at"] for h in hits], key=lambda x: scan.parse_hhmm(+ x[:-3]).hour % 12 * 60 + int(x[-5:-3])))+ self.assertEqual(sum(1 for h in hits if h["at"] == "10:15 AM"), 11)+ lly = [h for h in hits if h["symbol"] == "LLY"][0]+ self.assertEqual((lly["price"], lly["or_high"], lly["pct_over"]), (1255.0, 1254.99, 0.0))++ def test_price_floor(self):+ hits, counts, _ = self.scan_at("2026-10-19 10:15", min_price=5)+ self.assertEqual(len(hits), 41) # AMC at $2.97 drops out+ self.assertEqual(counts["illiquid"], 9)+ self.assertNotIn("AMC", [h["symbol"] for h in hits])++ def test_in_progress_bar_and_no_breakout_yet(self):+ hits, _, _ = self.scan_at("2026-10-19 10:14", syms=["TSLA"])+ self.assertEqual(hits, []) # the 10:10 bar is not done until 10:15+ hits, _, _ = self.scan_at("2026-10-19 10:15", syms=["TSLA"])+ self.assertEqual(hits[0]["at"], "10:15 AM")++ def test_the_live_tick_is_dropped(self):+ s = self.data["TSLA"]+ self.assertEqual(scan.ts_to_eastern(s["t"][-1]), DT(2026, 10, 19, 10, 58, 7)) # off the grid+ bars = scan.session_bars(s, D(2026, 10, 19), DT(2026, 10, 19, 10, 59))+ self.assertEqual(len(bars), 17) # 9:30 to 10:50; 10:55 in progress, the tick dropped+ self.assertTrue(scan.usable(bars, D(2026, 10, 19), DT(2026, 10, 19, 10, 59), 3))+ hits, _, _ = self.scan_at("2026-10-19 11:00", syms=["TSLA"])+ self.assertEqual(hits[0]["price"], 364.18) # still the first close above the range++ def test_stage_one_is_a_necessary_condition(self):+ day, cut = D(2026, 10, 19), DT(2026, 10, 19, 10, 15)+ for sym, s in self.data.items():+ bars = scan.session_bars(s, day, cut)+ if scan.usable(bars, day, cut, 3) and scan.orb_hit(bars, 3):+ self.assertTrue(scan.orb_candidate(bars, 3), sym)++ def test_confirm_uses_the_v8_highs(self):+ spark_like = {k: dict(v, h=None, l=None) for k, v in self.data.items()} # closes only, like spark+ asked = []++ def confirm(sym):+ asked.append(sym)+ return self.data[sym]+ hits, counts, failed = scan.scan_orb(spark_like, self.syms, D(2026, 10, 19), DT(2026, 10, 19, 10, 15), 15,+ 0, 0, confirm)+ self.assertEqual(len(hits), 42)+ self.assertEqual(counts["candidates"], len(asked))+ self.assertLess(len(asked), 231) # stage 1 skipped most charts++ def broken(sym):+ raise scan.ScanError("Yahoo answered HTTP 429 for /v8/finance/chart/%s" % sym)+ hits, counts, failed = scan.scan_orb(spark_like, ["TSLA", "KO"], D(2026, 10, 19),+ DT(2026, 10, 19, 10, 15), 15, 0, 0, broken)+ self.assertEqual(hits, [])+ self.assertIn("429", failed["TSLA"])++ def test_a_missing_bar_makes_a_chart_unusable(self):+ s = bars_series("2026-10-20", [10, 10.2, 10.1, None, 10.5, 10.6, 10.7, 10.8, 10.9])+ bars = scan.session_bars(s, D(2026, 10, 20), DT(2026, 10, 20, 10, 15))+ self.assertFalse(scan.usable(bars, D(2026, 10, 20), DT(2026, 10, 20, 10, 15), 3))++ def test_winter_time_half_day_and_a_30_minute_range(self):+ # Fri Nov 27 2026: standard time (UTC-5) and a 1:00 PM close+ closes = [100, 101, 100.5, 100.8, 101.2, 100.9, 101.5] + [101.0] * 40+ s = bars_series("2026-11-27", closes, highs=[c + 0.2 for c in closes])+ hits, counts, _ = scan.scan_orb({"X": s}, ["X"], D(2026, 11, 27), DT(2026, 11, 27, 12, 0), 30, 0, 0)+ self.assertEqual(counts["scanned"], 1)+ self.assertEqual(hits[0]["at"], "10:05 AM") # range 9:30 to 10:00 (high 101.4), 10:00 bar 101.5+ self.assertEqual(hits[0]["or_high"], 101.4)+ bars = scan.session_bars(s, D(2026, 11, 27), DT(2026, 11, 27, 12, 59))+ self.assertEqual(scan.ts_to_eastern(s["t"][0]), DT(2026, 11, 27, 9, 30))+ self.assertEqual(len(bars), 41) # 9:30 to 12:50 done at 12:59; bars after 1:00 dropped+ with self.assertRaises(scan.ScanError) as cm:+ scan.orb_window(scan.parse_now("2026-11-27 13:10"), None, 15, datetime.time(15, 30))+ self.assertIn("closed at 1:00 PM", str(cm.exception))++ def test_window_messages(self):+ until = datetime.time(15, 30)++ def msg(now, at=None, until=until):+ with self.assertRaises(scan.ScanError) as cm:+ scan.orb_window(scan.parse_now(now), at, 15, until)+ return str(cm.exception)+ self.assertIn("weekend", msg("2026-10-17 10:15"))+ self.assertIn("Thanksgiving", msg("2026-11-26 10:15"))+ self.assertIn("Run orb again after 9:50 AM", msg("2026-10-19 09:40"))+ self.assertIn("Run orb again after 9:50 AM", msg("2026-10-19 09:47"))+ self.assertIn("expired", msg("2026-10-19 15:45"))+ self.assertIn("expired", msg("2026-10-19 11:30", until=datetime.time(11, 0)))+ self.assertIn("closed at 4:00 PM", msg("2026-10-19 16:30"))+ self.assertIn("later than now", msg("2026-10-19 10:00", at=datetime.time(10, 15)))+ self.assertIn("after the 4:00 PM close", msg("2026-10-19 17:00", at=datetime.time(16, 30)))+ self.assertEqual(scan.orb_window(scan.parse_now("2026-10-19 16:30"), datetime.time(10, 15), 15, until),+ (D(2026, 10, 19), DT(2026, 10, 19, 10, 15)))+ self.assertEqual(scan.orb_window(scan.parse_now("2026-10-19 09:50"), None, 15, until)[1],+ DT(2026, 10, 19, 9, 50))+ with self.assertRaises(scan.ScanError):+ scan.orb_window(scan.parse_now("2026-10-19 10:15"), None, 7, until)+++class LiveFiveMinute(unittest.TestCase):+ """A real spark 5-minute answer and TSLA's v8 chart, fetched at 10:01:47 AM ET on Tue Oct 20 2026."""++ def setUp(self):+ with open(SPARK5, encoding="utf-8") as fh:+ self.spark = scan.parse_spark(fh.read())+ with open(TSLA5, encoding="utf-8") as fh:+ self.v8 = scan.parse_chart(fh.read(), "TSLA")+ self.now = scan.parse_now("2026-10-20T14:01:48Z")++ def test_in_progress_bar_and_live_tick_are_dropped(self):+ self.assertEqual(len(self.spark), 20)+ self.assertIn("BRK.B", self.spark)+ t = self.spark["TSLA"]+ self.assertEqual(len(t["t"]), 8) # 9:30 ... 10:00 (in progress) + the 10:01:47 tick+ self.assertEqual(scan.ts_to_eastern(t["t"][-1]), DT(2026, 10, 20, 10, 1, 47))+ day, cut = scan.orb_window(self.now, None, 15, datetime.time(15, 30))+ self.assertEqual(cut, DT(2026, 10, 20, 10, 1))+ bars = scan.session_bars(t, day, cut)+ self.assertEqual([b["start"].strftime("%H:%M") for b in bars], ["09:30", "09:35", "09:40", "09:45",+ "09:50", "09:55"])+ self.assertEqual(len(scan.session_bars(self.v8, day, cut)), 6)++ def test_tsla_broke_its_range_at_ten(self):+ day, cut = scan.orb_window(self.now, None, 15, datetime.time(15, 30))+ hits, counts, failed = scan.scan_orb(self.spark, ["TSLA", "AMC"], day, cut, 15, 5, 0, lambda s: self.v8)+ # range 9:30 to 9:45: high 370.49 (the 9:30 bar), low 363.64; the 9:55 bar closed 370.585+ self.assertEqual(hits, [{"symbol": "TSLA", "setups": ["orb"], "price": 370.58, "at": "10:00 AM",+ "bar_start": "09:55", "bar_index": 5, "or_high": 370.49, "or_low": 363.64,+ "pct_over": 0.03}])+ self.assertEqual(counts["illiquid"], 1) # AMC under the $5 floor++ def test_stage_two_cap_takes_the_most_traded(self):+ data, _ = scan.load_offline(WALL)+ spark_like = {k: dict(v, h=None, l=None) for k, v in data.items()}+ asked = []++ def confirm(sym):+ asked.append(sym)+ return data[sym]+ day, cut = D(2026, 10, 19), DT(2026, 10, 19, 10, 15)+ hits, counts, _ = scan.scan_orb(spark_like, sorted(data), day, cut, 15, 0, 0, confirm, max_confirm=10)+ self.assertEqual((counts["confirmed"], counts["unconfirmed"]), (10, counts["candidates"] - 10))+ self.assertIn("TSLA", asked) # the most dollars traded by 10:15+ self.assertLessEqual(len(hits), 10)+ hits_all, _, _ = scan.scan_orb(spark_like, sorted(data), day, cut, 15, 0, 0, confirm, max_confirm=0)+ self.assertEqual(len(hits_all), 42)+ for h in hits:+ self.assertIn(h, hits_all)+++class Cli(unittest.TestCase):+ def setUp(self):+ self.d = tempfile.mkdtemp()+ self.t = os.path.join(self.d, "trader")+ self.wl = os.path.join(self.t, "watchlist.json")++ def tearDown(self):+ shutil.rmtree(self.d)++ def read(self, path):+ with open(path, encoding="utf-8") as fh:+ return json.load(fh)++ def test_universe_daily_orb_end_to_end(self):+ uni = os.path.join(self.t, "universe.txt")+ code, text, _ = run(["universe", "--offline", SYMDIR, "--out", uni])+ self.assertEqual(code, 0)+ self.assertIn("Kept 17 US-listed", text)+ with open(uni, encoding="utf-8") as fh:+ lines = fh.read().splitlines()+ self.assertEqual(len(lines), 17)+ self.assertIn("BRK.B|Berkshire Hathaway Inc. New Common Stock", lines)++ # daily over that universe with the fixture charts: only KO and TSLA are in both, so partial+ code, text, _ = run(["daily", "--universe", uni, "--offline", DAILY, "--now", "2026-10-19 09:00",+ "--out", self.wl, "--min-volume", "0"])+ self.assertEqual(code, 0)+ self.assertIn("Fetched 2 of 17 charts (15 failed or had no data)", text)+ doc = self.read(self.wl)+ self.assertEqual((doc["mode"], doc["universe"], doc["scanned"], doc["failed"]), ("daily", 17, 2, 15))+ self.assertEqual(doc["hits"], [{"symbol": "KO", "setups": ["breakout_20d"], "price": 93.9,+ "close_date": "2026-10-16", "rsi": 75.3, "volume": 3680307}])+ self.assertEqual(doc["as_of"], "2026-10-16 close")++ # the reel's 10:15 scan+ code, text, _ = run(["orb", "--offline", WALL, "--now", "2026-10-19 10:15", "--min-price", "0",+ "--out", self.wl])+ self.assertEqual(code, 0)+ self.assertIn("42 of 231 charts closed above their opening-range high by 10:15 AM", text)+ self.assertIn("10:15 AM TSLA $364.18 range 354.47 to 362.18 +0.55% over", text)+ self.assertIn("not a list of stocks to buy", text)+ doc = self.read(self.wl)+ self.assertEqual({k: doc[k] for k in ("created_by", "created_at", "mode", "as_of", "universe", "scanned",+ "source")},+ {"created_by": "trader-scanner", "created_at": "2026-10-19T14:15:00Z", "mode": "orb",+ "as_of": "2026-10-19 10:15 ET", "universe": 234, "scanned": 231, "source": "yahoo"})+ self.assertEqual(len(doc["hits"]), 42)+ self.assertIn({"symbol": "TSLA", "setups": ["orb"], "price": 364.18, "at": "10:15 AM", "bar_start": "10:10",+ "bar_index": 8, "or_high": 362.18, "or_low": 354.47, "pct_over": 0.55}, doc["hits"])++ # the hits read back as a watchlist, with --at instead of --now+ code, text, _ = run(["orb", "--offline", WALL, "--at", "10:15", "--watchlist", self.wl, "--min-price", "0",+ "--json", "--no-write"])+ self.assertEqual(code, 0)+ out = json.loads(text)+ self.assertEqual((out["universe"], out["scanned"], len(out["hits"])), (42, 42, 42))++ def test_partial_stage_two_is_said(self):+ """The networked path with a fake Yahoo that answers from the Oct 19 bundle."""+ bundle = json.loads(scan._read_maybe_gz(WALL))+ calls = []++ def get(path):+ calls.append(path)+ if path.startswith("/v7/finance/spark"):+ res = []+ for y in path.split("symbols=")[1].split("&")[0].split(","):+ r = ((bundle.get(y.replace("-", ".")) or {}).get("chart") or {}).get("result")+ if r:+ closes = r[0]["indicators"]["quote"][0].get("close", [])+ res.append({"symbol": y, "response": [dict(r[0], indicators={"quote": [{"close": closes}]})]})+ return json.dumps({"spark": {"result": res, "error": None}})+ return json.dumps(bundle[path.split("/chart/")[1].split("?")[0].replace("-", ".")])+ old_get, old_sleep, real_now = scan.yahoo_get, scan.SLEEP, scan.parse_now+ scan.yahoo_get, scan.SLEEP = get, (lambda s: None)+ scan.parse_now = lambda text: real_now(text or "2026-10-19 10:20") # the machine clock, pinned+ uni = os.path.join(self.d, "u.txt")+ with open(uni, "w") as fh:+ fh.write("\n".join(sorted(bundle)) + "\n")+ try:+ code, text, _ = run(["orb", "--universe", uni, "--now", "2026-10-19 10:15", "--min-price", "0",+ "--max-confirm", "10", "--no-write"])+ finally:+ scan.yahoo_get, scan.SLEEP, scan.parse_now = old_get, old_sleep, real_now+ self.assertEqual(code, 0)+ self.assertIn("231 usable; 95 candidates, 10 confirmed", text)+ self.assertIn("PARTIAL: 85 more candidates were not checked", text)+ self.assertIn("5 of the 10 checked charts closed above their opening-range high by 10:15 AM", text)+ self.assertEqual(sum(1 for c in calls if c.startswith("/v8/")), 10)+ self.assertEqual(sum(1 for c in calls if c.startswith("/v7/")), 12) # 234 symbols, 20 a request+ self.assertTrue(all("range=1d&interval=5m" in c for c in calls))++ def test_plain_messages_and_exit_codes(self):+ code, _, err = run(["orb", "--offline", WALL, "--now", "2026-10-17 10:15", "--out", self.wl])+ self.assertEqual(code, 1)+ self.assertIn("No session on Sat 2026-10-17 (weekend)", err)+ self.assertNotIn("Traceback", err)+ self.assertFalse(os.path.exists(self.wl))+ code, _, err = run(["orb", "--offline", WALL, "--now", "2026-10-19 09:44", "--out", self.wl])+ self.assertIn("after 9:50 AM", err)+ cfg = os.path.join(self.t, "config.json")+ os.makedirs(self.t)+ with open(cfg, "w") as fh:+ json.dump({"no_entries_after": "10:00"}, fh)+ code, _, err = run(["orb", "--offline", WALL, "--now", "2026-10-19 10:15", "--config", cfg])+ self.assertEqual(code, 1)+ self.assertIn("expired", err)+ code, _, err = run(["orb", "--offline", WALL])+ self.assertIn("--at HH:MM", err)+ code, text, _ = run(["orb", "--offline", WALL, "--now", "2026-10-19 10:10", "--symbols", "TSLA",+ "--out", self.wl])+ self.assertEqual(code, 1) # no breakout yet, but the empty list is written+ self.assertIn("No chart closed above its opening-range high by 10:10 AM", text)+ self.assertEqual(self.read(self.wl)["hits"], [])+ code, _, err = run(["daily", "--universe", os.path.join(self.d, "nope.txt")])+ self.assertEqual(code, 1)+ self.assertIn("scan.py universe", err)+ code, _, err = run(["daily", "--offline", os.path.join(self.d, "nothing-here")])+ self.assertIn("no offline file", err)+ empty = os.path.join(self.d, "empty.json")+ with open(empty, "w") as fh:+ fh.write("{}")+ code, _, err = run(["daily", "--offline", empty])+ self.assertEqual(code, 1)+ self.assertIn("no symbols to scan", err)++ def test_offline_folder_of_v8_files(self):+ folder = os.path.join(self.d, "charts")+ os.makedirs(folder)+ data, _ = scan.load_offline(WALL)+ bundle = json.loads(scan._read_maybe_gz(WALL))+ for sym in ("TSLA", "AAPL", "KO", "SQ"):+ with open(os.path.join(folder, sym + ".json"), "w") as fh:+ json.dump(bundle[sym], fh)+ code, text, _ = run(["orb", "--offline", folder, "--now", "2026-10-19 10:15", "--no-write", "--json"])+ out = json.loads(text)+ self.assertEqual((out["universe"], out["scanned"], out["failed"]), (4, 3, 1))+ self.assertEqual([h["symbol"] for h in out["hits"]], ["AAPL", "TSLA"])+ self.assertEqual(code, 0)++ def test_symbol_lists(self):+ txt = os.path.join(self.d, "list.txt")+ with open(txt, "w") as fh:+ fh.write("# my list\nTSLA|Tesla, Inc. - Common Stock\nko\n\nTSLA\n")+ self.assertEqual(scan.symbols_from_file(txt), ["TSLA", "KO", "TSLA"])+ js = os.path.join(self.d, "wl.json")+ with open(js, "w") as fh:+ json.dump({"hits": [{"symbol": "tsla"}, {"symbol": "KO"}]}, fh)+ self.assertEqual(scan.symbols_from_file(js), ["TSLA", "KO"])+ code, text, _ = run(["daily", "--offline", DAILY, "--watchlist", txt, "--now", "2026-10-19 09:00",+ "--json", "--no-write", "--min-volume", "0"])+ out = json.loads(text)+ self.assertEqual((out["universe"], out["scanned"]), (2, 2))+ code, text, _ = run(["daily", "--offline", DAILY, "--limit", "3", "--now", "2026-10-19 09:00", "--json",+ "--no-write", "--min-volume", "0"])+ self.assertEqual(json.loads(text)["universe"], 3)++ def test_daily_json(self):+ code, text, _ = run(["daily", "--offline", DAILY, "--now", "2026-10-19 09:00", "--json", "--no-write",+ "--min-volume", "0", "--min-price", "0"])+ self.assertEqual(code, 0)+ out = json.loads(text)+ self.assertEqual(len(out["hits"]), 15)+ self.assertEqual(out["note"], "A scan is a list of charts that match a rule, not a list of stocks to buy.")+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_timemachine.py b/tests/test_timemachine.pynew file mode 100644index 0000000..3cf6426--- /dev/null+++ b/tests/test_timemachine.py@@ -0,0 +1,614 @@+import copy+import gzip+import hashlib+import io+import json+import os+import random+import shutil+import tempfile+import unittest+import urllib.error+from contextlib import redirect_stdout, redirect_stderr++from _load import load, FIX++tm = load("trader-timemachine", "timemachine")++DIR = os.path.join(FIX, "trader-timemachine")+TSLA = os.path.join(DIR, "TSLA-60d5m.json.gz") # Yahoo v8 chart, range=60d interval=5m, fetched 2026-10-19 10:49 ET+with gzip.open(TSLA, "rt", encoding="utf-8") as _fh:+ TEXT = _fh.read()+NOW = "2026-10-19 10:50"+NOW_UTC = tm.parse_now(NOW)++# the reel's plan, as trader-exit writes it (CONTRACT.md)+PLAN = {"created_by": "trader-exit", "symbol": "TSLA", "side": "buy", "date": "2026-10-19", "setup": "orb",+ "entry": 364.18, "entry_time": "10:15 AM", "entry_bar": 8, "interval": "5m",+ "opening_range": {"high": 362.18, "low": 354.47, "minutes": 15},+ "stop": 358.32, "stop_rule": "or_mid", "stop_label": "opening-range midpoint",+ "target": 370.04, "target_r": 1.0, "target_label": "1R (one times the risk)",+ "risk_per_share": 5.86, "reward_risk": 1.0, "flat_by": "15:55"}++# fingerprints of the reel's refs/sim-out.json (sim.py mid 1, seed 19): proves bit-for-bit equality+SIM_BANDS = "b9b7c006a733c68b"+SIM_PATHS = "90f313ef40c576a0"+SIM_TRADES = "0058bef72b0dcdee"+SIM_HIST = {"lo": 351.75, "hi": 377.39,+ "bins": [107, 109, 128, 199, 252, 331, 465, 571, 689, 694, 757, 811, 761, 732, 686, 558, 503, 452,+ 327, 244, 160, 125, 102, 78]}+++def sha(x):+ return hashlib.sha256(json.dumps(x).encode("utf-8")).hexdigest()[:16]+++def plan(**kw):+ raw = dict(PLAN)+ raw.update(kw)+ return tm.normalize_plan(raw)+++def machine(p=None, text=TEXT, now=NOW_UTC, **kw):+ return tm.time_machine(text, p or plan(), now, **kw)+++def edited(fn):+ """The fixture's chart JSON, changed by fn(result), back as text."""+ doc = json.loads(TEXT)+ fn(doc["chart"]["result"][0])+ return json.dumps(doc)+++def keep_bars(result, keep):+ """Keep only the bars where keep(ts) is true."""+ q = result["indicators"]["quote"][0]+ idx = [i for i, ts in enumerate(result["timestamp"]) if keep(ts)]+ result["timestamp"] = [result["timestamp"][i] for i in idx]+ for k in q:+ q[k] = [q[k][i] for i in idx]+++def et(ts):+ return tm.to_eastern(tm.utc_of(ts))+++def run(argv):+ out, err = io.StringIO(), io.StringIO()+ with redirect_stdout(out), redirect_stderr(err):+ code = tm.main(argv)+ return code, out.getvalue(), err.getvalue()+++class Reel(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.doc = machine()++ def test_the_reel_odds(self):+ m = self.doc["mc"]+ self.assertEqual((m["replays"], m["seed"], m["window"], m["until"]), (10000, 19, 2, "16:00"))+ self.assertEqual(m["pool_sessions"], 59)+ self.assertEqual(m["bars_left"], 69)+ self.assertEqual((m["pool_from"], m["pool_to"]), ("2026-07-27", "2026-10-16"))+ self.assertEqual(m["p_target"], 0.2938)+ self.assertEqual(m["p_stop"], 0.2548)+ self.assertEqual(m["p_neither"], 0.4514)+ self.assertEqual(m["p_green"], 0.5168)+ self.assertEqual(m["median_close"], 364.36)+ self.assertEqual(m["p5_close"], 355.54)+ self.assertEqual(m["p95_close"], 373.54)+ self.assertEqual(m["avg_R"], 0.034)+ self.assertEqual(m["r_at_target"], 1.0)++ def test_bit_for_bit_with_the_reel_sim(self):+ m = self.doc["mc"]+ self.assertEqual(sha(m["bands"]), SIM_BANDS)+ self.assertEqual(len(m["sample_paths"]), 160)+ self.assertEqual(sha(m["sample_paths"]), SIM_PATHS)+ self.assertEqual(m["hist"], SIM_HIST)+ self.assertEqual(m["bands"][-1], [355.42, 360.91, 364.46, 368.12, 373.65])++ def test_the_history_replay(self):+ h = self.doc["history"]+ self.assertEqual((h["sessions"], h["triggered"]), (59, 33))+ self.assertEqual((h["target"], h["stop"], h["close"], h["green"]), (13, 15, 5, 15))+ self.assertEqual(h["avg_R"], -0.062)+ self.assertEqual(h["rule"], {"setup": "orb", "or_minutes": 15, "stop_rule": "or_mid", "target_r": 1.0})+ slim = [{"date": t["date"], "entry": t["entry"], "outcome": t["outcome"], "R": t["R"]} for t in h["trades"]]+ self.assertEqual(sha(slim), SIM_TRADES)+ first = h["trades"][0]+ self.assertEqual((first["date"], first["entry"], first["stop"], first["target"], first["outcome"]),+ ("2026-07-28", 307.97, 304.89, 311.05, "target"))++ def test_the_verdict_says_coin_flip(self):+ self.assertEqual(self.doc["verdict"], "Close to a coin flip: target first 29.4 % vs stop first 25.5 %.")+ # 1R breaks even at 50 % of the replays that hit one side; the reel's target got 53.6 %+ gap, share, even = tm.lean(self.doc["mc"])+ self.assertEqual((round(share, 3), even), (0.536, 0.5))+ self.assertEqual(self.doc["verdict_notes"],+ ["45.1 % of the replays hit neither by 4:00 PM; the price at 4:00 PM decides those."])++ def test_bands_start_at_the_entry(self):+ m = self.doc["mc"]+ self.assertEqual(m["bands"][0], [364.18] * 5)+ self.assertEqual(len(m["bands"]), 70)+ self.assertEqual((m["band_times"][0], m["band_times"][-1], len(m["band_times"])), ("10:15", "16:00", 70))+ self.assertTrue(all(p[0] == 364.18 and len(p) == 70 for p in m["sample_paths"]))++ def test_the_plan_is_carried_through(self):+ p = self.doc["plan"]+ self.assertEqual((p["symbol"], p["entry"], p["stop"], p["target"], p["entry_bar"], p["entry_time"]),+ ("TSLA", 364.18, 358.32, 370.04, 8, "10:15 AM"))+ self.assertEqual((p["risk_per_share"], p["target_r"], p["flat_by"]), (5.86, 1.0, "15:55"))+ self.assertEqual(self.doc["warnings"], [])++ def test_the_text_report(self):+ text = "\n".join(tm.report(self.doc))+ for line in ("TSLA buy, Monday 2026-10-19: entry 364.18 at 10:15 AM (bar 8), stop 358.32, target 370.04",+ "10,000 replays", "69 five-minute bars", "seed 19", "59 full sessions",+ "target first 29.4 %", "stop first 25.5 %", "neither 45.1 % still open at 4:00 PM",+ "green 51.7 %", "median 364.36, 90 % of replays between 355.54 and 373.54",+ "Average R: +0.034", "fired 33 times: 13 target, 15 stop, 5 neither. Average R -0.062",+ "Close to a coin flip: target first 29.4 % vs stop first 25.5 %.\n45.1 % of the replays "+ "hit neither by 4:00 PM; the price at 4:00 PM decides those.", "not a prediction", "--seed 19"):+ self.assertIn(line, text)+ for word in ("profit", "P&L", "guarantee", "real time", "tick by tick"):+ self.assertNotIn(word, text)+++class Seeds(unittest.TestCase):+ def test_same_seed_same_numbers(self):+ a = machine(replays=2000, seed=5)["mc"]+ b = machine(replays=2000, seed=5)["mc"]+ self.assertEqual(a, b)++ def test_another_seed_gives_other_numbers(self):+ m = machine(seed=7)["mc"]+ self.assertNotEqual((m["p_target"], m["p_stop"], m["median_close"]), (0.2938, 0.2548, 364.36))+ self.assertAlmostEqual(m["p_target"] + m["p_stop"] + m["p_neither"], 1.0, places=6)+ self.assertNotEqual(sha(m["bands"]), SIM_BANDS)++ def test_the_draws_are_stable_across_pythons(self):+ # random.Random(seed), randint and choice are stable since Python 3.2; the reel numbers above+ # are the real proof, this pins the first draws so a failure points at the RNG+ r = random.Random(19)+ self.assertEqual([r.randint(-2, 2) for _ in range(8)], [-2, 2, -2, 2, -1, 1, 0, 2])+ self.assertEqual(r.choice(range(59)), 18)++ def test_window_and_replays(self):+ a = machine(replays=500, window=0)["mc"]+ self.assertEqual((a["replays"], a["window"]), (500, 0))+ self.assertNotEqual(a["bands"], machine(replays=500)["mc"]["bands"])+ with self.assertRaises(tm.TMError):+ machine(replays=0)+ with self.assertRaises(tm.TMError):+ machine(window=11)+++class Bars(unittest.TestCase):+ def setUp(self):+ self.result = tm.chart_result(TEXT, "TSLA")++ def test_the_in_progress_tick_is_dropped(self):+ meta, bars, dropped = tm.parse_bars(self.result, NOW_UTC)+ self.assertEqual(dropped, {"no_price": 0, "off_grid": 1, "not_complete": 1, "outside_hours": 0})+ last = bars[-1]+ self.assertEqual((last["date"], last["start"], last["slot"]), ("2026-10-19", "10:40", 14))+ # with the real clock (any time later) the data's own time still marks 10:45 as in progress+ self.assertEqual(tm.parse_bars(self.result, tm.parse_now(None))[1][-1]["start"], "10:40")+ entry = [b for b in bars if b["date"] == "2026-10-19" and b["slot"] == 8][0]+ self.assertEqual((entry["start"], entry["c"]), ("10:10", 364.1759948730469))++ def test_now_pins_the_clock(self):+ bars = tm.parse_bars(self.result, tm.parse_now("2026-10-19 10:12"))[1]+ today = [b for b in bars if b["date"] == "2026-10-19"]+ self.assertEqual(len(today), 8)+ with self.assertRaises(tm.TMError) as cm:+ machine(now=tm.parse_now("2026-10-19 10:12"))+ self.assertIn("not in the data", str(cm.exception))+ self.assertIn("10:05 bar", str(cm.exception))+ self.assertEqual(machine(now=tm.parse_now("2026-10-19 10:15"), replays=200)["mc"]["pool_sessions"], 59)++ def test_daylight_saving(self):+ stamps = [1793367000, # 2026-10-30 13:30Z = 9:30 EDT+ 1793629800, # 2026-11-02 14:30Z = 9:30 EST+ 1793626200, # 2026-11-02 13:30Z = 8:30 EST, before the open+ 1793649600] # 2026-11-02 20:00Z = 15:00 EST+ res = {"meta": {"symbol": "X"}, "timestamp": stamps,+ "indicators": {"quote": [{"open": [1] * 4, "high": [1] * 4, "low": [1] * 4, "close": [1] * 4,+ "volume": [0] * 4}]}}+ meta, bars, dropped = tm.parse_bars(res, tm.parse_now("2026-11-03T00:00Z"))+ self.assertEqual([(b["date"], b["start"], b["slot"]) for b in bars],+ [("2026-10-30", "09:30", 0), ("2026-11-02", "09:30", 0), ("2026-11-02", "15:00", 66)])+ self.assertEqual(dropped["outside_hours"], 1)+ self.assertEqual(tm.eastern_offset(tm.utc_of(1793367000)), -4)+ self.assertEqual(tm.eastern_offset(tm.utc_of(1793629800)), -5)++ def test_a_half_day_is_left_out(self):+ def cut(res): # 2026-09-04 ends at 1:00 PM, like a real early close: 42 bars+ keep_bars(res, lambda ts: not (et(ts).date().isoformat() == "2026-09-04" and et(ts).hour >= 13))+ doc = machine(text=edited(cut), replays=300)+ self.assertEqual(doc["mc"]["pool_sessions"], 58)+ self.assertEqual(doc["data"]["short_sessions_left_out"], [{"date": "2026-09-04", "bars": 42}])+ self.assertEqual(doc["history"]["sessions"], 58)+ self.assertNotIn("2026-09-04", [t["date"] for t in doc["history"]["trades"]])+ self.assertIn("Left out 1 short session", "\n".join(tm.report(doc)))++ def test_today_is_not_in_the_pool(self):+ doc = machine(replays=200)+ self.assertEqual(doc["mc"]["pool_to"], "2026-10-16")+ self.assertNotIn("2026-10-19", [t["date"] for t in doc["history"]["trades"]])++ def test_a_missing_price_is_dropped(self):+ def hole(res):+ res["indicators"]["quote"][0]["close"][5] = None+ doc = machine(text=edited(hole), replays=200)+ self.assertEqual(doc["data"]["dropped"]["no_price"], 1)+ self.assertEqual(doc["mc"]["pool_sessions"], 58) # 2026-07-27 now has a gap++ def test_empty_and_broken_data(self):+ empty = json.dumps({"chart": {"result": [{"meta": {"symbol": "TSLA"}, "timestamp": [],+ "indicators": {"quote": [{}]}}], "error": None}})+ with self.assertRaises(tm.TMError) as cm:+ machine(text=empty)+ self.assertIn("no complete 5-minute bars", str(cm.exception))+ gone = json.dumps({"chart": {"result": None, "error": {"code": "Not Found",+ "description": "No data found, symbol may be delisted"}}})+ with self.assertRaises(tm.TMError) as cm:+ machine(text=gone)+ self.assertIn("No data found", str(cm.exception))+ with self.assertRaises(tm.TMError):+ machine(text="<html>rate limited</html>")++ def test_fewer_than_20_sessions_is_refused(self):+ def trim(res):+ keep_bars(res, lambda ts: et(ts).date().isoformat() >= "2026-09-22")+ with self.assertRaises(tm.TMError) as cm:+ machine(text=edited(trim))+ self.assertIn("only 19 full session(s)", str(cm.exception))+ self.assertIn("at least 20", str(cm.exception))++ def twenty(res):+ keep_bars(res, lambda ts: et(ts).date().isoformat() >= "2026-09-21")+ self.assertEqual(machine(text=edited(twenty), replays=200)["mc"]["pool_sessions"], 20)++ def test_an_early_close_day_ends_the_replay_at_1_pm(self):+ # the fixture's bars moved onto the 30 trading days up to Friday 2026-11-27 (an NYSE 1:00 PM+ # close), across the Nov 1 clock change, with real New York times for every bar+ sessions = tm.full_sessions(tm.split_sessions(tm.parse_bars(tm.chart_result(TEXT, "TSLA"), NOW_UTC)[1]),+ "2026-10-19")[0][-30:]+ days, d = [], tm.datetime.date(2026, 11, 27)+ while len(days) < 30:+ if d.weekday() < 5 and d.isoformat() != "2026-11-26":+ days.append(d)+ d -= tm.datetime.timedelta(days=1)+ stamps, cols = [], {"open": [], "high": [], "low": [], "close": [], "volume": []}+ for day, (_, bars) in zip(sorted(days), sessions):+ for b in bars[:42] if day.isoformat() == "2026-11-27" else bars:+ local = tm.datetime.datetime.combine(day, tm.datetime.time(9, 30)) + tm.datetime.timedelta(+ minutes=5 * b["slot"])+ stamps.append(int((tm.eastern_to_utc(local) - tm.EPOCH).total_seconds()))+ for k, f in (("open", "o"), ("high", "h"), ("low", "l"), ("close", "c"), ("volume", "v")):+ cols[k].append(b[f])+ text = json.dumps({"chart": {"result": [{"meta": {"symbol": "TSLA"}, "timestamp": stamps,+ "indicators": {"quote": [cols]}}]}})+ last = sessions[-1][1]+ p = plan(date="2026-11-27", entry=round(last[8]["c"], 2), stop=round(last[8]["c"], 2) - 5,+ target=round(last[8]["c"], 2) + 5, stop_rule="pct")+ later = tm.parse_now("2026-11-28 12:00")+ doc = machine(p, text=text, now=later, replays=300)+ self.assertEqual((doc["mc"]["until"], doc["mc"]["bars_left"], doc["mc"]["pool_sessions"]), ("13:00", 33, 29))+ self.assertIn("to 1:00 PM", "\n".join(tm.report(doc)))+ with self.assertRaises(tm.TMError) as cm:+ machine(p, text=text, now=later, until="15:55", replays=10)+ self.assertIn("early close", str(cm.exception))++ def test_the_data_must_be_the_plans_ticker(self):+ with self.assertRaises(tm.TMError) as cm:+ machine(plan(symbol="AAPL"))+ self.assertIn("data is for TSLA", str(cm.exception))+++class Plans(unittest.TestCase):+ def test_an_entry_not_in_the_data_is_refused(self):+ with self.assertRaises(tm.TMError) as cm:+ machine(plan(date="2026-10-20"))+ self.assertIn("not in the data", str(cm.exception))+ self.assertIn("no bars for that day", str(cm.exception))+ with self.assertRaises(tm.TMError) as cm: # 10:50 has not happened in this data yet+ machine(plan(entry_time="10:55 AM", entry_bar=None))+ self.assertIn("not in the data", str(cm.exception))++ def test_plan_checks(self):+ cases = [+ (dict(entry_time="10:17 AM", entry_bar=None), "5-minute grid"),+ (dict(entry_time="4:00 PM", entry_bar=None), "between 9:35 AM and 3:55 PM"),+ (dict(entry_bar=9), "disagrees with itself"),+ (dict(entry_time=None, entry_bar=None), "entry_time"),+ (dict(interval="1m"), "7 days of 1-min bars"),+ (dict(stop=365.0), "stop < entry < target"),+ (dict(side="short"), "buy or sell"),+ (dict(symbol=""), "ticker"),+ (dict(entry="abc"), "number for entry"),+ (dict(date="Oct 19"), "date like"),+ (dict(opening_range={"minutes": 7}), "multiple of 5"),+ ]+ for change, words in cases:+ with self.assertRaises(tm.TMError, msg=change) as cm:+ plan(**change)+ self.assertIn(words, str(cm.exception), change)++ def test_entry_bar_or_entry_time_alone(self):+ self.assertEqual(plan(entry_time=None)["entry_time"], "10:15 AM")+ self.assertEqual(plan(entry_bar=None)["entry_bar"], 8)+ self.assertEqual(plan(entry_time="10:15", entry_bar=None)["entry_bar"], 8)+ self.assertEqual(plan(entry_time="10:15am", entry_bar=None)["entry_bar"], 8)++ def test_until_cuts_the_replay(self):+ doc = machine(until="15:55", replays=500)+ m = doc["mc"]+ self.assertEqual((m["until"], m["bars_left"], m["band_times"][-1]), ("15:55", 68, "15:55"))+ self.assertIn("still open at 3:55 PM", "\n".join(tm.report(doc)))+ self.assertEqual(machine(until="3:55 PM", replays=500)["mc"], m)+ for bad, words in (("10:15 AM", "nothing to replay"), ("16:05", "no later than 4:00 PM"),+ ("15:57", "5-minute grid"), ("noon", "New York time")):+ with self.assertRaises(tm.TMError) as cm:+ machine(until=bad, replays=10)+ self.assertIn(words, str(cm.exception), bad)++ def test_an_entry_outside_its_bar_is_flagged(self):+ doc = machine(plan(entry=368.0, stop=362.0, target=374.0), replays=200)+ self.assertIn("outside that bar's range", doc["warnings"][0])++ def test_stop_rounds_away_from_the_entry(self):+ self.assertEqual(tm.cents_away(358.325, True), 358.32)+ self.assertEqual(tm.cents_away(358.325, False), 358.33)+ self.assertEqual(tm.cents_away(354.4700012207031, True), 354.47)+ self.assertEqual(tm.cents_away(354.46999999999997, True), 354.47)++ def test_the_stop_rule_is_worked_out_when_not_given(self):+ rule = machine(plan(stop_rule=None), replays=100)["history"]["rule"]+ self.assertEqual(rule["stop_rule"], "or_mid")+ rule = machine(plan(stop_rule=None, stop=354.47, target=373.89), replays=100)["history"]["rule"]+ self.assertEqual((rule["stop_rule"], rule["target_r"]), ("or_low", 1.0))+ rule = machine(plan(stop_rule="atr", stop=360.0, target=372.54), replays=100)["history"]["rule"]+ self.assertEqual((rule["stop_rule"], rule["stop_pct"], rule["target_r"]), ("pct", 1.1478, 2.0))++ def test_a_setup_other_than_orb_skips_the_history(self):+ doc = machine(plan(setup="flag"), replays=200)+ self.assertIsNone(doc["history"]["rule"])+ self.assertIn("orb", doc["history"]["note"])+ self.assertEqual(doc["mc"]["pool_sessions"], 59)+ self.assertIn("History: skipped", "\n".join(tm.report(doc)))++ def test_a_sell_plan_mirrors_the_rules(self):+ doc = machine(plan(side="sell", stop=370.04, target=358.32, stop_rule="or_high"), replays=2000)+ m = doc["mc"]+ self.assertAlmostEqual(m["p_target"] + m["p_stop"] + m["p_neither"], 1.0, places=6)+ self.assertEqual(m["r_at_target"], 1.0)+ self.assertEqual(doc["history"]["rule"]["stop_rule"], "or_high")+ for t in doc["history"]["trades"]:+ self.assertTrue(t["target"] < t["entry"] < t["stop"], t)+ self.assertIn("below the entry", "\n".join(tm.report(doc)))++ def test_the_verdict_thresholds_at_1r(self):+ # 1R: the target's share of the replays that hit one side against 50 %+ self.assertTrue(tm.verdict({"p_target": 0.30, "p_stop": 0.26}).startswith("Close to a coin flip"))+ self.assertTrue(tm.verdict({"p_target": 0.40, "p_stop": 0.30}).startswith("Leans toward the target"))+ self.assertTrue(tm.verdict({"p_target": 0.20, "p_stop": 0.30}).startswith("Leans toward the stop"))+ self.assertTrue(tm.verdict({"p_target": 0.60, "p_stop": 0.30}).startswith("Strongly toward the target"))+ self.assertEqual(tm.verdict({"p_target": 0.10, "p_stop": 0.60, "r_at_target": 1.0}),+ "Strongly toward the stop: target first 10.0 % vs stop first 60.0 %.")+ self.assertEqual(tm.verdict({"p_target": 0.0, "p_stop": 0.0, "until": "15:55"}),+ "No replay reached the target or the stop by 3:55 PM: the price at 3:55 PM decides every one.")++ def test_a_2r_target_is_judged_against_its_break_even(self):+ # the live TSLA run of 2026-10-20 (entry 370.58, stop 367.06, 2R target 377.62): it needs 33 %, got 32 %+ mc = {"p_target": 0.241, "p_stop": 0.505, "p_neither": 0.254, "r_at_target": 2.0, "avg_R": 0.095}+ self.assertEqual(tm.verdict(mc), "Close to break-even: at 2R the target has to come first in 33 % of the "+ "replays that hit one side; it did in 32 % (target first 24.1 % vs stop "+ "first 50.5 %).")+ self.assertEqual(tm.verdict_notes(mc), [])+ lean = dict(mc, p_target=0.15, p_stop=0.55)+ self.assertTrue(tm.verdict(lean).startswith("Leans toward the stop: at 2R the target has to come first in "+ "33 % of the replays that hit one side; it did in 21 %"))+ self.assertEqual(tm.verdict_notes(lean), ["Average R is +0.095 all the same: the replays that hit neither "+ "pull it the other way."])+ self.assertTrue(tm.verdict(dict(mc, p_target=0.30, p_stop=0.40)).startswith("Leans toward the target"))+ self.assertTrue(tm.verdict(dict(mc, p_target=0.40, p_stop=0.40)).startswith("Strongly toward the target"))+ self.assertIn("at 1.5R the target has to come first in 40 %", tm.verdict(dict(mc, r_at_target=1.5)))++ def test_2r_on_the_fixture_near_break_even(self):+ # stop 362.00, 2R target 368.54: 33.5 % vs 62.4 % looks lopsided, but 2R only needs a third+ doc = machine(plan(stop=362.0, target=368.54, stop_rule="pct"))+ m = doc["mc"]+ self.assertEqual((m["r_at_target"], m["p_target"], m["p_stop"], m["avg_R"]), (2.0, 0.3345, 0.6238, 0.068))+ self.assertEqual(doc["verdict"], "Close to break-even: at 2R the target has to come first in 33 % of the "+ "replays that hit one side; it did in 35 % (target first 33.5 % vs stop "+ "first 62.4 %).")+ self.assertEqual(doc["verdict_notes"], [])++ def test_2r_on_the_fixture_a_clear_lean(self):+ # the reel's entry and stop with a 2R target 375.90: the target first only 4.0 % vs stop first 25.6 %+ doc = machine(plan(target=375.90))+ m = doc["mc"]+ self.assertEqual((m["r_at_target"], m["p_target"], m["p_stop"], m["p_neither"], m["avg_R"]),+ (2.0, 0.0397, 0.2558, 0.7045, 0.042))+ self.assertEqual(doc["verdict"], "Strongly toward the stop: at 2R the target has to come first in 33 % of "+ "the replays that hit one side; it did in 13 % (target first 4.0 % vs stop "+ "first 25.6 %).")+ self.assertEqual(doc["verdict_notes"], [+ "70.5 % of the replays hit neither by 4:00 PM; the price at 4:00 PM decides those.",+ "Average R is +0.042 all the same: the replays that hit neither pull it the other way."])+ text = "\n".join(tm.report(doc))+ self.assertIn(doc["verdict"] + "\n" + doc["verdict_notes"][0] + "\n" + doc["verdict_notes"][1], text)+++class Network(unittest.TestCase):+ def setUp(self):+ self.calls, self.sleeps = [], []+ self._get, self._sleep = tm._get, tm._sleep+ tm._sleep = self.sleeps.append++ def tearDown(self):+ tm._get, tm._sleep = self._get, self._sleep++ def answer(self, codes):+ codes = list(codes)++ def fake(url, timeout=20):+ self.calls.append(url.split(".finance")[0].split("//")[1])+ code = codes.pop(0)+ if code != 200:+ raise urllib.error.HTTPError(url, code, "x", {}, io.BytesIO(b""))+ return TEXT+ tm._get = fake++ def test_url_and_user_agent(self):+ self.assertEqual(tm.chart_url("tsla"),+ "https://query2.finance.yahoo.com/v8/finance/chart/TSLA?range=60d&interval=5m")+ self.assertIn("/chart/BRK-B?", tm.chart_url("brk.b", "query1"))+ self.assertEqual(tm.UA, "Mozilla/5.0 (compatible; day-trader-skill/2.0; "+ "+https://github.com/Jakeschincariol/day-trader-skill)")++ def test_429_waits_retries_then_falls_back_to_query1(self):+ self.answer([429, 429, 200])+ self.assertEqual(tm.fetch_chart("TSLA"), TEXT)+ self.assertEqual(self.calls, ["query2", "query2", "query1"])+ self.assertEqual(self.sleeps, [tm.BACKOFF, tm.PAUSE])++ def test_one_429_then_ok(self):+ self.answer([429, 200])+ self.assertEqual(tm.fetch_chart("TSLA"), TEXT)+ self.assertEqual(self.calls, ["query2", "query2"])++ def test_5xx_falls_back(self):+ self.answer([503, 200])+ self.assertEqual(tm.fetch_chart("TSLA"), TEXT)+ self.assertEqual(self.calls, ["query2", "query1"])++ def test_rate_limited_everywhere_is_one_plain_line(self):+ self.answer([429, 429, 429, 429])+ with self.assertRaises(tm.TMError) as cm:+ tm.fetch_chart("TSLA")+ self.assertIn("rate limiting", str(cm.exception))++ def test_404(self):+ self.answer([404])+ with self.assertRaises(tm.TMError) as cm:+ tm.fetch_chart("ZZZZ")+ self.assertIn("check the ticker", str(cm.exception))++ def test_run_over_the_network_path(self):+ self.answer([200])+ d = tempfile.mkdtemp()+ try:+ p = os.path.join(d, "plan.json")+ with open(p, "w") as fh:+ json.dump(PLAN, fh)+ code, text, _ = run(["run", "--plan", p, "--now", NOW, "--replays", "300"])+ self.assertEqual(code, 0)+ self.assertEqual(self.calls, ["query2"])+ finally:+ shutil.rmtree(d)+++class Cli(unittest.TestCase):+ def setUp(self):+ self.d = tempfile.mkdtemp()+ self.plan = os.path.join(self.d, "trader", "plan.json")+ os.makedirs(os.path.dirname(self.plan))+ with open(self.plan, "w") as fh:+ json.dump(PLAN, fh, indent=2)+ self.out = os.path.join(self.d, "trader", "timemachine.json")++ def tearDown(self):+ shutil.rmtree(self.d)++ def test_run_with_the_plan_end_to_end(self):+ code, text, err = run(["run", "--plan", self.plan, "--offline", TSLA, "--now", NOW, "--write", self.out])+ self.assertEqual(code, 0, err)+ self.assertIn("target first 29.4 %", text)+ self.assertIn("Close to a coin flip: target first 29.4 % vs stop first 25.5 %.", text)+ self.assertIn("Wrote %s." % self.out, text)+ self.assertIn("/trader-budget", text)+ with open(self.out) as fh:+ doc = json.load(fh)+ self.assertEqual(sorted(k for k in ("plan", "mc", "history") if k in doc), ["history", "mc", "plan"])+ self.assertEqual(doc["created_by"], "trader-timemachine")+ self.assertEqual(doc["source"], "offline")+ self.assertEqual((doc["mc"]["p_target"], doc["mc"]["avg_R"]), (0.2938, 0.034))+ self.assertEqual(sha(doc["mc"]["sample_paths"]), SIM_PATHS)+ self.assertEqual((doc["history"]["triggered"], doc["history"]["avg_R"]), (33, -0.062))+ self.assertEqual(doc["plan"]["from"], self.plan)++ def test_json_output(self):+ code, text, _ = run(["run", "--plan", self.plan, "--offline", TSLA, "--now", NOW, "--json"])+ self.assertEqual(code, 0)+ doc = json.loads(text)+ self.assertEqual(doc["mc"]["p_stop"], 0.2548)+ self.assertNotIn("sample_paths", doc["mc"])+ self.assertEqual(doc["verdict"][:20], "Close to a coin flip")+ self.assertFalse(os.path.exists(self.out))++ def test_the_plan_as_flags_matches_the_file(self):+ code, text, err = run(["run", "--symbol", "tsla", "--date", "2026-10-19", "--entry", "364.18",+ "--stop", "358.32", "--target", "370.04", "--entry-time", "10:15 AM",+ "--offline", TSLA, "--now", NOW, "--json"])+ self.assertEqual(code, 0, err)+ doc = json.loads(text)+ self.assertEqual((doc["mc"]["p_target"], doc["mc"]["p_green"]), (0.2938, 0.5168))+ self.assertEqual(doc["plan"]["stop_rule"], "or_mid")+ self.assertEqual((doc["history"]["target"], doc["history"]["stop"], doc["history"]["avg_R"]), (13, 15, -0.062))+ code, _, err = run(["run", "--symbol", "TSLA", "--entry", "364.18", "--offline", TSLA])+ self.assertEqual(code, 1)+ self.assertIn("--stop", err)++ def test_offline_folder_and_default_paths(self):+ shutil.copy(TSLA, self.d)+ cwd = os.getcwd()+ os.chdir(self.d)+ try:+ code, text, err = run(["run", "--offline", ".", "--now", NOW, "--replays", "500", "--write"])+ self.assertEqual(code, 0, err)+ self.assertTrue(os.path.exists(os.path.join("trader", "timemachine.json")))+ code, text, err = run(["chart", "--from"])+ self.assertEqual(code, 0, err)+ self.assertIn("* median", text)+ with open(os.path.join("trader", "timemachine.json")) as fh:+ self.assertEqual(json.load(fh)["mc"]["replays"], 500)+ finally:+ os.chdir(cwd)++ def test_errors_are_one_plain_line(self):+ for argv in (["run", "--plan", os.path.join(self.d, "nope.json")],+ ["run", "--plan", self.plan, "--offline", os.path.join(self.d, "missing.json.gz")],+ ["run", "--plan", self.plan, "--offline", TSLA, "--until", "9:00"],+ ["chart", "--from", os.path.join(self.d, "nope.json")]):+ code, text, err = run(argv)+ self.assertEqual(code, 1, argv)+ self.assertEqual(len(err.strip().splitlines()), 1, err)+ self.assertTrue(err.startswith("timemachine.py: "), err)+ self.assertNotIn("Traceback", err)+ self.assertEqual(run([])[0], 1)++ def test_chart(self):+ run(["run", "--plan", self.plan, "--offline", TSLA, "--now", NOW, "--write", self.out])+ code, text, _ = run(["chart", "--from", self.out])+ self.assertEqual(code, 0)+ lines = text.splitlines()+ self.assertIn("2,000 replay paths from the 10:15 AM entry (seed 19)", lines[0])+ self.assertTrue(any(l.startswith(" 370.04 |") and l.endswith(" target") for l in lines))+ self.assertTrue(any(l.startswith(" 358.32 |") and l.endswith(" stop") for l in lines))+ self.assertTrue(any(l.startswith(" 364.18 |*") and l.endswith(" entry") for l in lines))+ self.assertIn("10:15", text)+ self.assertIn("4:00", text)+ self.assertEqual(lines[-2:], ["Close to a coin flip: target first 29.4 % vs stop first 25.5 %.",+ "45.1 % of the replays hit neither by 4:00 PM; the price at 4:00 PM decides those."])+ code, again, _ = run(["chart", "--plan", self.plan, "--offline", TSLA, "--now", NOW])+ self.assertEqual(again, text)+++if __name__ == "__main__":+ unittest.main()diff --git a/trader-alerts/SKILL.md b/trader-alerts/SKILL.mdnew file mode 100644index 0000000..0517437--- /dev/null+++ b/trader-alerts/SKILL.md@@ -0,0 +1,160 @@+---+name: trader-alerts+description: >-+ Price Alerts. Rings when a price, a stop or the opening bell hits. Turns+ the trade plan into three alerts in one go (the stop, the target and "flat+ by close" at your flat-by time), plus above / below / stop / target levels,+ percent moves from the previous close, any time of day, and the NYSE+ opening bell, each ringing once so you are not spammed. Knows NYSE hours+ with the 2026 and 2027 holidays and 1:00 p.m. early closes, works out New+ York time itself, fetches free delayed quotes (Yahoo chart JSON, Stooq+ CSV) one ticker at a time, and writes trader/prices.json for sizing and the+ risk check. Use when the user says "alert me when", "tell me if TSLA hits",+ "watch my stop", "watch my trade", "remind me to close by 3:55", "is the+ market open", "when does the market open", "get me a price", or right+ after /trader-exit writes a plan.+argument-hint: "[ticker] [price]"+---++# trader-alerts++Price Alerts watches the numbers so the user does not have to stare at a+chart. An alert is information, never an order: when a stop alert rings,+nothing is sold by this skill. With a bracket order the stop-loss and the+take-profit already sit at the broker and do the work; the alerts tell the+user what happened and when it is time to be flat.++`${CLAUDE_SKILL_DIR}` below is this skill's folder (where this SKILL.md lives).++```bash+python3 "${CLAUDE_SKILL_DIR}/alerts.py" clock # NYSE open or closed, next open+python3 "${CLAUDE_SKILL_DIR}/alerts.py" add --from-plan # stop, target, flat by close from trader/plan.json+python3 "${CLAUDE_SKILL_DIR}/alerts.py" add --opening-bell+python3 "${CLAUDE_SKILL_DIR}/alerts.py" add --symbol TSLA --stop 358.32+python3 "${CLAUDE_SKILL_DIR}/alerts.py" add --symbol TSLA --target 370.04+python3 "${CLAUDE_SKILL_DIR}/alerts.py" add --at 15:55 --label "flat by close" --before-close+python3 "${CLAUDE_SKILL_DIR}/alerts.py" add --symbol KO --pct 3+python3 "${CLAUDE_SKILL_DIR}/alerts.py" check # exit 0 = something rang+python3 "${CLAUDE_SKILL_DIR}/alerts.py" quote TSLA --write # -> trader/prices.json+python3 "${CLAUDE_SKILL_DIR}/alerts.py" quote --holdings --write # portfolio + plan tickers+python3 "${CLAUDE_SKILL_DIR}/alerts.py" list+python3 "${CLAUDE_SKILL_DIR}/alerts.py" reset tsla-plan-stop+```++`--now "2026-10-19 15:55"` pins the clock (New York time); `--offline DIR`+reads saved quote files instead of the network.++## What it reads and writes++| file | what |+| --- | --- |+| `trader/plan.json` | the trade from trader-exit, for `add --from-plan` |+| `trader/alerts.json` | the rules (`alerts.example.json` in this folder) |+| `trader/state/alerts.json` | which rules rang and when, so each rings once |+| `trader/prices.json` | the latest quotes, merged in, for trader-budget and trader-risk |+| `trader/portfolio.json` | the tickers held, for `quote --holdings` |++## Rule types++| type | rings when | rings again |+| --- | --- | --- |+| `above` / `target` | price at or above `price` | after `reset`, or on its own if `"rearm": true` and the price fell back |+| `below` / `stop` | price at or below `price` | same |+| `pct_move` | moved `pct` percent from the previous close (or `ref`), optional `direction` up or down | once per day at most |+| `time` | the New York clock passed `at` ("15:55") on a trading day | once per trading day |+| `opening_bell` | the NYSE is open | once per trading day |++A rule with `"date"` is watched on that New York date only; `--from-plan`+rules carry the plan's date, so yesterday's stop never rings today. A `time`+rule with `"before_close": true` moves 3 hours earlier on a 1:00 p.m. early+close, so "flat by close" at 15:55 rings at 12:55 on those days.++## Quotes++- `yahoo` (default): `query2.finance.yahoo.com/v8/finance/chart/<TICKER>`, an+ unofficial free JSON endpoint, one request per ticker, half a second apart.+ On a 429 it waits and tries once more; on a 429 or a 5xx after that it+ tries `query1`. It identifies itself as `day-trader-skill/2.0`.+- `stooq`: `stooq.com/q/l/?s=tsla.us&f=sd2t2ohlcv&h&e=csv`, Stooq's free CSV.+ It answered 404 on 2026-10-13; the parser stays for when it is back.+- Free quotes are unofficial, delayed and can lag. They are fine for alerts+ and for checking a size, not for timing an order. The broker's price is the+ one that fills. Each price in `trader/prices.json` keeps its quote time, and+ trader-risk only uses one under 15 minutes old.+- If both are down, read the price from the broker connector (Alpaca+ `get_stock_snapshot`, IBKR `get_price_snapshot`) and write it into+ `trader/prices.json` as `{"as_of": "...Z", "prices": {"TSLA": 366.48}}`.++## The NYSE clock++Regular session 9:30 a.m. to 4:00 p.m. New York time, closed on weekends and+on these holidays, from nyse.com/markets/hours-calendars (read 2026-10-13):++- 2026: Jan 1, Jan 19, Feb 16, Apr 3 (Good Friday), May 25, Jun 19, Jul 3+ (Independence Day observed), Sep 7, Nov 26, Dec 25. Early close 1:00 p.m. on+ Nov 27 and Dec 24.+- 2027: Jan 1, Jan 18, Feb 15, Mar 26 (Good Friday), May 31, Jun 18+ (Juneteenth observed), Jul 5 (Independence Day observed), Sep 6, Nov 25,+ Dec 24 (Christmas observed). Early close 1:00 p.m. on Nov 26.++Daylight saving time is worked out in the tool, so it needs no time zone+files and ignores the computer's own zone. For any other year it says the+holiday list is unknown.++## Steps++1. Right after trader-exit writes the plan, run `add --from-plan`. Confirm+ the three alerts back to the user: the stop, the target and the flat-by time.+2. Run `check` while the trade is open: every few minutes from a Claude+ scheduled task or `/loop`. Each run fetches only the tickers in today's+ rules and rings each alert once. A check reads the latest delayed quote;+ it is not a live feed, and a price can pass a level between two checks.+3. Tell the user what rang in one line each. A stop or target alert means the+ bracket order has probably filled: check `get_open_position` and record the+ fill with trader-broker. "Flat by close" means close anything still open:+ trader-broker `flatten`, then trader-risk, then the user's yes. Never act+ for them.++## Example: the reel++TSLA on Monday 2026-10-19: entry 364.18 at 10:15 AM, stop 358.32, target+370.04, flat by 15:55. `add --from-plan` writes `tsla-plan-stop`,+`tsla-plan-target` and `tsla-flat-by` for that day. A `check` at 10:53 reads+the real 10:52 quote, 366.48, between the stop and the target:++```+NYSE OPEN (2026-10-19 10:53 New York, regular session).+Nothing hit. 3 rule(s) watched today, TSLA $366.48.+```++At 3:55 PM:++```+ALERT Flat by close: it is 15:55 New York (set for 15:55), the market closes at 16:00. If TSLA is still+open, close it: trader-broker flatten --symbol TSLA builds the sell ticket, then trader-risk and your yes.+```++It rings once. The next morning the plan's three alerts are no longer+watched; with `add --opening-bell`, the bell rings at 9:30.++## Rules++- An alert is a fact about a price or the clock. Say it as a fact.+- Never present a quote as live. Free quotes are delayed and unofficial.+- Confirm every new rule back to the user: ticker, type, level, day.++## What it never does++It never places, cancels or changes an order, never claims a quote is+live, and never predicts where a price is going.++## Safety++- Education and tooling, not financial advice. A PASS is a rules check, not a recommendation.+- Paper trading by default (`"paper": true`). Going live is the user's own decision, in their own config.+- Nothing in this pack places an order except trader-broker, and only when all three hold: trader-risk+ passed that exact order today, the user typed an explicit yes for that one order in the chat, and the+ user clicked Allow once on Claude's own card because the order tool is set to "Needs approval"+ (Customize > Connectors > tool permissions). Never set an order tool to "Always allow".+- No options, margin, short selling or leverage unless the config allows it and the user confirms.+- Broker keys live in environment variables or the Claude Desktop config, never in the chat.diff --git a/trader-alerts/alerts.example.json b/trader-alerts/alerts.example.jsonnew file mode 100644index 0000000..74dab38--- /dev/null+++ b/trader-alerts/alerts.example.json@@ -0,0 +1,9 @@+{+ "rules": [+ {"id": "opening-bell", "type": "opening_bell"},+ {"id": "tsla-plan-stop", "symbol": "TSLA", "type": "stop", "price": 358.32, "note": "plan stop: opening-range midpoint", "date": "2026-10-19"},+ {"id": "tsla-plan-target", "symbol": "TSLA", "type": "target", "price": 370.04, "note": "plan target: 1R (one times the risk)", "date": "2026-10-19"},+ {"id": "tsla-flat-by", "symbol": "TSLA", "type": "time", "at": "15:55", "label": "flat by close", "before_close": true, "date": "2026-10-19"},+ {"id": "tsla-move-3", "symbol": "TSLA", "type": "pct_move", "pct": 3}+ ]+}diff --git a/trader-alerts/alerts.py b/trader-alerts/alerts.pynew file mode 100644index 0000000..5c503a7--- /dev/null+++ b/trader-alerts/alerts.py@@ -0,0 +1,787 @@+#!/usr/bin/env python3+"""Price alerts and the NYSE clock for trader-alerts. Standard library only.++ python3 alerts.py clock # is the NYSE open? next open / close+ python3 alerts.py quote TSLA --write # quotes -> trader/prices.json+ python3 alerts.py quote --holdings --write # every ticker in your portfolio and plan+ python3 alerts.py add --from-plan # stop, target and flat-by-close from trader/plan.json+ python3 alerts.py add --symbol TSLA --stop 358.32+ python3 alerts.py add --symbol TSLA --target 370.04+ python3 alerts.py add --at 15:55 --label "flat by close" --before-close+ python3 alerts.py add --symbol KO --pct 3+ python3 alerts.py add --opening-bell+ python3 alerts.py check # rings what hit, once; exit 1 if nothing rang+ python3 alerts.py check --now "2026-10-19 15:55" --offline tests/fixtures/trader-alerts+ python3 alerts.py list+ python3 alerts.py reset tsla-plan-stop++Rule types:+ above / target the price is at or above "price"+ below / stop the price is at or below "price"+ pct_move the price moved "pct" percent or more from the previous close+ (or from "ref" if you give one); "direction": "up" or "down"+ opening_bell the NYSE opened today (rings once per trading day)+ time the New York clock passed "at" (HH:MM) on a trading day+ (rings once per trading day); "before_close": true moves it+ 3 hours earlier on a 1:00 p.m. early close, so a 15:55+ "flat by close" rings at 12:55 on those days++A rule with "date" is only watched on that New York date (rules from a plan+are for the plan's day only). An above / below alert rings ONCE and then stays+quiet until you reset it, unless the rule has "rearm": true (it re-arms when+the price crosses back). A pct_move alert rings at most once per day.++Quotes (free, delayed, unofficial; for alerts only, never for timing an order):+ yahoo https://query2.finance.yahoo.com/v8/finance/chart/TSLA (falls back to+ query1 on a 429 or a 5xx; one retry with a pause on a 429; one+ request per ticker, half a second apart; the default)+ stooq https://stooq.com/q/l/?s=tsla.us&f=sd2t2ohlcv&h&e=csv (Stooq's free+ CSV; it answered 404 on 2026-10-13, kept for when it is back)+ --offline DIR reads DIR/<source>-<TICKER>.json|csv (or .json.gz) instead.++NYSE calendar: the 2026 and 2027 holidays and 1:00 p.m. early closes as+published at https://www.nyse.com/markets/hours-calendars (read 2026-10-13).+Outside those years the clock says the holiday list is unknown.+"""++import argparse+import csv+import datetime+import gzip+import io+import json+import os+import re+import sys+import time+import urllib.error+import urllib.request++UA = "Mozilla/5.0 (compatible; day-trader-skill/2.0; +https://github.com/Jakeschincariol/day-trader-skill)"+PAUSE = 0.5 # seconds between requests: be polite to free endpoints+BACKOFF = 2.0 # seconds to wait before the one retry after a 429+YAHOO_HOSTS = ("query2.finance.yahoo.com", "query1.finance.yahoo.com")+HHMM = re.compile(r"^([01]?\d|2[0-3]):([0-5]\d)$")++NYSE_HOLIDAYS = {+ "2026-01-01": "New Year's Day",+ "2026-01-19": "Martin Luther King, Jr. Day",+ "2026-02-16": "Washington's Birthday",+ "2026-04-03": "Good Friday",+ "2026-05-25": "Memorial Day",+ "2026-06-19": "Juneteenth National Independence Day",+ "2026-07-03": "Independence Day (observed)",+ "2026-09-07": "Labor Day",+ "2026-11-26": "Thanksgiving Day",+ "2026-12-25": "Christmas Day",+ "2027-01-01": "New Year's Day",+ "2027-01-18": "Martin Luther King, Jr. Day",+ "2027-02-15": "Washington's Birthday",+ "2027-03-26": "Good Friday",+ "2027-05-31": "Memorial Day",+ "2027-06-18": "Juneteenth National Independence Day (observed)",+ "2027-07-05": "Independence Day (observed)",+ "2027-09-06": "Labor Day",+ "2027-11-25": "Thanksgiving Day",+ "2027-12-24": "Christmas Day (observed)",+}+NYSE_EARLY_CLOSE = { # 1:00 p.m. ET+ "2026-11-27": "day after Thanksgiving",+ "2026-12-24": "Christmas Eve",+ "2027-11-26": "day after Thanksgiving",+}+CALENDAR_YEARS = (2026, 2027)+OPEN = datetime.time(9, 30)+CLOSE = datetime.time(16, 0)+EARLY = datetime.time(13, 0)+++class AlertError(Exception):+ pass+++# ---------------------------------------------------------------- time++def _nth_sunday(year, month, n):+ d = datetime.date(year, month, 1)+ d += datetime.timedelta(days=(6 - d.weekday()) % 7)+ return d + datetime.timedelta(weeks=n - 1)+++def eastern_offset(utc):+ """Hours from UTC for New York: -4 in daylight time, -5 otherwise.+ DST runs from 2:00 a.m. on the second Sunday of March to 2:00 a.m. on the+ first Sunday of November (US rule since 2007)."""+ y = utc.year+ start = datetime.datetime.combine(_nth_sunday(y, 3, 2), datetime.time(7, 0)) # 2:00 EST+ end = datetime.datetime.combine(_nth_sunday(y, 11, 1), datetime.time(6, 0)) # 2:00 EDT+ naive = utc.replace(tzinfo=None)+ return -4 if start <= naive < end else -5+++def to_eastern(utc):+ return utc.replace(tzinfo=None) + datetime.timedelta(hours=eastern_offset(utc))+++def eastern_to_utc(local):+ for off in (-4, -5):+ utc = local - datetime.timedelta(hours=off)+ if eastern_offset(utc) == off:+ return utc+ return local + datetime.timedelta(hours=5)+++def parse_now(text):+ """ISO time -> naive UTC. A time without an offset is taken as New York time."""+ if not text:+ return datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0, tzinfo=None)+ t = text.strip().replace("Z", "+00:00")+ try:+ dt = datetime.datetime.fromisoformat(t)+ except ValueError:+ raise AlertError("--now wants a time like \"2026-10-19 10:15\" (New York) or ...Z (UTC)")+ if dt.tzinfo is None:+ return eastern_to_utc(dt)+ return (dt - dt.utcoffset()).replace(tzinfo=None)+++def trading_day(d):+ """(is_trading_day, reason). Weekends and the NYSE holiday list."""+ if d.weekday() >= 5:+ return False, "weekend"+ name = NYSE_HOLIDAYS.get(d.isoformat())+ if name:+ return False, "NYSE holiday: " + name+ return True, ""+++def session(d):+ """(open_time, close_time) in New York time, or None if closed all day."""+ ok, _ = trading_day(d)+ if not ok:+ return None+ return OPEN, (EARLY if d.isoformat() in NYSE_EARLY_CLOSE else CLOSE)+++def market_status(now_utc):+ local = to_eastern(now_utc)+ d = local.date()+ ok, reason = trading_day(d)+ st = {"now_new_york": local.strftime("%Y-%m-%d %H:%M"), "date": d.isoformat(),+ "weekday": local.strftime("%A"), "calendar_known": d.year in CALENDAR_YEARS,+ "open": False, "reason": reason, "early_close": NYSE_EARLY_CLOSE.get(d.isoformat())}+ s = session(d)+ if s:+ o, c = s+ st["opens"], st["closes"] = o.strftime("%H:%M"), c.strftime("%H:%M")+ if o <= local.time() < c:+ st["open"] = True+ st["reason"] = "regular session"+ elif local.time() < o:+ st["reason"] = "before the open"+ else:+ st["reason"] = "after the close"+ # next open+ nd = d if (s and local.time() < s[0]) else d + datetime.timedelta(days=1)+ for _ in range(15):+ if session(nd):+ st["next_open"] = "%s 09:30" % nd.isoformat()+ break+ nd += datetime.timedelta(days=1)+ return st+++# ---------------------------------------------------------------- quotes++def stooq_url(sym):+ return "https://stooq.com/q/l/?s=%s.us&f=sd2t2ohlcv&h&e=csv" % sym.lower().replace(".", "-")+++def yahoo_url(sym, host=YAHOO_HOSTS[0]):+ return "https://%s/v8/finance/chart/%s?range=1d&interval=1d" % (host, sym.upper().replace(".", "-"))+++def parse_stooq(text, sym):+ """Symbol,Date,Time,Open,High,Low,Close,Volume -> quote. N/D means no data."""+ rows = list(csv.DictReader(io.StringIO(text.strip())))+ if not rows:+ raise AlertError("Stooq returned no rows for %s" % sym)+ r = {k.strip().lower(): (v or "").strip() for k, v in rows[0].items() if k}+ close = r.get("close", "")+ if not close or close.upper() == "N/D":+ raise AlertError("Stooq has no data for %s (check the ticker)" % sym)++ def f(k):+ v = r.get(k, "")+ try:+ return float(v)+ except ValueError:+ return None+ return {"symbol": sym.upper(), "price": float(close), "open": f("open"), "high": f("high"),+ "low": f("low"), "prev_close": None, "time": ("%s %s" % (r.get("date", ""), r.get("time", ""))).strip(),+ "source": "stooq"}+++def parse_yahoo(text, sym):+ try:+ data = json.loads(text)+ res = data["chart"]["result"]+ except (ValueError, KeyError, TypeError):+ raise AlertError("Yahoo returned something unexpected for %s" % sym)+ if not res:+ err = (data.get("chart") or {}).get("error") or {}+ raise AlertError("Yahoo has no data for %s: %s" % (sym, err.get("description", "unknown ticker")))+ m = res[0].get("meta", {})+ price = m.get("regularMarketPrice")+ if price is None:+ raise AlertError("Yahoo has no price for %s" % sym)+ t = m.get("regularMarketTime")+ when = (datetime.datetime.fromtimestamp(t, datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+ if t else "")+ q = (res[0].get("indicators", {}).get("quote") or [{}])[0]+ opens = [x for x in (q.get("open") or []) if x is not None]+ return {"symbol": sym.upper(), "price": float(price), "open": opens[0] if opens else None,+ "high": m.get("regularMarketDayHigh"), "low": m.get("regularMarketDayLow"),+ "prev_close": m.get("previousClose") or m.get("chartPreviousClose"), "time": when,+ "currency": m.get("currency"), "source": "yahoo"}+++_urlopen = urllib.request.urlopen # tests swap these two+_sleep = time.sleep+++def _get(url, timeout=20):+ """(HTTP status, body). A network failure is an AlertError."""+ req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "*/*"})+ try:+ with _urlopen(req, timeout=timeout) as r:+ return 200, r.read().decode("utf-8", "replace")+ except urllib.error.HTTPError as e:+ try:+ body = e.read().decode("utf-8", "replace")+ except Exception:+ body = ""+ finally:+ try:+ e.close()+ except Exception:+ pass+ return e.code, body+ except urllib.error.URLError as e:+ raise AlertError("could not reach %s: %s" % (url.split("/")[2], e.reason))+++def fetch(url, timeout=20):+ code, text = _get(url, timeout)+ if code != 200:+ raise AlertError("%s answered HTTP %d" % (url.split("?")[0], code))+ return text+++def fetch_yahoo(sym, timeout=20):+ """query2 first. A 429 waits BACKOFF seconds and tries once more; a 429 or a 5xx+ after that moves on to query1. A 404 comes back as Yahoo's own error JSON."""+ last = None+ for host in YAHOO_HOSTS:+ url = yahoo_url(sym, host)+ code, text = _get(url, timeout)+ if code == 429:+ _sleep(BACKOFF)+ code, text = _get(url, timeout)+ if code == 200:+ return text+ if code == 404 and text.strip().startswith("{"):+ return text+ last = (url, code)+ if code != 429 and code < 500:+ break+ raise AlertError("%s answered HTTP %d" % (last[0].split("?")[0], last[1]))+++def _offline_text(folder, source, sym):+ ext = "csv" if source == "stooq" else "json"+ base = os.path.join(folder, "%s-%s.%s" % (source, sym, ext))+ if os.path.exists(base):+ with open(base, encoding="utf-8") as fh:+ return fh.read()+ if os.path.exists(base + ".gz"):+ with gzip.open(base + ".gz", "rt", encoding="utf-8") as fh:+ return fh.read()+ raise AlertError("no offline quote file %s" % base)+++def get_quotes(symbols, source="yahoo", offline=None, pause=PAUSE):+ """{SYM: quote} and [errors]. One request per ticker, with a pause between."""+ quotes, errors = {}, []+ for i, sym in enumerate(symbols):+ sym = sym.upper()+ try:+ if offline:+ text = _offline_text(offline, source, sym)+ else:+ if i and pause:+ _sleep(pause)+ text = fetch(stooq_url(sym)) if source == "stooq" else fetch_yahoo(sym)+ quotes[sym] = parse_stooq(text, sym) if source == "stooq" else parse_yahoo(text, sym)+ except AlertError as e:+ errors.append(str(e))+ return quotes, errors+++def write_prices(path, quotes, now_utc, source):+ old = {}+ if os.path.exists(path):+ try:+ with open(path, encoding="utf-8") as fh:+ old = json.load(fh)+ except (ValueError, OSError):+ old = {}+ prices = dict(old.get("prices", {}))+ detail = dict(old.get("detail", {}))+ stamp = now_utc.strftime("%Y-%m-%dT%H:%M:%SZ")+ for s, q in quotes.items():+ prices[s] = q["price"]+ detail[s] = {"prev_close": q.get("prev_close"), "time": q.get("time"), "source": q.get("source"),+ "fetched": stamp}+ doc = {"as_of": stamp, "source": source,+ "note": ("Delayed quotes for alerts and sizing checks. Your broker's price is the one that fills. "+ "detail.fetched is when each price was read."),+ "prices": prices, "detail": detail}+ _write(path, doc)+ return doc+++def _write(path, doc):+ d = os.path.dirname(path)+ if d:+ os.makedirs(d, exist_ok=True)+ tmp = path + ".tmp"+ with open(tmp, "w", encoding="utf-8") as fh:+ json.dump(doc, fh, indent=2)+ fh.write("\n")+ os.replace(tmp, path)+++def _read(path, default):+ if not path or not os.path.exists(path):+ return default+ try:+ with open(path, encoding="utf-8") as fh:+ return json.load(fh)+ except ValueError as e:+ raise AlertError("%s is not valid JSON: %s" % (path, e))+++# ---------------------------------------------------------------- rules++PRICE_TYPES = {"above", "below", "stop", "target", "pct_move", "opening_bell", "time"}+NO_QUOTE = {"opening_bell", "time"}+++def _hhmm(text):+ m = HHMM.match(str(text or "").strip())+ if not m:+ return None+ return datetime.time(int(m.group(1)), int(m.group(2)))+++def validate(rule):+ t = rule.get("type")+ if t not in PRICE_TYPES:+ raise AlertError("rule %s: unknown type %r" % (rule.get("id"), t))+ if t not in NO_QUOTE and not rule.get("symbol"):+ raise AlertError("rule %s needs a symbol" % rule.get("id"))+ if t in ("above", "below", "stop", "target") and not isinstance(rule.get("price"), (int, float)):+ raise AlertError("rule %s needs a numeric price" % rule.get("id"))+ if t == "pct_move" and not isinstance(rule.get("pct"), (int, float)):+ raise AlertError("rule %s needs a numeric pct" % rule.get("id"))+ if t == "time" and _hhmm(rule.get("at")) is None:+ raise AlertError("rule %s needs \"at\" as a New York time like \"15:55\"" % rule.get("id"))+ if rule.get("date") and not re.match(r"^\d{4}-\d{2}-\d{2}$", str(rule["date"])):+ raise AlertError("rule %s: date must be YYYY-MM-DD" % rule.get("id"))+++def active(rule, today):+ """A rule with a "date" is watched on that New York date only."""+ return not rule.get("date") or str(rule["date"]) == today+++def _rang_today(stamp, today):+ """Did a rule that rang at this UTC stamp ring on this New York date?"""+ if not stamp:+ return False+ try:+ utc = datetime.datetime.strptime(stamp[:19], "%Y-%m-%dT%H:%M:%S")+ except ValueError:+ return stamp[:10] == today+ return to_eastern(utc).date().isoformat() == today+++def ring_time(rule, status):+ """The time a time rule rings today, moved 3 hours earlier on an early close if "before_close"."""+ at = _hhmm(rule.get("at"))+ if rule.get("before_close") and status.get("early_close"):+ at = (datetime.datetime.combine(datetime.date(2000, 1, 1), at) - datetime.timedelta(hours=3)).time()+ return at+++def evaluate(rules, quotes, status, state, now_utc):+ """Pure function. Returns (rings, new_state). Each ring: {id, symbol, message}."""+ state = json.loads(json.dumps(state or {}))+ rung = state.setdefault("rung", {})+ today = status["date"]+ local = to_eastern(now_utc)+ stamp = now_utc.strftime("%Y-%m-%dT%H:%M:%SZ")+ rings = []+ for r in rules:+ validate(r)+ rid = r.get("id") or "%s-%s" % (r.get("symbol", "market"), r["type"])+ if not active(r, today):+ continue+ typ = {"stop": "below", "target": "above"}.get(r["type"], r["type"])+ if typ == "opening_bell":+ if status["open"] and not _rang_today(rung.get(rid), today):+ rings.append({"id": rid, "symbol": "", "message": "Opening bell: the NYSE is open (%s New York)%s."+ % (status["now_new_york"], (", early close at 1:00 p.m. today, "+ + status["early_close"]) if status.get("early_close") else "")})+ rung[rid] = stamp+ continue+ if typ == "time":+ at = ring_time(r, status)+ if status.get("opens") and local.time() >= at and not _rang_today(rung.get(rid), today):+ label = r.get("label") or "time alert"+ msg = "%s%s: it is %s New York (set for %s)" % (label[:1].upper(), label[1:],+ local.strftime("%H:%M"), at.strftime("%H:%M"))+ msg += (", the market closes at %s." % status["closes"]) if status["open"] else \+ ", the market has closed."+ sym = str(r.get("symbol") or "").upper()+ if sym:+ msg += (" If %s is still open, close it: trader-broker flatten --symbol %s builds the sell "+ "ticket, then trader-risk and your yes." % (sym, sym))+ rings.append({"id": rid, "symbol": sym, "message": msg})+ rung[rid] = stamp+ continue+ sym = r["symbol"].upper()+ q = quotes.get(sym)+ if not q:+ continue+ p = q["price"]+ if typ in ("above", "below"):+ hit = p >= r["price"] if typ == "above" else p <= r["price"]+ if hit and rid not in rung:+ word = "at or above" if typ == "above" else "at or below"+ label = {"stop": "stop", "target": "target"}.get(r["type"], "alert level")+ rings.append({"id": rid, "symbol": sym, "message": "%s %s $%.2f: %s your %s $%s%s."+ % (sym, "is" if status["open"] else "last", p, word, label, _n(r["price"]),+ (" (" + r["note"] + ")") if r.get("note") else "")})+ rung[rid] = stamp+ elif not hit and rid in rung and r.get("rearm"):+ del rung[rid]+ elif typ == "pct_move":+ ref = r.get("ref") or q.get("prev_close") or q.get("open")+ if not ref:+ continue+ move = 100.0 * (p / float(ref) - 1)+ want = r.get("direction")+ hit = abs(move) >= r["pct"] and (not want or (want == "up") == (move > 0))+ if hit and not _rang_today(rung.get(rid), today):+ rings.append({"id": rid, "symbol": sym, "message": "%s moved %+.2f%% to $%.2f (from $%.2f)."+ % (sym, move, p, float(ref))})+ rung[rid] = stamp+ state["last_check"] = stamp+ return rings, state+++def _n(x):+ x = float(x)+ return str(int(x)) if x == int(x) else "%.2f" % x+++def rules_from_plan(plan, cfg_flat_by=None):+ """trader/plan.json -> a stop alert, a target alert and a flat-by-close time alert, for the plan's day."""+ if not isinstance(plan, dict) or not plan.get("symbol"):+ raise AlertError("the plan has no symbol (run trader-exit first)")+ sym = str(plan["symbol"]).upper()+ out = []+ for key, typ, word in (("stop", "stop", "plan stop"), ("target", "target", "plan target")):+ v = plan.get(key)+ if not isinstance(v, (int, float)) or v <= 0:+ raise AlertError("the plan has no %s (run trader-exit)" % key)+ label = plan.get("%s_label" % key)+ out.append({"id": "%s-plan-%s" % (sym.lower(), key), "symbol": sym, "type": typ, "price": float(v),+ "note": word + (": " + label if label else "")})+ flat = plan.get("flat_by") or cfg_flat_by or "15:55"+ if _hhmm(flat) is None:+ raise AlertError("the plan's flat_by %r is not a time like 15:55" % flat)+ out.append({"id": "%s-flat-by" % sym.lower(), "symbol": sym, "type": "time", "at": flat,+ "label": "flat by close", "before_close": True})+ if plan.get("date"):+ for r in out:+ r["date"] = str(plan["date"])+ return out+++# ---------------------------------------------------------------- commands++def holdings(a):+ syms = []+ pf = _read(a.portfolio, {})+ for p in pf.get("positions", []) if isinstance(pf, dict) else []:+ syms.append(str(p.get("ticker") or p.get("symbol") or "").upper())+ plan = _read(a.plan, {})+ if isinstance(plan, dict) and plan.get("symbol"):+ syms.append(str(plan["symbol"]).upper())+ return [s for s in syms if s]+++def _dedupe(items):+ out = []+ for s in items:+ if s and s not in out:+ out.append(s)+ return out+++def cmd_clock(a):+ st = market_status(parse_now(a.now))+ if a.json:+ print(json.dumps(st, indent=2))+ else:+ print("New York %s (%s): NYSE %s, %s." % (st["now_new_york"], st["weekday"],+ "OPEN" if st["open"] else "closed", st["reason"]))+ if st.get("opens"):+ print("Today's session: %s to %s%s." % (st["opens"], st["closes"],+ (" (early close: %s)" % st["early_close"]) if st.get("early_close") else ""))+ if not st["open"] and st.get("next_open"):+ print("Next open: %s New York." % st["next_open"])+ if not st["calendar_known"]:+ print("Holiday list covers %s only: check nyse.com for this date." % " and ".join(map(str, CALENDAR_YEARS)))+ return 0 if st["open"] else 1+++def cmd_quote(a):+ syms = _dedupe([s.upper() for s in a.symbols] + (holdings(a) if a.holdings else []))+ if not syms:+ raise AlertError("which tickers? alerts.py quote TSLA KO, or --holdings")+ now = parse_now(a.now)+ quotes, errors = get_quotes(syms, a.source, a.offline)+ if a.write and quotes:+ write_prices(a.write, quotes, now, a.source)+ if a.json:+ print(json.dumps({"quotes": quotes, "errors": errors}, indent=2))+ else:+ for s in syms:+ q = quotes.get(s)+ if q:+ chg = ""+ if q.get("prev_close"):+ chg = " (%+.2f%% vs prev close $%.2f)" % (100.0 * (q["price"] / q["prev_close"] - 1), q["prev_close"])+ print("%-6s $%.2f%s %s [%s]" % (s, q["price"], chg, q.get("time", ""), q["source"]))+ for e in errors:+ print("error: " + e)+ if a.write and quotes:+ print("Wrote %d price(s) to %s." % (len(quotes), a.write))+ print("Quotes are free, delayed and unofficial: for alerts only. Your broker's price is the one that fills.")+ return 0 if quotes else 1+++def cmd_check(a):+ doc = _read(a.rules, None)+ if not doc or not doc.get("rules"):+ raise AlertError("no rules in %s: add some with alerts.py add --from-plan" % a.rules)+ rules = doc["rules"]+ now = parse_now(a.now)+ status = market_status(now)+ watched = [r for r in rules if active(r, status["date"])]+ syms = _dedupe([str(r.get("symbol", "")).upper() for r in watched if r.get("type") not in NO_QUOTE])+ quotes, errors = (get_quotes(syms, a.source, a.offline) if syms else ({}, []))+ state = _read(a.state, {})+ rings, state = evaluate(rules, quotes, status, state, now)+ if not a.no_write:+ _write(a.state, state)+ if quotes:+ write_prices(a.prices_out, quotes, now, a.source)+ if a.json:+ print(json.dumps({"market": status, "rings": rings, "errors": errors,+ "quotes": {s: q["price"] for s, q in quotes.items()}}, indent=2))+ else:+ print("NYSE %s (%s New York, %s)." % ("OPEN" if status["open"] else "closed", status["now_new_york"],+ status["reason"]))+ for r in rings:+ print("ALERT " + r["message"])+ if not rings:+ print("Nothing hit. %d rule(s) watched today%s." % (+ len(watched), (", " + ", ".join("%s $%.2f" % (s, quotes[s]["price"]) for s in syms if s in quotes))+ if quotes else ""))+ for e in errors:+ print("error: " + e)+ if rings:+ print("An alert is information, not an order. A bracket's stop-loss and take-profit already sit at "+ "the broker: check get_open_position and record any fill (ticket.py fill). To close a "+ "position yourself: ticket.py flatten, then trader-risk and your yes.")+ return 0 if rings else 1+++def cmd_add(a):+ doc = _read(a.rules, {"rules": []})+ doc.setdefault("rules", [])+ if a.from_plan:+ plan = _read(a.plan, None)+ if plan is None:+ raise AlertError("no plan at %s (run trader-exit first)" % a.plan)+ cfg = _read(a.config, {}) if a.config else {}+ new = rules_from_plan(plan, (cfg or {}).get("flat_by"))+ ids = {r["id"] for r in new}+ doc["rules"] = [r for r in doc["rules"] if r.get("id") not in ids] + new+ state = _read(a.state, {})+ if state.get("rung"):+ for i in ids:+ state["rung"].pop(i, None)+ _write(a.state, state)+ _write(a.rules, doc)+ for r in new:+ print("Added %s: %s" % (r["id"], json.dumps(r)))+ print("Run alerts.py check every few minutes while the trade is open (a scheduled task or /loop). "+ "Free quotes are delayed; the broker's bracket orders are what actually stop you out.")+ return 0+ if a.opening_bell:+ rule = {"id": a.id or "opening-bell", "type": "opening_bell"}+ elif a.at:+ if _hhmm(a.at) is None:+ raise AlertError("--at wants a New York time like 15:55")+ rule = {"id": a.id or ("time-%s" % a.at.replace(":", "")), "type": "time", "at": a.at,+ "label": a.label or "time alert"}+ if a.symbol:+ rule["symbol"] = a.symbol.upper()+ if a.before_close:+ rule["before_close"] = True+ else:+ if not a.symbol:+ raise AlertError("--symbol is required (or --from-plan, --at, --opening-bell)")+ sym = a.symbol.upper()+ if a.above is not None:+ rule = {"type": "above", "price": a.above}+ elif a.below is not None:+ rule = {"type": "below", "price": a.below}+ elif a.stop is not None:+ rule = {"type": "stop", "price": a.stop}+ elif a.target is not None:+ rule = {"type": "target", "price": a.target}+ elif a.pct is not None:+ rule = {"type": "pct_move", "pct": a.pct}+ if a.direction:+ rule["direction"] = a.direction+ else:+ raise AlertError("give one of --above, --below, --stop, --target or --pct")+ val = rule.get("price", rule.get("pct"))+ rule = dict({"id": a.id or ("%s-%s-%s" % (sym.lower(), rule["type"], _n(val)))}, symbol=sym, **rule)+ if a.rearm:+ rule["rearm"] = True+ if a.note:+ rule["note"] = a.note+ if a.date:+ rule["date"] = a.date+ validate(rule)+ if any(r.get("id") == rule["id"] for r in doc["rules"]):+ raise AlertError("a rule with id %s already exists" % rule["id"])+ doc["rules"].append(rule)+ _write(a.rules, doc)+ print("Added %s: %s" % (rule["id"], json.dumps(rule)))+ return 0+++def cmd_list(a):+ doc = _read(a.rules, {"rules": []})+ state = _read(a.state, {})+ if not doc.get("rules"):+ print("No rules yet.")+ return 1+ for r in doc["rules"]:+ rid = r.get("id")+ rung = state.get("rung", {}).get(rid)+ print("%-24s %s%s" % (rid, json.dumps({k: v for k, v in r.items() if k != "id"}),+ (" (rang %s)" % rung) if rung else ""))+ return 0+++def cmd_reset(a):+ state = _read(a.state, {})+ if a.id not in state.get("rung", {}):+ print("%s has not rung (nothing to reset)." % a.id)+ return 1+ del state["rung"][a.id]+ _write(a.state, state)+ print("Re-armed %s." % a.id)+ return 0+++def main(argv=None):+ ap = argparse.ArgumentParser(description="Price alerts and the NYSE clock (trader-alerts).")+ sub = ap.add_subparsers(dest="cmd")++ def net(p):+ p.add_argument("--source", default="yahoo", choices=["yahoo", "stooq"])+ p.add_argument("--offline", metavar="DIR", help="read <source>-<TICKER>.json|csv files, no network")+ p.add_argument("--now", help="pretend it is this time (no offset = New York time)")+ p.add_argument("--json", action="store_true")++ p = sub.add_parser("clock", help="is the NYSE open?")+ p.add_argument("--now")+ p.add_argument("--json", action="store_true")+ p = sub.add_parser("quote", help="latest delayed quotes")+ net(p)+ p.add_argument("symbols", nargs="*")+ p.add_argument("--holdings", action="store_true", help="add tickers from your portfolio and plan")+ p.add_argument("--portfolio", default="trader/portfolio.json")+ p.add_argument("--plan", default="trader/plan.json")+ p.add_argument("--write", nargs="?", const="trader/prices.json", metavar="PATH",+ help="save to prices.json (default trader/prices.json)")+ p = sub.add_parser("check", help="check every rule, ring what hit")+ net(p)+ p.add_argument("--rules", default="trader/alerts.json")+ p.add_argument("--state", default="trader/state/alerts.json")+ p.add_argument("--prices-out", default="trader/prices.json")+ p.add_argument("--no-write", action="store_true")+ p = sub.add_parser("add", help="add a rule")+ p.add_argument("--rules", default="trader/alerts.json")+ p.add_argument("--state", default="trader/state/alerts.json")+ p.add_argument("--symbol")+ g = p.add_mutually_exclusive_group()+ g.add_argument("--above", type=float)+ g.add_argument("--below", type=float)+ g.add_argument("--stop", type=float)+ g.add_argument("--target", type=float)+ g.add_argument("--pct", type=float)+ g.add_argument("--opening-bell", action="store_true")+ g.add_argument("--at", metavar="HH:MM", help="a time alert, New York time")+ g.add_argument("--from-plan", action="store_true", help="stop, target and flat-by-close from the plan")+ p.add_argument("--plan", default="trader/plan.json")+ p.add_argument("--config", default="trader/config.json", help="flat_by when the plan has none")+ p.add_argument("--label", help="what a time alert says, e.g. \"flat by close\"")+ p.add_argument("--before-close", action="store_true",+ help="a time alert that moves 3 hours earlier on a 1:00 p.m. early close")+ p.add_argument("--date", help="watch this rule on this New York date only (YYYY-MM-DD)")+ p.add_argument("--direction", choices=["up", "down"])+ p.add_argument("--rearm", action="store_true")+ p.add_argument("--note")+ p.add_argument("--id")+ p = sub.add_parser("list", help="list the rules")+ p.add_argument("--rules", default="trader/alerts.json")+ p.add_argument("--state", default="trader/state/alerts.json")+ p = sub.add_parser("reset", help="re-arm a rule that rang")+ p.add_argument("id")+ p.add_argument("--state", default="trader/state/alerts.json")+ a = ap.parse_args(argv)+ if not a.cmd:+ ap.print_help()+ return 1+ try:+ return {"clock": cmd_clock, "quote": cmd_quote, "check": cmd_check, "add": cmd_add,+ "list": cmd_list, "reset": cmd_reset}[a.cmd](a)+ except AlertError as e:+ print("alerts.py: %s" % e, file=sys.stderr)+ return 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/trader-analyst/SKILL.md b/trader-analyst/SKILL.mdnew file mode 100644index 0000000..9d9b95a--- /dev/null+++ b/trader-analyst/SKILL.md@@ -0,0 +1,123 @@+---+name: trader-analyst+description: >-+ The Earnings Analyst. Reads a company's reported numbers straight from SEC+ EDGAR (XBRL company facts from its 10-Qs and 10-Ks, plus the latest earnings+ 8-K and its press release) and sums up what changed: revenue, gross,+ operating and net margins, net income and diluted EPS, quarter by quarter,+ each against the same quarter a year earlier, with the trailing twelve+ months. Reads an earnings call transcript when you paste one. Use when the+ user says "how did Tesla's earnings look", "analyze the earnings", "what+ changed this quarter", "is revenue growing", "check the 10-Q", "compare+ margins", "sum up the call", "does it report this week", or before trading+ a stock around its earnings.+argument-hint: "[tickers]"+---++# trader-analyst++Earnings move stocks more than anything else on the calendar, and the press+release is written to put the best number first. This skill reads the numbers+the company actually filed with the SEC, lines them up quarter by quarter, and+says plainly what changed. For a day trader it answers two questions before a+trade: what did the last report say, and is the next one inside this trade?++Tool in this folder (standard library Python, no keys):++```bash+python3 "${CLAUDE_SKILL_DIR}/facts.py" --help+```++It needs the SEC User-Agent (`sec_user_agent` in `trader/config.json`, or+`SEC_USER_AGENT`): "Your Name [email protected]" with the user's real name and+email. It refuses to call SEC without one.++## What it reads and writes++- Reads `https://data.sec.gov/api/xbrl/companyfacts/CIK##########.json` (every+ number the company has tagged in its filings), the company's submissions+ list (for the newest 10-Q or 10-K and the newest 8-K with item 2.02,+ "Results of Operations") and that 8-K's folder to find the press release+ (the EX-99.1 exhibit).+- Writes `trader/metrics.json` with `--metrics`: one row per company (TTM+ revenue, net income and diluted EPS, the latest margins and growth), for+ your notes or a spreadsheet. `metrics.example.json` in this folder is a+ real run for AAPL, AXP, GOOGL, KO and BAC on 2026-10-13.+- Earnings calls: the tool does not fetch transcripts. If the user pastes one+ (or the company's IR page has it), read it and sum up what management said+ changed: guidance, margins, demand, anything they declined to answer.+- The next report date is not in SEC data. Look for it in `/trader-news`+ headlines or on the company's investor relations page, and say where it+ came from.++## The rules++- **Filed numbers first.** The table comes from XBRL facts the company filed.+ Use the press release for context (guidance, segment colour), and say which+ numbers came from where.+- **Compare like with like.** Growth is against the same quarter a year+ earlier. Quarter-on-quarter changes are shown but many businesses are+ seasonal (Apple's December quarter is always its biggest).+- **Say what is derived.** Companies do not file a Q4 10-Q. The fourth+ quarter is the 10-K year minus the three quarters inside it and is marked+ "derived"; derived EPS is approximate.+- **Say when the data lags.** SEC's facts API can trail a filing. When the+ newest 10-Q is later than the newest quarter in the facts, the tool prints a+ NOTE with the link: read the 10-Q itself before summarising.+- **Flag one-offs.** When net income is above operating income, gains outside+ the business (investment marks, tax items) are inside it. The tool says so.+ Banks and insurers have no gross margin: blank, not zero.++## Steps++1. Run it for the companies in question (or the tickers on+ `trader/watchlist.json`):++ ```bash+ python3 "${CLAUDE_SKILL_DIR}/facts.py" TSLA+ python3 "${CLAUDE_SKILL_DIR}/facts.py" TSLA NVDA AMD --metrics trader/metrics.json+ ```++ `--quarters 8` shows two years, `--json` everything machine-readable,+ `--cik` a company without a ticker.+2. Open the latest earnings press release (the EX-99 link) and the 10-Q when+ the numbers need context, and read them.+3. Write the summary: one line on the quarter (revenue, EPS, growth), one on+ margins, one on anything unusual (a one-off, a derived quarter, data that+ lags), and the links. Plain words, real numbers, no adjectives the numbers+ do not support.+4. If the next report falls inside the planned trade (an overnight hold, or a+ report before the open), say it before `/trader-exit` sets the stop: a stop+ does not protect against a gap, the stock can open past it.++## Example: the reel's stock++`facts.py TSLA` (run 2026-10-20): quarter ending 2026-06-30 (Q2 2026),+revenue $28.24B, +25.5% against a year earlier, net income $1.11B (-4.9%),+diluted EPS $0.32 (-3.0%); gross margin 16.8% (-4.3 points on the quarter+before), operating margin 1.4%; last four quarters $103.6B revenue and $1.08+EPS. The tool flags that net income is above operating income, so gains+outside the business are inside it. Latest 10-Q filed 2026-07-23. Monday's+headlines said Tesla reports this week, so the summary ends: "The next report+is days away. A day trade that closes before the bell is not exposed to it;+anything held overnight is."++`facts.py AAPL` (2026-10-13): revenue $109.42B, +16.4% against a year+earlier, diluted EPS $2.02 (+28.7%). For Coca-Cola the tool noted that SEC's+facts stopped at 2026-04-03 while the 10-Q for 2026-07-03 was already filed,+so the summary read that 10-Q directly.++## What it never does++- Never says a stock is cheap, expensive, a buy or a sell. It reports what+ the company filed.+- Never invents a number the filings do not have, or estimates a quarter it+ cannot derive.+- Never calls SEC without the User-Agent, and stays well under 10 requests a+ second.++## Safety++Education and tooling, not financial advice. This skill only reads filings.+Nothing places an order except `/trader-broker`, after `/trader-risk` passes+and the user types an explicit yes for that order.diff --git a/trader-analyst/facts.py b/trader-analyst/facts.pynew file mode 100644index 0000000..8dc27a6--- /dev/null+++ b/trader-analyst/facts.py@@ -0,0 +1,548 @@+#!/usr/bin/env python3+"""Earnings reader for trader-analyst. Standard library only.++Pulls a company's reported numbers from SEC's XBRL "company facts" API and+lays out what changed, quarter by quarter: revenue, gross, operating and net+margins, net income, diluted EPS, and growth against the same quarter a year+earlier. It also finds the latest earnings press release (the EX-99 exhibit+of the newest 8-K with item 2.02) and the latest 10-Q or 10-K.++ python3 facts.py AAPL+ python3 facts.py AAPL KO --quarters 8+ python3 facts.py AAPL --json+ python3 facts.py AAPL AXP GOOGL KO BAC --metrics trader/metrics.json++Sources (SEC; a User-Agent with your name and email is required, from+--user-agent, SEC_USER_AGENT or sec_user_agent in trader/config.json):+ https://www.sec.gov/files/company_tickers.json ticker -> CIK+ https://data.sec.gov/api/xbrl/companyfacts/CIK##########.json+ https://data.sec.gov/submissions/CIK##########.json filings list+ https://www.sec.gov/Archives/edgar/data/<cik>/<accession>/index.json++How the quarters are built:+ - A quarter is a reported value covering about three months (80 to 100+ days). When a period was reported more than once (a later filing repeats+ it as a comparison), the latest filing wins, so restatements are used.+ - Companies do not file a fourth-quarter 10-Q. The fourth quarter is the+ full year (10-K) minus the three quarters inside it, and it is marked+ "derived". Derived EPS is approximate: share counts change during a year.+ - Revenue is read from the first concept a company uses of:+ RevenueFromContractWithCustomerExcludingAssessedTax, Revenues,+ RevenuesNetOfInterestExpense, SalesRevenueNet and a few more. Banks and+ insurers report revenue differently; margins for them can be blank.++--metrics FILE merges one row per ticker into a JSON file (for notes or a sheet)+(TTM revenue and EPS, margins, growth). Offline: --offline DIR reads+company_tickers.json, companyfacts-CIK##########.json,+submissions-CIK##########.json and <accession>/index.json from DIR.++Numbers only: this tool never says whether a stock is a buy.+"""++import argparse+import datetime as _dt+import gzip+import json+import os+import re+import sys+import time+import urllib.error+import urllib.request++TICKERS_URL = "https://www.sec.gov/files/company_tickers.json"+FACTS_URL = "https://data.sec.gov/api/xbrl/companyfacts/CIK%s.json"+SUBMISSIONS_URL = "https://data.sec.gov/submissions/CIK%s.json"+ARCHIVE_URL = "https://www.sec.gov/Archives/edgar/data/%d/%s/"+PLACEHOLDER = "[email protected]"+UA_HELP = ("SEC requires a User-Agent with your name and email. Set \"sec_user_agent\": "+ "\"Your Name [email protected]\" in trader/config.json (your real name and email), "+ "or export SEC_USER_AGENT, or pass --user-agent.")++CONCEPTS = {+ "revenue": ["RevenueFromContractWithCustomerExcludingAssessedTax", "Revenues",+ "RevenuesNetOfInterestExpense", "RevenueFromContractWithCustomerIncludingAssessedTax",+ "SalesRevenueNet", "SalesRevenueGoodsNet", "SalesRevenueServicesNet"],+ "cost_of_revenue": ["CostOfGoodsAndServicesSold", "CostOfRevenue", "CostOfGoodsSold"],+ "gross_profit": ["GrossProfit"],+ "operating_income": ["OperatingIncomeLoss"],+ "net_income": ["NetIncomeLoss", "ProfitLoss", "NetIncomeLossAvailableToCommonStockholdersBasic"],+ "eps_diluted": ["EarningsPerShareDiluted", "EarningsPerShareBasicAndDiluted"],+}+FLOWS = ("revenue", "cost_of_revenue", "gross_profit", "operating_income", "net_income")+++class FactsError(Exception):+ pass+++def user_agent(cli=None, config="trader/config.json"):+ ua = (cli or os.environ.get("SEC_USER_AGENT") or "").strip()+ if not ua and config and os.path.isfile(config):+ try:+ with open(config, encoding="utf-8") as fh:+ ua = str(json.load(fh).get("sec_user_agent") or "").strip()+ except (OSError, ValueError):+ ua = ""+ if not ua or "@" not in ua or PLACEHOLDER in ua:+ return None+ return ua+++class Fetcher(object):+ def __init__(self, ua=None, offline=None, pause=0.15):+ self.ua, self.offline, self.pause, self._last = ua, offline, pause, 0.0++ def json(self, url, name):+ if self.offline:+ path = os.path.join(self.offline, name)+ if not os.path.isfile(path):+ raise FactsError("offline: no file %s" % path)+ with open(path, encoding="utf-8") as fh:+ return json.load(fh)+ if not self.ua:+ raise FactsError(UA_HELP)+ gap = time.time() - self._last+ if gap < self.pause:+ time.sleep(self.pause - gap)+ self._last = time.time()+ req = urllib.request.Request(url, headers={"User-Agent": self.ua,+ "Accept-Encoding": "gzip"})+ try:+ with urllib.request.urlopen(req, timeout=60) as resp:+ data = resp.read()+ if resp.headers.get("Content-Encoding") == "gzip":+ data = gzip.decompress(data)+ except urllib.error.HTTPError as exc:+ if exc.code == 404:+ raise FactsError("SEC has no data at %s (no XBRL filings for this CIK?)" % url)+ raise FactsError("HTTP %s for %s" % (exc.code, url))+ except urllib.error.URLError as exc:+ raise FactsError("could not reach %s: %s" % (url, exc.reason))+ return json.loads(data.decode("utf-8"))+++# ---------------------------------------------------------------- facts++def _date(s):+ return _dt.date.fromisoformat(s)+++def facts_for(companyfacts, concept, unit_hint=None):+ """Raw facts for one us-gaap concept (USD, or USD/shares for EPS)."""+ node = companyfacts.get("facts", {}).get("us-gaap", {}).get(concept)+ if not node:+ return []+ units = node.get("units", {})+ unit = unit_hint if unit_hint in units else next(iter(units), None)+ return units.get(unit, []) if unit else []+++def periods(facts):+ """{(start, end): fact} for duration facts from 10-Q/10-K.++ The value comes from the latest filing (restatements win). The fiscal+ label (fy, fp) comes from the first filing that reported the period: a+ later 10-Q that repeats it as a comparison carries its own fy and fp."""+ latest, first = {}, {}+ for f in facts:+ if "start" not in f or f.get("form", "").split("/")[0] not in ("10-Q", "10-K", "20-F", "40-F"):+ continue+ key = (f["start"], f["end"])+ stamp = (f.get("filed", ""), f.get("accn", ""))+ if key not in latest or stamp > (latest[key].get("filed", ""), latest[key].get("accn", "")):+ latest[key] = f+ if key not in first or stamp < (first[key].get("filed", ""), first[key].get("accn", "")):+ first[key] = f+ out = {}+ for key, f in latest.items():+ g = dict(f)+ g["fy"], g["fp"] = first[key].get("fy"), first[key].get("fp")+ g["first_filed"] = first[key].get("filed")+ out[key] = g+ return out+++def quarterly(facts, derive_q4=True):+ """{end: {"value", "start", "end", "derived", "fy", "fp", "form"}} three-month values."""+ per = periods(facts)+ q = {}+ years = []+ for (start, end), f in per.items():+ days = (_date(end) - _date(start)).days+ if 80 <= days <= 100:+ q[end] = {"value": f["val"], "start": start, "end": end, "derived": False,+ "fy": f.get("fy"), "fp": f.get("fp"), "form": f.get("form"),+ "filed": f.get("filed")}+ elif 350 <= days <= 380:+ years.append((start, end, f))+ if derive_q4:+ for start, end, f in years:+ if end in q:+ continue+ inside = [v for v in q.values() if v["start"] >= start and v["end"] < end]+ inside.sort(key=lambda v: v["end"])+ if len(inside) != 3:+ continue+ last_q_start = _date(inside[-1]["end"]) + _dt.timedelta(days=1)+ q[end] = {"value": f["val"] - sum(v["value"] for v in inside),+ "start": last_q_start.isoformat(), "end": end, "derived": True,+ "fy": f.get("fy"), "fp": "Q4", "form": f.get("form"),+ "filed": f.get("filed")}+ return q+++def series(companyfacts, key, derive_q4=True):+ """Quarterly series for a metric, trying its concepts in order and filling gaps."""+ unit = "USD/shares" if key == "eps_diluted" else "USD"+ merged, used = {}, []+ for concept in CONCEPTS[key]:+ q = quarterly(facts_for(companyfacts, concept, unit), derive_q4)+ if not q:+ continue+ added = False+ for end, v in q.items():+ if end not in merged:+ merged[end] = dict(v, concept=concept)+ added = True+ if added:+ used.append(concept)+ return merged, used+++def _yoy_match(series_, end, days=365, slack=10):+ target = _date(end) - _dt.timedelta(days=days)+ best = None+ for e in series_:+ gap = abs((_date(e) - target).days)+ if gap <= slack and (best is None or gap < best[0]):+ best = (gap, e)+ return series_[best[1]] if best else None+++def pct(a, b):+ if a is None or b in (None, 0):+ return None+ return round(100.0 * (a - b) / abs(b), 1)+++def margin(part, whole):+ if part is None or not whole:+ return None+ return round(100.0 * part / whole, 1)+++def analyse(companyfacts, quarters=6, name=None):+ """Every number in the report, as a dict."""+ s = {}+ concepts = {}+ for key in CONCEPTS:+ s[key], concepts[key] = series(companyfacts, key, derive_q4=True)+ rev = s["revenue"]+ if not rev and not s["net_income"]:+ raise FactsError("no quarterly revenue or net income in the XBRL facts")+ ends = sorted(set(rev) | set(s["net_income"]), reverse=True)[:quarters]+ rows = []+ for end in ends:+ r = rev.get(end, {}).get("value")+ gp = s["gross_profit"].get(end, {}).get("value")+ if gp is None and r is not None and end in s["cost_of_revenue"]:+ gp = r - s["cost_of_revenue"][end]["value"]+ oi = s["operating_income"].get(end, {}).get("value")+ ni = s["net_income"].get(end, {}).get("value")+ eps = s["eps_diluted"].get(end, {}).get("value")+ prior = {k: _yoy_match(s[k], end) for k in ("revenue", "net_income", "eps_diluted")}+ base = rev.get(end) or s["net_income"].get(end) or {}+ rows.append({+ "end": end, "start": base.get("start"),+ "fiscal": "%s %s" % (base.get("fp") or "", base.get("fy") or ""),+ "derived": any(s[k].get(end, {}).get("derived") for k in ("revenue", "net_income")),+ "revenue": r, "gross_profit": gp, "operating_income": oi, "net_income": ni,+ "eps_diluted": round(eps, 2) if eps is not None else None,+ "gross_margin": margin(gp, r), "operating_margin": margin(oi, r),+ "net_margin": margin(ni, r),+ "revenue_yoy": pct(r, (prior["revenue"] or {}).get("value")),+ "net_income_yoy": pct(ni, (prior["net_income"] or {}).get("value")),+ "eps_yoy": pct(eps, (prior["eps_diluted"] or {}).get("value")),+ "filed": base.get("filed"), "form": base.get("form"),+ })+ ttm = {}+ for key in ("revenue", "net_income", "eps_diluted"):+ last4 = sorted(s[key])[-4:]+ if len(last4) == 4 and (_date(last4[-1]) - _date(last4[0])).days < 300:+ ttm[key] = sum(s[key][e]["value"] for e in last4)+ if "eps_diluted" in ttm:+ ttm["eps_diluted"] = round(ttm["eps_diluted"], 2)+ return {"entity": name or companyfacts.get("entityName"),+ "cik": str(companyfacts.get("cik", "")).zfill(10),+ "rows": rows, "ttm": ttm, "concepts": concepts}+++def stale_note(result, filings):+ """A note when SEC's facts lag a report that is already filed."""+ rep = (filings or {}).get("report")+ if not rep or not result["rows"] or not rep.get("period"):+ return None+ latest = result["rows"][0]["end"]+ if rep["period"] > latest and (_date(rep["period"]) - _date(latest)).days > 20:+ return ("SEC's XBRL facts stop at %s, but a %s for the period ending %s was filed %s. "+ "Read it directly: %s" % (latest, rep["form"], rep["period"], rep["filed"],+ rep["url"]))+ return None+++def changes(result):+ """Plain sentences: what changed in the latest quarter."""+ rows = result["rows"]+ if not rows:+ return []+ cur = rows[0]+ prev = rows[1] if len(rows) > 1 else None+ out = []++ def money(v):+ return "n/a" if v is None else "$%.2fB" % (v / 1e9) if abs(v) >= 1e9 else "$%.1fM" % (v / 1e6)++ label = "Quarter ending %s%s" % (cur["end"], " (derived from the 10-K)" if cur["derived"] else "")+ line = "%s: revenue %s" % (label, money(cur["revenue"]))+ if cur["revenue_yoy"] is not None:+ line += " (%+.1f%% vs a year earlier)" % cur["revenue_yoy"]+ line += ", net income %s" % money(cur["net_income"])+ if cur["net_income_yoy"] is not None:+ line += " (%+.1f%%)" % cur["net_income_yoy"]+ if cur["eps_diluted"] is not None:+ line += ", diluted EPS $%.2f" % cur["eps_diluted"]+ if cur["eps_yoy"] is not None:+ line += " (%+.1f%%)" % cur["eps_yoy"]+ out.append(line + ".")+ for key, name in (("gross_margin", "Gross margin"), ("operating_margin", "Operating margin"),+ ("net_margin", "Net margin")):+ if cur[key] is None:+ continue+ s = "%s %.1f%%" % (name, cur[key])+ if prev and prev[key] is not None:+ s += " (%+.1f points vs the quarter before)" % (cur[key] - prev[key])+ out.append(s + ".")+ if cur["net_income"] is not None and cur["operating_income"] is not None \+ and cur["net_income"] > cur["operating_income"]:+ out.append("Net income is above operating income: it includes gains outside the "+ "business (investments, tax items). Check the 10-Q before reading it as growth.")+ if prev and cur["revenue"] is not None and prev["revenue"]:+ out.append("Revenue %+.1f%% vs the quarter before (many businesses are seasonal: "+ "compare with a year earlier first)." % pct(cur["revenue"], prev["revenue"]))+ return out+++# ---------------------------------------------------------------- filings++EXHIBIT_RANK = [r"ex(?:hibit)?[-_]?99[-_.]?0?1(?!\d)", r"ex(?:hibit)?[-_]?99",+ r"earnings|release|press", r"ex(?:hibit)?[-_]?\d"]+++def exhibit_name(names, primary=None):+ """The press release among a filing's files (EX-99.1 by its usual names)."""+ docs = [n for n in names if n.lower().endswith((".htm", ".html", ".txt", ".pdf"))+ and n != primary and not re.match(r"^(R\d+\.htm|\d{10}-\d{2}-\d{6})", n)]+ for rx in EXHIBIT_RANK:+ hits = sorted(n for n in docs if re.search(rx, n, re.I))+ if hits:+ return hits[0]+ return None+++def latest_filings(submissions, cik, fetcher=None):+ """Newest 10-Q/10-K and newest earnings 8-K (item 2.02) with its EX-99 exhibit."""+ rec = submissions.get("filings", {}).get("recent", {})+ out = {"report": None, "earnings_8k": None}+ base_cik = int(cik)+ for i, form in enumerate(rec.get("form", [])):+ acc = rec["accessionNumber"][i]+ folder = ARCHIVE_URL % (base_cik, acc.replace("-", ""))+ if out["report"] is None and form in ("10-Q", "10-K", "20-F", "40-F"):+ out["report"] = {"form": form, "filed": rec["filingDate"][i],+ "period": rec["reportDate"][i], "accession": acc,+ "url": folder + rec["primaryDocument"][i]}+ if out["earnings_8k"] is None and form == "8-K" and "2.02" in (rec.get("items", [""] * (i + 1))[i] or ""):+ e = {"form": form, "filed": rec["filingDate"][i], "accession": acc,+ "url": folder + rec["primaryDocument"][i], "exhibit": None,+ "index": folder + "%s-index.htm" % acc}+ if fetcher is not None:+ try:+ idx = fetcher.json(folder + "index.json", os.path.join(acc.replace("-", ""), "index.json"))+ names = [it["name"] for it in idx.get("directory", {}).get("item", [])]+ pick = exhibit_name(names, rec["primaryDocument"][i])+ if pick:+ e["exhibit"] = folder + pick+ except FactsError:+ pass+ out["earnings_8k"] = e+ if out["report"] and out["earnings_8k"]:+ break+ return out+++# ---------------------------------------------------------------- output++def _m(v):+ if v is None:+ return "-"+ return "{:,.0f}".format(v / 1e6)+++def _p(v):+ return "-" if v is None else "%+.1f%%" % v if v < 0 or v > 0 else "0.0%"+++def _pm(v):+ return "-" if v is None else "%.1f%%" % v+++def render(ticker, result, filings):+ out = ["%s (%s), CIK %s. US$ millions except EPS. Source: SEC XBRL company facts." % (+ result["entity"], ticker, result["cik"]), ""]+ out.append("%-11s %-9s %10s %8s %7s %7s %7s %10s %8s %7s" % (+ "quarter end", "fiscal", "revenue", "rev yoy", "gross", "oper", "net",+ "net inc", "EPS dil", "EPS yoy"))+ for r in result["rows"]:+ out.append("%-11s %-9s %10s %8s %7s %7s %7s %10s %8s %7s%s" % (+ r["end"], r["fiscal"].strip()[:9], _m(r["revenue"]), _p(r["revenue_yoy"]),+ _pm(r["gross_margin"]), _pm(r["operating_margin"]), _pm(r["net_margin"]),+ _m(r["net_income"]), "-" if r["eps_diluted"] is None else "%.2f" % r["eps_diluted"],+ _p(r["eps_yoy"]), " derived" if r["derived"] else ""))+ t = result["ttm"]+ if t:+ out.append("")+ out.append("Last 4 quarters: revenue %s, net income %s, diluted EPS %s." % (+ "$" + _m(t.get("revenue")) + "M" if t.get("revenue") is not None else "-",+ "$" + _m(t.get("net_income")) + "M" if t.get("net_income") is not None else "-",+ "$%.2f" % t["eps_diluted"] if t.get("eps_diluted") is not None else "-"))+ out.append("")+ out.append("What changed:")+ for line in changes(result):+ out.append(" - " + line)+ if filings:+ out.append("")+ rep, e8 = filings.get("report"), filings.get("earnings_8k")+ if rep:+ out.append("Latest %s: period %s, filed %s %s" % (rep["form"], rep["period"],+ rep["filed"], rep["url"]))+ if e8:+ out.append("Latest earnings 8-K (item 2.02): filed %s %s" % (+ e8["filed"], e8["exhibit"] or e8["index"]))+ note = stale_note(result, filings)+ if note:+ out.append("")+ out.append("NOTE: " + note)+ if any(r["derived"] for r in result["rows"]):+ out.append("")+ out.append("Derived quarters are the 10-K year minus the three 10-Qs; derived EPS is "+ "approximate.")+ return "\n".join(out) + "\n"+++def metrics_row(ticker, result):+ rows = result["rows"]+ cur = rows[0] if rows else {}+ t = result["ttm"]+ return {"ticker": ticker, "name": result["entity"], "cik": result["cik"],+ "period_end": cur.get("end"), "revenue_ttm": t.get("revenue"),+ "net_income_ttm": t.get("net_income"), "eps_ttm": t.get("eps_diluted"),+ "revenue_growth_yoy": cur.get("revenue_yoy"), "eps_growth_yoy": cur.get("eps_yoy"),+ "net_income_growth_yoy": cur.get("net_income_yoy"),+ "gross_margin": cur.get("gross_margin"), "operating_margin": cur.get("operating_margin"),+ "net_margin": cur.get("net_margin"), "source": "SEC XBRL company facts"}+++def clean_title(title):+ return re.sub(r"\s*/[A-Z]{2,5}/?\s*$", "", title or "").strip() or None+++def ticker_ciks(fetcher):+ """ticker -> (10-digit CIK, company name) from company_tickers.json."""+ data = fetcher.json(TICKERS_URL, "company_tickers.json")+ out = {}+ for v in data.values():+ out.setdefault(v["ticker"].upper().replace("-", "."),+ (str(v["cik_str"]).zfill(10), clean_title(v.get("title"))))+ return out+++def main(argv=None):+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])+ ap.add_argument("tickers", nargs="*", help="tickers, e.g. AAPL KO")+ ap.add_argument("--cik", help="use this CIK instead of a ticker lookup (one company)")+ ap.add_argument("--quarters", type=int, default=6)+ ap.add_argument("--no-filings", action="store_true", help="skip the 8-K and 10-Q links")+ ap.add_argument("--metrics", metavar="FILE", help="merge a row per ticker into this JSON")+ ap.add_argument("--user-agent")+ ap.add_argument("--config", default="trader/config.json")+ ap.add_argument("--offline", metavar="DIR")+ ap.add_argument("--json", action="store_true")+ args = ap.parse_args(argv)+ if not args.tickers and not args.cik:+ ap.print_help()+ return 2+ ua = user_agent(args.user_agent, args.config)+ if not ua and not args.offline:+ print("facts: " + UA_HELP, file=sys.stderr)+ return 2+ fetcher = Fetcher(ua, offline=args.offline)+ results, rows, failed = [], [], 0+ try:+ ciks = {} if args.cik else ticker_ciks(fetcher)+ except FactsError as exc:+ print("facts: %s" % exc, file=sys.stderr)+ return 2+ wanted = args.tickers or [args.cik]+ for t in wanted:+ tick = t.upper()+ if args.cik:+ cik, name = str(args.cik).zfill(10), None+ else:+ cik, name = ciks.get(tick.replace("-", "."), (None, None))+ if not cik:+ print("facts: no SEC CIK for %s (is it a US filer? ETFs and foreign filers "+ "may not have XBRL facts)" % tick, file=sys.stderr)+ failed += 1+ continue+ try:+ cf = fetcher.json(FACTS_URL % cik, "companyfacts-CIK%s.json" % cik)+ result = analyse(cf, quarters=args.quarters, name=name)+ filings = None+ if not args.no_filings:+ sub = fetcher.json(SUBMISSIONS_URL % cik, "submissions-CIK%s.json" % cik)+ filings = latest_filings(sub, cik, fetcher)+ except FactsError as exc:+ print("facts: %s: %s" % (tick, exc), file=sys.stderr)+ failed += 1+ continue+ results.append({"ticker": tick, "result": result, "filings": filings,+ "changes": changes(result), "note": stale_note(result, filings)})+ rows.append(metrics_row(tick, result))+ if not args.json:+ sys.stdout.write(render(tick, result, filings))+ sys.stdout.write("\n")+ if args.json:+ print(json.dumps(results, indent=2))+ if args.metrics and rows:+ existing = {}+ if os.path.isfile(args.metrics):+ with open(args.metrics, encoding="utf-8") as fh:+ existing = {r["ticker"]: r for r in json.load(fh).get("companies", [])}+ for r in rows:+ existing[r["ticker"]] = r+ folder = os.path.dirname(args.metrics)+ if folder:+ os.makedirs(folder, exist_ok=True)+ with open(args.metrics, "w", encoding="utf-8") as fh:+ json.dump({"as_of": _dt.date.today().isoformat(),+ "companies": sorted(existing.values(), key=lambda r: r["ticker"])},+ fh, indent=2)+ fh.write("\n")+ if not args.json:+ print("wrote %s (%d companies)" % (args.metrics, len(existing)))+ return 0 if results and not failed else (1 if results else 2)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/trader-analyst/metrics.example.json b/trader-analyst/metrics.example.jsonnew file mode 100644index 0000000..524eb84--- /dev/null+++ b/trader-analyst/metrics.example.json@@ -0,0 +1,85 @@+{+ "as_of": "2026-10-13",+ "companies": [+ {+ "ticker": "AAPL",+ "name": "Apple Inc.",+ "cik": "0000320193",+ "period_end": "2026-06-27",+ "revenue_ttm": 466823000000,+ "net_income_ttm": 128930000000,+ "eps_ttm": 8.71,+ "revenue_growth_yoy": 16.4,+ "eps_growth_yoy": 28.7,+ "net_income_growth_yoy": 27.1,+ "gross_margin": 50.1,+ "operating_margin": 32.6,+ "net_margin": 27.2,+ "source": "SEC XBRL company facts"+ },+ {+ "ticker": "AXP",+ "name": "AMERICAN EXPRESS CO",+ "cik": "0000004962",+ "period_end": "2026-06-30",+ "revenue_ttm": 43086000000,+ "net_income_ttm": 11445000000,+ "eps_ttm": 16.47,+ "revenue_growth_yoy": 8.6,+ "eps_growth_yoy": 11.0,+ "net_income_growth_yoy": 7.8,+ "gross_margin": null,+ "operating_margin": null,+ "net_margin": 27.7,+ "source": "SEC XBRL company facts"+ },+ {+ "ticker": "BAC",+ "name": "BANK OF AMERICA CORP",+ "cik": "0000070858",+ "period_end": "2026-06-30",+ "revenue_ttm": 119237000000,+ "net_income_ttm": 33637000000,+ "eps_ttm": 4.34,+ "revenue_growth_yoy": 15.0,+ "eps_growth_yoy": 34.4,+ "net_income_growth_yoy": 26.6,+ "gross_margin": null,+ "operating_margin": null,+ "net_margin": 28.8,+ "source": "SEC XBRL company facts"+ },+ {+ "ticker": "GOOGL",+ "name": "Alphabet Inc.",+ "cik": "0001652044",+ "period_end": "2026-06-30",+ "revenue_ttm": 445866000000,+ "net_income_ttm": 244205000000,+ "eps_ttm": 19.91,+ "revenue_growth_yoy": 24.2,+ "eps_growth_yoy": 294.4,+ "net_income_growth_yoy": 297.9,+ "gross_margin": 61.6,+ "operating_margin": 34.0,+ "net_margin": 93.7,+ "source": "SEC XBRL company facts"+ },+ {+ "ticker": "KO",+ "name": "COCA COLA CO",+ "cik": "0000021344",+ "period_end": "2026-04-03",+ "revenue_ttm": 49284000000,+ "net_income_ttm": 13701000000,+ "eps_ttm": 3.18,+ "revenue_growth_yoy": 12.1,+ "eps_growth_yoy": 18.2,+ "net_income_growth_yoy": 17.8,+ "gross_margin": 63.0,+ "operating_margin": 35.0,+ "net_margin": 31.5,+ "source": "SEC XBRL company facts"+ }+ ]+}diff --git a/trader-broker/SKILL.md b/trader-broker/SKILL.mdnew file mode 100644index 0000000..da8522a--- /dev/null+++ b/trader-broker/SKILL.md@@ -0,0 +1,212 @@+---+name: trader-broker+description: >-+ Order Executor. Sends approved orders to your broker, paper trading by+ default, never without your yes. Shows each order as a plain ticket (a+ bracket shows its stop-loss, take-profit and the max loss at the stop)+ plus the exact JSON for Alpaca's place_stock_order, records your yes word+ for word, then Claude's own Allow once / Deny card asks again. Builds the+ sell ticket that closes a day trade by your flat-by time, records fills,+ and logs each trade's max loss so trader-risk can hold the daily limit.+ Covers setting up Alpaca's official MCP server in Claude Desktop (paper by+ default, keys in env vars, never in chat), the Interactive Brokers+ connector, and setting order tools to "Needs approval". Use when the user+ says "place the order", "buy it", "execute", "send it to my broker",+ "close my position", "flatten", "get me out", "connect Alpaca", "set up+ paper trading", or after /trader-risk passes.+argument-hint: "[order number]"+---++# trader-broker++The Order Executor is the only skill in this pack that can lead to a real+order, so it is the strictest. An order reaches the market only after three+separate gates, every time, for every order:++1. **trader-risk passed this exact order today** (matched by fingerprint).+2. **The user typed an explicit yes for this one order** in the chat.+3. **The user clicked Allow once** on Claude's own permission card, which+ appears because the order tool is set to "Needs approval".++Two yeses from the user, one PASS from the rules. No yes, no order.++`${CLAUDE_SKILL_DIR}` below is this skill's folder (where this SKILL.md lives).++```bash+python3 "${CLAUDE_SKILL_DIR}/ticket.py" show # every ticket, READY or not+python3 "${CLAUDE_SKILL_DIR}/ticket.py" approve --index 1 --reply "yes"+python3 "${CLAUDE_SKILL_DIR}/ticket.py" result --index 1 --status placed --broker-id ID --filled-qty 8 --filled-price 364.20+python3 "${CLAUDE_SKILL_DIR}/ticket.py" fill --symbol TSLA --side sell --qty 8 --price 370.04+python3 "${CLAUDE_SKILL_DIR}/ticket.py" flatten --symbol TSLA --qty 8+python3 "${CLAUDE_SKILL_DIR}/ticket.py" log+```++`ticket.py` never talks to a broker. It renders tickets, checks that a reply+is a real yes for that order, builds the flatten ticket, and keeps the log in+`trader/state/broker.json`. `--now "2026-10-19 10:15"` pins the clock (New York time).++## What it reads and writes++| file | what |+| --- | --- |+| `trader/orders.json` | the proposed orders (trader-budget writes it; `flatten` replaces it) |+| `trader/state/risk.json` | trader-risk's verdicts; only a PASS from today is READY |+| `trader/state/broker.json` | every yes, no, placed, failed and filled, with each entry's max loss |+| `trader/portfolio.json` | cash and shares, updated by `fill` and by `result --filled-qty` |+| `trader/plan.json` | the flat-by time for `flatten` |++## Setup A: Alpaca (official MCP server, Claude Desktop)++Alpaca's own server is github.com/alpacahq/alpaca-mcp-server (MIT). It runs on+the user's computer inside Claude Desktop. It is not in Claude's connector+directory. It trades on a **paper** account unless told otherwise. Checked+against its source on 2026-10-20 (version 2.4.0).++1. The user makes an Alpaca account and creates **paper trading** API keys in+ the Alpaca dashboard. Paper keys are separate from live keys.+2. The user installs `uv` (it provides `uvx`), from docs.astral.sh/uv.+3. In Claude Desktop: Settings > Developer > Edit Config. That opens+ `claude_desktop_config.json` (macOS: `~/Library/Application Support/Claude/`,+ Windows: `%APPDATA%\Claude\`). The user adds this block (also in+ `claude_desktop_config.example.json` here) and types their own keys into the file:++```json+{+ "mcpServers": {+ "alpaca": {+ "command": "uvx",+ "args": ["alpaca-mcp-server"],+ "env": {+ "ALPACA_API_KEY": "paste your paper key here, in this file only",+ "ALPACA_SECRET_KEY": "paste your paper secret here, in this file only",+ "ALPACA_PAPER_TRADE": "true",+ "ALPACA_TOOLSETS": "account,trading,stock-data"+ }+ }+ }+}+```++ The `env` block hands the keys to the server as environment variables.+ **Keys never go in the chat.** Never ask for them, never read this file+ back into the conversation, and if the user pastes a key anyway, tell them+ to delete that message and make new keys in the Alpaca dashboard.+ `ALPACA_PAPER_TRADE` is already true by default; writing it makes it+ visible. `ALPACA_TOOLSETS` is optional and hides the tools they do not need.+4. Restart Claude Desktop.+5. **Set the tool permissions.** Customize > Connectors (Settings > Connectors+ in older versions), open alpaca, and for each tool pick Always allow, Needs+ approval or Blocked:+ - `place_stock_order`: **Needs approval**. Never Always allow.+ - every other tool that places, changes, cancels or closes anything+ (`cancel_order_by_id`, `replace_order_by_id`, `close_position`,+ `update_account_config`): Needs approval.+ - `place_option_order`, `place_crypto_order`, `close_all_positions`,+ `cancel_all_orders`, `exercise_options_position`,+ `do_not_exercise_options_position`: **Blocked** unless the user has a+ reason and says so.+ - read-only tools (`get_account_info`, `get_all_positions`, `get_open_position`,+ `get_orders`, `get_clock`, `get_stock_snapshot`, `get_stock_latest_quote`):+ Always allow is fine.+6. Check it: ask Claude for the Alpaca account info (read only) and confirm+ in the Alpaca dashboard that it is the paper account.++In Claude Code instead of Claude Desktop, keep the order tool on ask in+`.claude/settings.json`: `"permissions": {"ask": ["mcp__alpaca__place_stock_order"]}`,+and never put an order tool in `allow`.++**Bracket orders on Alpaca.** `place_stock_order` takes+`take_profit_limit_price` and `stop_loss_stop_price` (and an optional+`stop_loss_limit_price`). When either is there, the server sets+`order_class` to "bracket" by itself; trader-budget writes it anyway so the+ticket shows it. A bracket is whole shares only, with `time_in_force` day or+gtc. After the entry fills, the stop-loss and the take-profit wait at the+broker as two orders that cancel each other. They are day orders too, so they+end at the close: one more reason to be flat by then.++## Setup B: Interactive Brokers (connector in Claude's directory)++Interactive Brokers publishes a verified connector: claude.ai/directory/interactive-brokers+(connector URL `https://api.ibkr.com/v1/api/mcp`). Add it from Customize >+Connectors > Browse connectors and sign in to IBKR there, not in the chat.+Its listing says Claude can draft trade instructions that are sent to the+user's IBKR account for their review and approval, and that Claude never+submits orders directly to the market. So with IBKR the final yes happens in+IBKR as well. Set `"broker": "ibkr"` in `trader/config.json`. Set its tools+that draft orders to Needs approval too.++## Steps: the entry++1. `ticket.py show`. Only READY tickets go to the user. A ticket that is NOT+ READY or BLOCKED goes back to `/trader-risk`.+2. Show ONE ticket and ask: "Place this order? Reply yes or no." One order+ per question. Never offer "yes to all".+3. Run `ticket.py approve --index N --reply "<the user's reply, word for word>"`.+ If it prints "Not recorded", the reply was not an explicit yes for this+ order (for example "sure", "yes to all", or a yes that names a different+ stock or amount). Ask again. Never turn a reply into a yes yourself.+4. Only after "Recorded your yes", call `place_stock_order` with exactly the+ JSON the ticket printed. Claude's card appears: Allow once or Deny.+5. Record what happened: `ticket.py result --index N --status placed+ --broker-id <id> --filled-qty Q --filled-price P` (the fill from the+ response or `get_open_position`), or `--status denied`, or `--status failed`+ with `--note`. A failed order is not retried without a new check and a new yes.+ The log keeps the entry's max loss for trader-risk's daily limit.++## Steps: while it is open, and out by the close++- trader-alerts watches the stop, the target and the flat-by time+ (`alerts.py add --from-plan`). The bracket's own orders do the stopping.+- When the stop-loss or the take-profit fills, record it:+ `ticket.py fill --symbol TSLA --side sell --qty 8 --price 358.32`.+- By `flat_by` (15:55 New York), anything still open gets closed:+ 1. Ask Alpaca how many shares are held: `get_open_position` (read only).+ 2. `ticket.py flatten --symbol TSLA --qty 8` writes a market sell for those+ shares to `trader/orders.json`.+ 3. `/trader-risk`. A sell that only closes what the user holds is never+ blocked by the daily limits or the entry window.+ 4. `ticket.py show`, then the user's yes for that one order, as above.+ 5. The bracket's stop-loss and take-profit still hold those shares, so+ Alpaca rejects a new sell until they are canceled: `get_orders` (status+ open, nested true) shows them; `cancel_order_by_id` each one (Needs+ approval). Then `place_stock_order` with the ticket, then `result`.++## Example: the reel++```+ORDER 1 of 1, PAPER account, Alpaca+ BUY 8 TSLA, market, good for today+ stop-loss 358.32+ take-profit 370.04+ max loss about $46.88 if the stop fills at 358.32 (it can fill worse in a fast market)+ why: opening-range breakout on TSLA: 8 shares, bound by your $50 max loss per trade (8 x 5.86 = $46.88 at the stop)+ READY: trader-risk PASS, waiting for your yes+ Claude will call place_stock_order with exactly:+ {"symbol": "TSLA", "side": "buy", "qty": "8", "type": "market", "time_in_force": "day",+ "order_class": "bracket", "take_profit_limit_price": "370.04", "stop_loss_stop_price": "358.32"}+```++The user replies "yes". Claude records it, calls `place_stock_order`, and the+card reads "Claude wants to use Place stock order" with that JSON and two+buttons: Allow once, Deny. Allow once sends it to the paper account. The+`why` and the plan stay in the file; they are never sent.++## What it never does++- Never places an order without all three gates, and never two orders on one yes.+- Never places orders from a scheduled or background task: nobody is there to say yes.+- Never asks for, reads, stores or repeats API keys or passwords.+- Never switches `ALPACA_PAPER_TRADE` or `"paper"` to live. The user does that themselves.+- Never calls `close_all_positions`, `cancel_all_orders`, option or crypto order tools on its own.+- Never promises a fill price: a market order and a stop fill at whatever the market gives.++## Safety++- Education and tooling, not financial advice. A PASS is a rules check, not a recommendation.+- Paper trading by default (`"paper": true`). Going live is the user's own decision, in their own config.+- Nothing in this pack places an order except trader-broker, and only when all three hold: trader-risk+ passed that exact order today, the user typed an explicit yes for that one order in the chat, and the+ user clicked Allow once on Claude's own card because the order tool is set to "Needs approval"+ (Customize > Connectors > tool permissions). Never set an order tool to "Always allow".+- No options, margin, short selling or leverage unless the config allows it and the user confirms.+- Broker keys live in environment variables or the Claude Desktop config, never in the chat.diff --git a/trader-broker/claude_desktop_config.example.json b/trader-broker/claude_desktop_config.example.jsonnew file mode 100644index 0000000..b663c85--- /dev/null+++ b/trader-broker/claude_desktop_config.example.json@@ -0,0 +1,14 @@+{+ "mcpServers": {+ "alpaca": {+ "command": "uvx",+ "args": ["alpaca-mcp-server"],+ "env": {+ "ALPACA_API_KEY": "YOUR_PAPER_API_KEY_TYPED_HERE_NEVER_IN_CHAT",+ "ALPACA_SECRET_KEY": "YOUR_PAPER_SECRET_KEY_TYPED_HERE_NEVER_IN_CHAT",+ "ALPACA_PAPER_TRADE": "true",+ "ALPACA_TOOLSETS": "account,trading,stock-data"+ }+ }+ }+}diff --git a/trader-broker/ticket.py b/trader-broker/ticket.pynew file mode 100644index 0000000..721aa2b--- /dev/null+++ b/trader-broker/ticket.py@@ -0,0 +1,720 @@+#!/usr/bin/env python3+"""Order tickets and the decision log for trader-broker. Standard library only.++This tool never talks to a broker and never places anything. It does its+work around the one moment that matters, your yes:++ show renders each proposed order as a plain-English ticket plus the+ exact JSON Claude will send to Alpaca's place_stock_order tool.+ A bracket order shows its stop-loss, take-profit and the max loss+ at the stop. An order is READY only if trader-risk passed THIS+ exact order today (matched by fingerprint) and nobody has decided+ on it yet.+ approve records your explicit yes for ONE order, with your reply word for+ word. It refuses "yes to all", "sure", "ok", a yes that names a+ different stock or amount, and any order that is not READY.+ decline records a no.+ result records what happened after the Allow once / Deny card:+ placed (with the broker's order id), denied, or failed.+ fill records a fill in trader/portfolio.json (cash and shares).+ flatten builds a sell ticket that closes a symbol's open position by+ flat_by. It still goes through trader-risk and your yes.+ log prints today's decisions.++ python3 ticket.py show # every order, READY or not+ python3 ticket.py show --index 1 --json # one ticket as JSON+ python3 ticket.py approve --index 1 --reply "yes"+ python3 ticket.py result --index 1 --status placed --broker-id 61e6...+ python3 ticket.py fill --symbol TSLA --side buy --qty 8 --price 364.20+ python3 ticket.py flatten --symbol TSLA --qty 8+ python3 ticket.py log++Everything is written to trader/state/broker.json (append only). Dates are+New York dates; --now "2026-10-19 10:15" pins the clock.+"""++import argparse+import datetime+import hashlib+import json+import os+import re+import sys++ALPACA_FIELDS = ("symbol", "side", "qty", "notional", "type", "time_in_force", "limit_price",+ "stop_price", "trail_price", "trail_percent", "extended_hours", "client_order_id",+ "order_class", "take_profit_limit_price", "stop_loss_stop_price",+ "stop_loss_limit_price", "advanced_instructions")+STRING_FIELDS = ("qty", "notional", "limit_price", "stop_price", "trail_price", "trail_percent",+ "take_profit_limit_price", "stop_loss_stop_price", "stop_loss_limit_price")+TIF_WORDS = {"day": "good for today", "gtc": "good until canceled", "opg": "at the open",+ "cls": "at the close", "ioc": "immediate or cancel", "fok": "fill or kill"}+YES_WORDS = ("yes", "y")+BATCH_WORDS = {"all", "every", "everything", "rest", "remaining", "them", "both", "batch", "each"}+DOUBT_WORDS = {"no", "not", "dont", "don't", "wait", "cancel", "stop", "but", "maybe", "later",+ "hold", "unless", "if"}+++class TicketError(Exception):+ pass+++# ---------------------------------------------------------------- time (New York, no tz files)++def _nth_sunday(year, month, n):+ d = datetime.date(year, month, 1)+ d += datetime.timedelta(days=(6 - d.weekday()) % 7)+ return d + datetime.timedelta(weeks=n - 1)+++def eastern_offset(utc):+ """Hours from UTC for New York: -4 in daylight time, -5 otherwise.+ DST runs from 2:00 a.m. on the second Sunday of March to 2:00 a.m. on the+ first Sunday of November (US rule since 2007)."""+ y = utc.year+ start = datetime.datetime.combine(_nth_sunday(y, 3, 2), datetime.time(7, 0)) # 2:00 EST+ end = datetime.datetime.combine(_nth_sunday(y, 11, 1), datetime.time(6, 0)) # 2:00 EDT+ naive = utc.replace(tzinfo=None)+ return -4 if start <= naive < end else -5+++def to_eastern(utc):+ return utc.replace(tzinfo=None) + datetime.timedelta(hours=eastern_offset(utc))+++def eastern_to_utc(local):+ for off in (-4, -5):+ utc = local - datetime.timedelta(hours=off)+ if eastern_offset(utc) == off:+ return utc+ return local + datetime.timedelta(hours=5)+++def parse_now(text):+ """ISO time -> naive UTC. A time without an offset is taken as New York time."""+ if not text:+ return datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0, tzinfo=None)+ t = text.strip().replace("Z", "+00:00")+ try:+ dt = datetime.datetime.fromisoformat(t)+ except ValueError:+ raise TicketError("--now wants a time like \"2026-10-19 10:15\" (New York) or ...Z (UTC)")+ if dt.tzinfo is None:+ return eastern_to_utc(dt)+ return (dt - dt.utcoffset()).replace(tzinfo=None)+++def ny_iso(now_utc):+ """naive UTC -> "2026-10-19T10:15:00-04:00" (New York wall clock with its offset)."""+ off = eastern_offset(now_utc)+ return "%s%+03d:00" % (to_eastern(now_utc).replace(microsecond=0).isoformat(), off)+++# ---------------------------------------------------------------- files++def read_json(path, what, required=True):+ if not path or not os.path.exists(path):+ if required:+ raise TicketError("no %s at %s" % (what, path))+ return None+ try:+ with open(path, encoding="utf-8") as fh:+ return json.load(fh)+ except json.JSONDecodeError as e:+ raise TicketError("%s is not valid JSON: %s" % (path, e))+++def write_json(path, data):+ d = os.path.dirname(path)+ if d:+ os.makedirs(d, exist_ok=True)+ tmp = path + ".tmp"+ with open(tmp, "w", encoding="utf-8") as fh:+ json.dump(data, fh, indent=2)+ fh.write("\n")+ os.replace(tmp, path)+++def rec_day(rec):+ """The trading day a decision belongs to: its "date" (the day it was made under), else the day of "at"."""+ return str(rec.get("date") or str(rec.get("at", ""))[:10])+++# ---------------------------------------------------------------- the order++def fingerprint(order):+ """Same function as trader-risk/check.py: identifies the exact order."""+ core = {k: order[k] for k in ALPACA_FIELDS if k in order and order[k] is not None}+ blob = json.dumps(core, sort_keys=True, separators=(",", ":"))+ return hashlib.sha256(blob.encode("utf-8")).hexdigest()[:16]+++def _str_num(v):+ if isinstance(v, bool):+ return v+ if isinstance(v, (int, float)):+ f = float(v)+ return str(int(f)) if f == int(f) else repr(f)+ return str(v)+++def _f(x):+ try:+ return float(x)+ except (TypeError, ValueError):+ return None+++def tool_input(order):+ """The exact arguments for place_stock_order: Alpaca's parameter names,+ numbers as strings (its signature types qty, notional and prices as str).+ "why" and "plan" are ours and are never sent."""+ out = {}+ for k in ALPACA_FIELDS:+ if k in order and order[k] is not None:+ out[k] = _str_num(order[k]) if k in STRING_FIELDS else order[k]+ return out+++def _money(v):+ f = float(v)+ s = "{:,.2f}".format(f)+ return "$" + (s[:-3] if s.endswith(".00") else s)+++def _p(v):+ return "%.2f" % float(v)+++def is_bracket(order):+ oc = str(order.get("order_class") or "").lower()+ legs = order.get("take_profit_limit_price") is not None or order.get("stop_loss_stop_price") is not None+ return oc == "bracket" or (not oc and legs)+++def max_loss(order):+ """(dollars, stop) lost if the stop fills exactly at the stop, or (None, stop)."""+ stop = _f(order.get("stop_loss_stop_price")) or _f((order.get("plan") or {}).get("stop"))+ q = _f(order.get("qty"))+ if not stop or not q:+ return None, stop+ plan = order.get("plan") or {}+ if str(order.get("type", "market")) == "limit" and _f(order.get("limit_price")):+ entry = _f(order["limit_price"])+ elif _f(plan.get("max_loss")) is not None:+ return round(_f(plan["max_loss"]), 2), stop+ else:+ entry = _f(plan.get("entry"))+ if not entry:+ return None, stop+ risk = abs(entry - stop)+ return round(q * int(round(risk * 100)) / 100.0, 2), stop+++def plain_parts(order):+ """The ticket in plain words, one part per line."""+ side = str(order.get("side", "")).upper()+ sym = order.get("symbol", "?")+ typ = str(order.get("type", "market"))+ tif = TIF_WORDS.get(str(order.get("time_in_force", "day")), order.get("time_in_force"))+ if is_bracket(order):+ how = "limit %s" % _p(order["limit_price"]) if typ == "limit" and order.get("limit_price") else typ+ parts = ["%s %s %s, %s, %s" % (side, _str_num(order.get("qty")), sym, how, tif)]+ if order.get("stop_loss_stop_price") is not None:+ leg = "stop-loss %s" % _p(order["stop_loss_stop_price"])+ if order.get("stop_loss_limit_price") is not None:+ leg += " (limit %s)" % _p(order["stop_loss_limit_price"])+ parts.append(leg)+ if order.get("take_profit_limit_price") is not None:+ parts.append("take-profit %s" % _p(order["take_profit_limit_price"]))+ loss, stop = max_loss(order)+ if loss is not None:+ parts.append("max loss about %s if the stop fills at %s (it can fill worse in a fast market)"+ % (_money(loss), _p(stop)))+ return parts+ if order.get("notional") is not None:+ what = "%s of %s" % (_money(order["notional"]), sym)+ else:+ q = _str_num(order.get("qty"))+ what = "%s share%s of %s" % (q, "" if q == "1" else "s", sym)+ if typ == "limit":+ how = "limit order at %s" % _money(order.get("limit_price"))+ elif typ == "stop":+ how = "stop order at %s" % _money(order.get("stop_price"))+ elif typ == "stop_limit":+ how = "stop %s, limit %s" % (_money(order.get("stop_price")), _money(order.get("limit_price")))+ else:+ how = "%s order" % typ.replace("_", " ")+ return ["%s %s, %s, %s" % (side, what, how, tif)]+++def plain(order):+ """BUY $1,250 of AAPL, market order, good for today+ BUY 8 TSLA, market, good for today / stop-loss 358.32 / take-profit 370.04 / max loss about $46.88 ..."""+ return " / ".join(plain_parts(order))+++def amount_numbers(order):+ nums = []+ for k in ("notional", "qty", "limit_price", "stop_loss_stop_price", "take_profit_limit_price",+ "stop_loss_limit_price"):+ if order.get(k) is not None:+ v = _f(order[k])+ if v is not None:+ nums.append(v)+ loss, _ = max_loss(order)+ if loss is not None:+ nums.append(loss)+ return nums+++def parse_yes(reply, order, batch_symbols=()):+ """Is this reply an explicit yes for THIS one order? Returns (ok, why)."""+ raw = (reply or "").strip()+ if not raw:+ return False, "the reply is empty"+ if "?" in raw:+ return False, "the reply is a question, not a yes"+ words = re.findall(r"[a-z']+", raw.lower())+ if not words or words[0] not in YES_WORDS:+ return False, "only a reply that starts with \"yes\" counts (not ok, sure, go, do it)"+ if BATCH_WORDS & set(words):+ return False, "a yes covers one order at a time, not a batch"+ if DOUBT_WORDS & set(words[1:]):+ return False, "the reply has a condition or a doubt in it; ask again"+ sym = str(order.get("symbol", "")).upper()+ tokens = set(re.findall(r"[A-Z][A-Z.\-]{0,6}", raw.upper()))+ others = {s.upper() for s in batch_symbols} - {sym}+ named = tokens & others+ if named:+ return False, "the reply names %s, but this order is for %s" % (", ".join(sorted(named)), sym)+ nums = [float(n.replace(",", "")) for n in re.findall(r"\d[\d,]*(?:\.\d+)?", raw)]+ if nums:+ want = amount_numbers(order)+ if not any(abs(n - w) < 0.005 for n in nums for w in want):+ return False, "the reply says %s, but this order is %s" % (+ ", ".join(_str_num(n) for n in nums), plain(order))+ return True, "explicit yes for %s" % plain(order)+++# ---------------------------------------------------------------- state++def load_state(path):+ return read_json(path, "broker state", required=False) or {"orders": []}+++def latest(state, fp, today):+ """The latest decision recorded today for this fingerprint, or None."""+ found = None+ for rec in state.get("orders", []):+ if rec.get("fingerprint") == fp and rec_day(rec) == today:+ found = rec+ return found+++def risk_verdict(risk, fp, today):+ if not risk:+ return None, "trader-risk has not checked these orders (run check.py)"+ if risk.get("date") != today:+ return None, "the risk check is from %s, not today; run check.py again" % risk.get("date")+ for r in risk.get("results", []):+ if r.get("fingerprint") == fp:+ return r, None+ return None, "this exact order was not in the last risk check (it changed or is new); run check.py again"+++def status_of(order, risk, state, today):+ """(ready, label, risk_result)"""+ fp = fingerprint(order)+ rv, why = risk_verdict(risk, fp, today)+ if rv is None:+ return False, "NOT READY: " + why, None+ if rv.get("verdict") != "PASS":+ return False, "BLOCKED by trader-risk: " + "; ".join(rv.get("reasons", [])), rv+ rec = latest(state, fp, today)+ if rec:+ st = rec.get("status")+ if st == "approved":+ return False, "APPROVED by you at %s, waiting for the place_stock_order call" % rec.get("at"), rv+ return False, "DONE: %s at %s" % (st, rec.get("at")), rv+ return True, "READY: trader-risk PASS, waiting for your yes", rv+++def kind_of(order, rv):+ """entry or exit, as trader-risk saw it (older checks: a buy is an entry)."""+ if rv and rv.get("kind"):+ return rv["kind"]+ return "entry" if str(order.get("side", "")).lower() == "buy" else "exit"+++# ---------------------------------------------------------------- rendering++def render(order, idx, total, cfg, risk, state, today):+ ready, label, rv = status_of(order, risk, state, today)+ broker = str(cfg.get("broker", "alpaca")).lower()+ paper = cfg.get("paper", True)+ acct = "PAPER account" if paper else "LIVE ACCOUNT, REAL MONEY"+ lines = ["ORDER %d of %d, %s, %s" % (idx, total, acct, "Interactive Brokers" if broker == "ibkr" else "Alpaca")]+ for part in plain_parts(order):+ lines.append(" " + part)+ if order.get("why"):+ lines.append(" why: " + order["why"])+ lines.append(" " + label)+ for w in (rv or {}).get("warnings", []):+ lines.append(" note: " + w)+ if broker == "ibkr":+ lines.append(" Claude drafts this with the Interactive Brokers connector. IBKR sends it to your")+ lines.append(" IBKR account, and it only goes to the market after you approve it there.")+ else:+ lines.append(" Claude will call place_stock_order with exactly:")+ for l in json.dumps(tool_input(order), indent=2).splitlines():+ lines.append(" " + l)+ if is_bracket(order):+ lines.append(" Alpaca places the entry, then the stop-loss and the take-profit as two orders")+ lines.append(" that cancel each other: when one fills, the other is canceled.")+ if ready:+ lines.append(" Reply \"yes\" to place this one order, or \"no\" to skip it.")+ if broker != "ibkr":+ lines.append(" Claude's own card then asks again: Allow once places it, Deny stops it.")+ return "\n".join(lines), ready+++def ticket_json(order, idx, cfg, risk, state, today):+ ready, label, rv = status_of(order, risk, state, today)+ loss, stop = max_loss(order)+ return {"index": idx, "ready": ready, "status": label, "plain": plain(order),+ "fingerprint": fingerprint(order), "paper": bool(cfg.get("paper", True)),+ "broker": cfg.get("broker", "alpaca"), "tool": "place_stock_order",+ "tool_input": tool_input(order), "why": order.get("why", ""),+ "bracket": is_bracket(order), "max_loss": loss, "stop": stop}+++# ---------------------------------------------------------------- fills -> portfolio++def apply_fill(portfolio_path, cfg, symbol, side, qty, price, date):+ """Record a filled order in trader/portfolio.json: cash and shares, with a+ cost-basis lot per buy (oldest lots are relieved first on a sell)."""+ pf = read_json(portfolio_path, "portfolio", required=False)+ if pf is None:+ budget = cfg.get("budget")+ if not budget:+ raise TicketError("no %s yet and no budget in the config to start it from" % portfolio_path)+ pf = {"cash": float(budget), "positions": []}+ symbol = symbol.upper()+ qty, price = float(qty), float(price)+ if qty <= 0 or price <= 0:+ raise TicketError("a fill needs a positive qty and price")+ cost = round(qty * price, 2)+ pos = None+ for p in pf.setdefault("positions", []):+ if str(p.get("ticker", "")).upper() == symbol:+ pos = p+ if side == "buy":+ if pos is None:+ pos = {"ticker": symbol, "shares": 0.0, "lots": []}+ pf["positions"].append(pos)+ lots = pos.setdefault("lots", [])+ lots.append({"id": "%s-%d" % (symbol, len(lots) + 1), "date": date, "shares": qty, "cost": cost})+ pos["shares"] = round(float(pos.get("shares", 0)) + qty, 6)+ pf["cash"] = round(float(pf.get("cash", 0)) - cost, 2)+ else:+ if pos is None or float(pos.get("shares", 0)) + 1e-9 < qty:+ raise TicketError("cannot record selling %s %s: the portfolio holds %s"+ % (_str_num(qty), symbol, pos.get("shares", 0) if pos else 0))+ left = qty+ for lot in sorted(pos.get("lots", []), key=lambda l: l.get("date", "")):+ if left <= 1e-9:+ break+ take = min(left, float(lot["shares"]))+ per = float(lot["cost"]) / float(lot["shares"]) if float(lot["shares"]) else 0+ lot["cost"] = round(float(lot["cost"]) - per * take, 2)+ lot["shares"] = round(float(lot["shares"]) - take, 6)+ left -= take+ pos["lots"] = [l for l in pos.get("lots", []) if float(l["shares"]) > 1e-9]+ pos["shares"] = round(float(pos["shares"]) - qty, 6)+ if pos["shares"] <= 1e-9:+ pf["positions"].remove(pos)+ pf["cash"] = round(float(pf.get("cash", 0)) + cost, 2)+ write_json(portfolio_path, pf)+ return pf+++def log_fill(state_path, now, today, symbol, side, qty, price):+ """A fill in the log, so trader-risk can count day trades (a buy and a sell the same day)."""+ state = load_state(state_path)+ state.setdefault("orders", []).append({+ "at": ny_iso(now), "date": today, "status": "filled", "symbol": symbol.upper(), "side": side,+ "qty": _str_num(float(qty)), "price": float(price),+ "plain": "%s %s %s at %s" % (side.upper(), _str_num(float(qty)), symbol.upper(), _p(price))})+ write_json(state_path, state)+++# ---------------------------------------------------------------- commands++def _clock(a):+ now = parse_now(getattr(a, "now", None))+ today = getattr(a, "today", None) or to_eastern(now).date().isoformat()+ if not re.match(r"^\d{4}-\d{2}-\d{2}$", today):+ raise TicketError("--today wants a date like 2026-10-19")+ return now, today+++def _load(a):+ doc = read_json(a.orders, "orders file (run trader-budget, or ticket.py flatten, first)")+ orders = doc.get("orders", doc) if isinstance(doc, dict) else doc+ if not isinstance(orders, list) or not orders:+ raise TicketError("no orders in %s" % a.orders)+ cfg = read_json(a.config, "config", required=False) or {}+ risk = read_json(a.risk, "risk check", required=False)+ state = load_state(a.state)+ now, today = _clock(a)+ return orders, cfg, risk, state, today, now+++def _pick(orders, index):+ if index is None:+ raise TicketError("say which order: --index N")+ if not 1 <= index <= len(orders):+ raise TicketError("there is no order %d (there are %d)" % (index, len(orders)))+ return orders[index - 1]+++def cmd_show(a):+ orders, cfg, risk, state, today, now = _load(a)+ picks = [(a.index, _pick(orders, a.index))] if a.index else list(enumerate(orders, 1))+ if a.json:+ out = [ticket_json(o, i, cfg, risk, state, today) for i, o in picks]+ print(json.dumps(out[0] if a.index else out, indent=2))+ return 0 if any(t["ready"] for t in out) else 1+ blocks, any_ready = [], False+ for i, o in picks:+ text, ready = render(o, i, len(orders), cfg, risk, state, today)+ blocks.append(text)+ any_ready = any_ready or ready+ print("\n\n".join(blocks))+ print("\nOne order at a time: a yes covers one ticket, never the batch. Education and tooling, "+ "not financial advice.")+ return 0 if any_ready else 1+++def cmd_approve(a):+ orders, cfg, risk, state, today, now = _load(a)+ order = _pick(orders, a.index)+ ready, label, rv = status_of(order, risk, state, today)+ if not ready:+ raise TicketError("order %d is not ready: %s" % (a.index, label))+ ok, why = parse_yes(a.reply, order, [o.get("symbol", "") for o in orders])+ if not ok:+ print("Not recorded: %s. Ask the user again with the ticket for order %d." % (why, a.index))+ return 1+ loss, stop = max_loss(order)+ rec = {"at": ny_iso(now), "date": today, "index": a.index, "fingerprint": fingerprint(order),+ "symbol": str(order.get("symbol", "")).upper(), "side": order.get("side"),+ "qty": order.get("qty"), "kind": kind_of(order, rv), "max_loss": loss, "stop": stop,+ "plain": plain(order), "status": "approved", "reply": a.reply,+ "paper": bool(cfg.get("paper", True)), "broker": cfg.get("broker", "alpaca")}+ state.setdefault("orders", []).append(rec)+ write_json(a.state, state)+ print("Recorded your yes for order %d: %s." % (a.index, plain(order)))+ if str(cfg.get("broker", "alpaca")).lower() == "ibkr":+ print("Now draft it with the Interactive Brokers connector; approve it in your IBKR account.")+ else:+ print("Now call place_stock_order with exactly:")+ print(json.dumps(tool_input(order), indent=2))+ print("Claude's card shows Allow once / Deny. Then: ticket.py result --index %d --status "+ "placed|denied|failed" % a.index)+ return 0+++def cmd_decline(a):+ orders, cfg, risk, state, today, now = _load(a)+ order = _pick(orders, a.index)+ rec = {"at": ny_iso(now), "date": today, "index": a.index, "fingerprint": fingerprint(order),+ "symbol": str(order.get("symbol", "")).upper(), "side": order.get("side"),+ "plain": plain(order), "status": "declined", "reply": a.reply or "no"}+ state.setdefault("orders", []).append(rec)+ write_json(a.state, state)+ print("Recorded: you said no to order %d (%s). Nothing was sent." % (a.index, plain(order)))+ return 0+++def cmd_result(a):+ orders, cfg, risk, state, today, now = _load(a)+ order = _pick(orders, a.index)+ fp = fingerprint(order)+ rec = latest(state, fp, today)+ if not rec or rec.get("status") != "approved":+ raise TicketError("order %d has no yes recorded today; a result can only follow an approval" % a.index)+ new = {"at": ny_iso(now), "date": today, "index": a.index, "fingerprint": fp, "symbol": rec["symbol"],+ "side": rec["side"], "plain": rec["plain"], "status": a.status}+ for k in ("qty", "kind", "max_loss", "stop"):+ if rec.get(k) is not None:+ new[k] = rec[k]+ if a.broker_id:+ new["broker_order_id"] = a.broker_id+ if a.note:+ new["note"] = a.note+ state["orders"].append(new)+ write_json(a.state, state)+ print("Recorded order %d as %s." % (a.index, a.status))+ if a.status == "placed" and a.filled_qty and a.filled_price:+ apply_fill(a.portfolio, cfg, rec["symbol"], rec["side"], a.filled_qty, a.filled_price, today)+ log_fill(a.state, now, today, rec["symbol"], rec["side"], a.filled_qty, a.filled_price)+ print("Added the fill to %s." % a.portfolio)+ elif a.status == "placed":+ print("When it fills, record it: ticket.py fill --symbol %s --side %s --qty Q --price P"+ % (rec["symbol"], rec["side"]))+ if rec.get("kind") == "entry" and is_bracket(order):+ print("When the stop-loss or the take-profit fills later, record that sell the same way.")+ return 0+++def cmd_fill(a):+ cfg = read_json(a.config, "config", required=False) or {}+ now = parse_now(a.now)+ date = a.date or to_eastern(now).date().isoformat()+ if not re.match(r"^\d{4}-\d{2}-\d{2}$", date):+ raise TicketError("--date wants a date like 2026-10-19")+ pf = apply_fill(a.portfolio, cfg, a.symbol, a.side, a.qty, a.price, date)+ log_fill(a.state, now, date, a.symbol, a.side, a.qty, a.price)+ print("Recorded %s %s %s at %s on %s in %s. Cash now %s." % (a.side, a.qty, a.symbol.upper(),+ _money(a.price), date, a.portfolio,+ _money(pf["cash"])))+ return 0+++def cmd_flatten(a):+ cfg = read_json(a.config, "config", required=False) or {}+ sym = a.symbol.strip().upper()+ now, today = _clock(a)+ source = "the broker, get_open_position"+ if a.qty is not None:+ qty = _f(a.qty)+ if qty is None or qty <= 0:+ raise TicketError("--qty wants the number of shares you hold, like --qty 8")+ else:+ pf = read_json(a.portfolio, "portfolio", required=False) or {}+ qty = sum(_f(p.get("shares", p.get("qty"))) or 0 for p in pf.get("positions", [])+ if str(p.get("ticker") or p.get("symbol") or "").upper() == sym)+ source = a.portfolio+ if qty <= 1e-9:+ raise TicketError("nothing to flatten: no %s shares in %s. Check the broker (get_open_position "+ "%s) and pass --qty if you do hold some" % (sym, a.portfolio, sym))+ plan = read_json(a.plan, "plan", required=False) or {}+ flat_by = (plan.get("flat_by") if str(plan.get("symbol", "")).upper() == sym else None) \+ or cfg.get("flat_by") or "15:55"+ order = {"symbol": sym, "side": "sell", "qty": _str_num(qty), "type": "market", "time_in_force": "day",+ "why": "flat by %s New York: closes the %s day trade before the close (qty from %s)"+ % (flat_by, sym, source)}+ old = read_json(a.orders, "orders", required=False)+ replaced = len(old.get("orders", [])) if isinstance(old, dict) else 0+ doc = {"created_by": "trader-broker", "created_at": now.strftime("%Y-%m-%dT%H:%M:%SZ"), "status": "proposed",+ "paper": bool(cfg.get("paper", True)),+ "note": "Flatten ticket. Nothing is placed until trader-risk passes it and you say yes in the chat.",+ "source": "ticket.py flatten %s on %s" % (sym, today), "orders": [order]}+ write_json(a.orders, doc)+ print("Flatten %s: %s (flat by %s New York)." % (sym, plain(order), flat_by))+ print("Wrote it to %s%s." % (a.orders, (" (it replaced %d earlier proposal%s)"+ % (replaced, "" if replaced == 1 else "s")) if replaced else ""))+ if a.qty is None:+ print("The qty comes from %s. Check it against get_open_position %s before you say yes." % (source, sym))+ print("Next:")+ print(" 1. trader-risk: check.py. A sell that only closes what you hold is never blocked by the daily")+ print(" limits or the entry window.")+ print(" 2. ticket.py show, then the user's yes for this one order.")+ print(" 3. If the bracket's stop-loss and take-profit are still open, Alpaca holds these shares for them")+ print(" and rejects a new sell. Cancel them first: get_orders (status open, nested true), then")+ print(" cancel_order_by_id for each open leg (Needs approval). Then place_stock_order with the ticket.")+ return 0+++def cmd_log(a):+ state = load_state(a.state)+ now, today = _clock(a)+ rows = [r for r in state.get("orders", []) if a.all or rec_day(r) == today]+ if not rows:+ print("No decisions recorded%s." % ("" if a.all else " today"))+ return 1+ for r in rows:+ extra = (" id " + r["broker_order_id"]) if r.get("broker_order_id") else ""+ reply = (' reply "%s"' % r["reply"]) if r.get("reply") and r["status"] in ("approved", "declined") else ""+ loss = (" max loss %s" % _money(r["max_loss"])) if r.get("max_loss") is not None and r["status"] == "placed" else ""+ idx = ("#%s" % r["index"]) if r.get("index") is not None else " "+ print("%s %s %-9s %s%s%s%s" % (r.get("at"), idx, r.get("status"), r.get("plain"), reply, loss, extra))+ placed = sum(1 for r in rows if r.get("status") == "placed")+ print("%d placed%s." % (placed, "" if a.all else " today"))+ return 0+++def main(argv=None):+ ap = argparse.ArgumentParser(description="Order tickets and your yes (trader-broker). Never places orders.")+ sub = ap.add_subparsers(dest="cmd")++ def clock(p):+ p.add_argument("--now", help="pretend it is this New York time, e.g. \"2026-10-19 10:15\"")+ p.add_argument("--today", help="YYYY-MM-DD (default: today in New York)")++ def common(p):+ p.add_argument("--orders", default="trader/orders.json")+ p.add_argument("--config", default="trader/config.json")+ p.add_argument("--risk", default="trader/state/risk.json")+ p.add_argument("--state", default="trader/state/broker.json")+ clock(p)++ p = sub.add_parser("show", help="render the tickets")+ common(p)+ p.add_argument("--index", type=int)+ p.add_argument("--json", action="store_true")+ p = sub.add_parser("approve", help="record the user's explicit yes for one order")+ common(p)+ p.add_argument("--index", type=int, required=True)+ p.add_argument("--reply", required=True, help="the user's reply, word for word")+ p = sub.add_parser("decline", help="record a no")+ common(p)+ p.add_argument("--index", type=int, required=True)+ p.add_argument("--reply")+ p = sub.add_parser("result", help="record what happened after the Allow once / Deny card")+ common(p)+ p.add_argument("--index", type=int, required=True)+ p.add_argument("--status", required=True, choices=["placed", "denied", "failed"])+ p.add_argument("--broker-id")+ p.add_argument("--note")+ p.add_argument("--filled-qty")+ p.add_argument("--filled-price")+ p.add_argument("--portfolio", default="trader/portfolio.json")+ p = sub.add_parser("fill", help="record a fill in trader/portfolio.json")+ p.add_argument("--symbol", required=True)+ p.add_argument("--side", required=True, choices=["buy", "sell"])+ p.add_argument("--qty", required=True)+ p.add_argument("--price", required=True)+ p.add_argument("--date", help="YYYY-MM-DD (default: today in New York)")+ p.add_argument("--now")+ p.add_argument("--portfolio", default="trader/portfolio.json")+ p.add_argument("--config", default="trader/config.json")+ p.add_argument("--state", default="trader/state/broker.json")+ p = sub.add_parser("flatten", help="a sell ticket that closes a symbol's position by flat_by")+ p.add_argument("--symbol", required=True)+ p.add_argument("--qty", help="shares you hold, from get_open_position (default: trader/portfolio.json)")+ p.add_argument("--orders", default="trader/orders.json", help="where the ticket is written")+ p.add_argument("--portfolio", default="trader/portfolio.json")+ p.add_argument("--plan", default="trader/plan.json")+ p.add_argument("--config", default="trader/config.json")+ clock(p)+ p = sub.add_parser("log", help="today's decisions")+ p.add_argument("--state", default="trader/state/broker.json")+ clock(p)+ p.add_argument("--all", action="store_true")+ a = ap.parse_args(argv)+ if not a.cmd:+ ap.print_help()+ return 1+ try:+ return {"show": cmd_show, "approve": cmd_approve, "decline": cmd_decline, "result": cmd_result,+ "fill": cmd_fill, "flatten": cmd_flatten, "log": cmd_log}[a.cmd](a)+ except TicketError as e:+ print("ticket.py: %s" % e, file=sys.stderr)+ return 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/trader-budget/SKILL.md b/trader-budget/SKILL.mdnew file mode 100644index 0000000..e28ec39--- /dev/null+++ b/trader-budget/SKILL.md@@ -0,0 +1,166 @@+---+name: trader-budget+description: >-+ Budget Manager. Sizes every position to your budget and your max loss per+ trade. Reads the trade plan from trader-exit (entry, stop, target), finds+ the whole shares that fit inside four limits (max loss per trade, position+ cap, max order, cash after your buffer), says which limit decided it, and+ writes ONE bracket order (entry, stop-loss, take-profit) to+ trader/orders.json in the exact shape of Alpaca's place_stock_order. A stop+ too far away for your max loss is a plain refusal, not a smaller order.+ Nothing is placed. Use when the user says "how many shares", "size this+ trade", "how much should I buy", "I have $5,000", "I only want to risk $50+ a trade", "set my rules", "keep 10% in cash", or after /trader-exit writes+ a plan.+argument-hint: "[budget in dollars]"+---++# trader-budget++The Budget Manager turns a plan ("buy TSLA at 364.18, stop 358.32") into an+exact order ("buy 8 shares"), inside rules the user sets once. The stop+decides the size: the further away the stop, the fewer shares. It writes a+proposal only. trader-risk checks it and trader-broker asks the user yes or+no. Day trading loses most people money. Sizing to a max loss keeps each+loss small; it does not make a trade win.++`${CLAUDE_SKILL_DIR}` below is this skill's folder (where this SKILL.md lives).++```bash+python3 "${CLAUDE_SKILL_DIR}/size.py" # trader/plan.json + trader/config.json+python3 "${CLAUDE_SKILL_DIR}/size.py" --write # write trader/orders.json+python3 "${CLAUDE_SKILL_DIR}/size.py" --limit --write # a limit order at the plan's entry+python3 "${CLAUDE_SKILL_DIR}/size.py" --limit 364.00 --json # a limit order at 364.00+python3 "${CLAUDE_SKILL_DIR}/size.py" --weights AAPL=40,KO=60 --config split.json # weights mode, below+```++`--now "2026-10-19 10:15"` pins the clock (New York time). A plan for+another day is refused: make a new one with trader-exit.++## What it reads and writes++| file | what |+| --- | --- |+| `trader/config.json` | the rules (start from `config.example.json` in this folder) |+| `trader/plan.json` | the trade: entry, stop, target, setup, flat-by time (trader-exit writes it) |+| `trader/prices.json` | optional: a fresh price above the plan's entry means a bigger risk (trader-alerts writes it) |+| `trader/portfolio.json` | optional: its cash caps the size (trader-broker keeps it) |+| `trader/orders.json` | the one proposed bracket order it writes with `--write` |++## Step 1: set the rules once++If `trader/config.json` does not exist, copy `config.example.json` into+`trader/config.json` and ask the user for each value in plain words:++- **budget**: how much money this is for. Only money they can afford to lose.+- **cash_buffer_pct**: how much always stays in cash (default 10).+- **max_loss_per_trade_usd**: the most one trade may lose if the stop fills at the stop (default 50).+- **max_position_pct**, **max_order_usd**, **min_order_usd**: the biggest position (75% of the+ budget), the biggest order ($4,000) and the smallest order ($5).+- The day limits trader-risk enforces: **max_daily_loss_usd** (150), **max_trades_per_day** (3),+ **min_reward_risk** (1.0), **require_stop** (true), **no_entries_before** / **no_entries_after**+ ("09:45" / "15:30") and **flat_by** ("15:55"), all New York time.+- **blocked**: tickers they never want to trade.+- Keep **paper** true until they have watched it work on a paper account.++## Step 2: size the trade++```bash+python3 "${CLAUDE_SKILL_DIR}/size.py" --write+```++Whole shares only: Alpaca takes no fractions in a bracket order. The size is+the smallest of four limits:++| limit | shares |+| --- | --- |+| max loss | `max_loss_per_trade_usd` / risk a share (entry minus stop) |+| position cap | budget x `max_position_pct` / entry |+| max order | `max_order_usd` / entry |+| cash | (budget minus the cash buffer) / entry, never more than the cash in `trader/portfolio.json` |++The entry it sizes at: the limit price with `--limit`. For a market order, the+plan's entry, or the price in `trader/prices.json` if it is fresh (under 15+minutes old) and higher. A price that ran up since the plan means a bigger+loss at the same stop, so fewer shares. A lower price never shrinks the risk.++It refuses, and writes no order, when: the size is zero shares, the order is+under the minimum, reward:risk is under `min_reward_risk`, the stop is not+below the entry, the target is not above it (the move already happened), the+plan is for another day, the ticker is blocked, or the plan is a short. Say+the reason to the user in one line.++## Step 3: show the user++Show the four limits, which one decided the size, the shares, the dollars+and the max loss at the stop. Say plainly that a stop is an order, not a+promise: in a fast market it can fill below the stop. Then hand over to+`/trader-risk`.++## Example: the reel++TSLA on Monday 2026-10-19. Opening-range breakout: entry 364.18 at 10:15 AM,+stop 358.32 (the opening-range midpoint), target 370.04 (1R). Risk 5.86 a+share. The example config: $5,000 budget, 10% cash buffer, $50 max loss.++| limit | the math | shares |+| --- | --- | --- |+| max loss | $50 / 5.86 | **8 (decides it)** |+| position cap | 75% of $5,000 = $3,750 / 364.18 | 10 |+| max order | $4,000 / 364.18 | 10 |+| cash | $5,000 minus $500 = $4,500 / 364.18 | 12 |++8 shares = $2,913.44. Max loss at the stop: 8 x 5.86 = $46.88. It writes:++```json+{"symbol": "TSLA", "side": "buy", "qty": "8", "type": "market", "time_in_force": "day",+ "order_class": "bracket", "take_profit_limit_price": "370.04", "stop_loss_stop_price": "358.32",+ "why": "opening-range breakout on TSLA: 8 shares, bound by your $50 max loss per trade (8 x 5.86 = $46.88 at the stop)",+ "plan": {"entry": 364.18, "stop": 358.32, "target": 370.04, "risk_per_share": 5.86, "max_loss": 46.88,+ "setup": "orb", "entry_time": "10:15 AM", "flat_by": "15:55"}}+```++`why` and `plan` are notes for trader-risk and trader-broker. They are never+sent to Alpaca. With the stop at 300.00 instead, one share would risk 64.18,+more than the $50 max loss: no order. At 10:52 the real quote was 366.48, so+the same plan sizes to 6 shares at 8.16 a share, and reward:risk falls to+0.44: refused, because the move it was waiting for has mostly happened.++## Weights mode (kept from v1)++`--weights AAPL=22.04,KO=10.86` or `--targets FILE` (`targets.example.json`+here) splits a budget across a list by weight: the cash buffer comes off the+top, weights are renormalised to 100, any stock over `max_position_pct` is+pinned at the cap and its excess shared out, slices under the minimum order+are dropped, and amounts round to whole dollars so nothing is left idle by+accident. With `"max_position_pct": 25` and `"fractional": true`, the example+file gives AAPL $1,250 (capped), AXP $1,119, GOOGL $823, KO $708, BAC $600.+With `"fractional": false` (the example config) it buys whole shares and+needs prices (`--prices trader/prices.json`). These are plain buys with no stop: trader-risk blocks them while+`require_stop` is true and counts each one against `max_trades_per_day`. Use+a separate config (`--config`) for a long-term split.++## Rules++- Proposals only. This skill never calls a broker tool.+- Never size money the user has not said is for this. Ask for the budget and the max loss.+- Every number comes from the config, the plan or the prices. Nothing is guessed.+- No projections: never say what a trade will make. A target is a plan, not a forecast.+- Free Yahoo prices are unofficial and can lag. The broker's price is the one that fills.++## What it never does++It never places, approves or schedules an order, never raises a limit on its+own, never shrinks a stop to fit more shares, and never sizes options,+margin or short positions.++## Safety++- Education and tooling, not financial advice. A PASS is a rules check, not a recommendation.+- Paper trading by default (`"paper": true`). Going live is the user's own decision, in their own config.+- Nothing in this pack places an order except trader-broker, and only when all three hold: trader-risk+ passed that exact order today, the user typed an explicit yes for that one order in the chat, and the+ user clicked Allow once on Claude's own card because the order tool is set to "Needs approval"+ (Customize > Connectors > tool permissions). Never set an order tool to "Always allow".+- No options, margin, short selling or leverage unless the config allows it and the user confirms.+- Broker keys live in environment variables or the Claude Desktop config, never in the chat.diff --git a/trader-budget/config.example.json b/trader-budget/config.example.jsonnew file mode 100644index 0000000..f02db42--- /dev/null+++ b/trader-budget/config.example.json@@ -0,0 +1,25 @@+{+ "budget": 5000,+ "cash_buffer_pct": 10,+ "max_position_pct": 75,+ "max_order_usd": 4000,+ "min_order_usd": 5,+ "max_loss_per_trade_usd": 50,+ "max_daily_loss_usd": 150,+ "max_trades_per_day": 3,+ "max_orders_per_day": 10,+ "min_reward_risk": 1.0,+ "require_stop": true,+ "no_entries_before": "09:45",+ "no_entries_after": "15:30",+ "flat_by": "15:55",+ "fractional": false,+ "broker": "alpaca",+ "paper": true,+ "blocked": [],+ "allow_options": false,+ "allow_margin": false,+ "allow_short": false,+ "pdt_guard": false,+ "sec_user_agent": "Your Name [email protected]"+}diff --git a/trader-budget/size.py b/trader-budget/size.pynew file mode 100644index 0000000..1c9ba47--- /dev/null+++ b/trader-budget/size.py@@ -0,0 +1,881 @@+#!/usr/bin/env python3+"""Position sizing for trader-budget. Standard library only, no network.++Default mode: sizes ONE day trade from trader/plan.json (written by+trader-exit) to your budget and your max loss per trade, then writes one+bracket order (entry, stop-loss, take-profit) to trader/orders.json in the+shape of Alpaca's place_stock_order. It never places anything: trader-risk+checks the order and trader-broker asks you yes or no.++ python3 size.py # trader/plan.json + trader/config.json+ python3 size.py --write # write trader/orders.json+ python3 size.py --limit # a limit order at the plan's entry+ python3 size.py --limit 364.00 --write # a limit order at 364.00+ python3 size.py --now "2026-10-19 10:15" --json # pin the clock (New York time)++How many shares. Whole shares only: Alpaca takes no fractions in a bracket.++ shares = floor of the smallest of+ max loss max_loss_per_trade_usd / risk per share (entry minus stop)+ position cap budget x max_position_pct / entry+ max order max_order_usd / entry+ cash (budget minus the cash buffer) / entry+ (and no more than the cash in trader/portfolio.json, if you have one)++The entry it sizes at: a limit order's limit price; for a market order the+plan's entry, or the price in trader/prices.json if that is fresh (under 15+minutes old) and higher, because a price that ran up since the plan means a+bigger loss at the same stop. Zero shares (the stop is too far away for your+max loss) is a plain refusal: no order is written. So is a reward:risk under+min_reward_risk (the price ran toward the target since the plan).++Weights mode (kept from v1, no longer the headline): split a budget across a+list of stocks by weight.++ python3 size.py --weights AAPL=22.04,AXP=17.14,GOOGL=12.62,KO=10.86,BAC=9.20+ python3 size.py --targets my-weights.json --budget 5000 --write+ python3 size.py --weights ... --whole-shares --prices trader/prices.json++ 1. cash buffer budget x cash_buffer_pct stays in cash, never invested+ 2. weights renormalised to 100 over the stocks you keep (blocked+ tickers are dropped first; --top N keeps the N biggest)+ 3. cap no stock gets more than max_position_pct of the budget;+ anything over the cap is shared out to the others by+ weight, again and again until nobody is over+ 4. min order a slice under min_order_usd is dropped and its weight+ shared out, so you never place a $2 order+ 5. rounding whole dollars by default (--cents for cents); the rounding+ dollar goes to the biggest position that is not capped+ 6. whole shares with --whole-shares or "fractional": false; needs prices++Money that cannot be invested is reported as "left idle", never hidden.+"""++import argparse+import datetime+import json+import math+import os+import sys++# v2 defaults: the contract's config.example.json. Missing keys fall back to these.+DEFAULTS = {+ "budget": None,+ "cash_buffer_pct": 10,+ "max_position_pct": 75,+ "max_order_usd": 4000,+ "min_order_usd": 5,+ "max_loss_per_trade_usd": 50,+ "max_daily_loss_usd": 150,+ "max_trades_per_day": 3,+ "max_orders_per_day": 10,+ "min_reward_risk": 1.0,+ "require_stop": True,+ "no_entries_before": "09:45",+ "no_entries_after": "15:30",+ "flat_by": "15:55",+ "fractional": False,+ "broker": "alpaca",+ "paper": True,+ "blocked": [],+ "allow_options": False,+ "allow_margin": False,+ "allow_short": False,+ "pdt_guard": False,+}+EPS = 1e-9+FRESH_MINUTES = 15+SETUP_WORDS = {"orb": "opening-range breakout", "flag": "flag", "bounce": "oversold bounce"}+++class SizeError(Exception):+ pass+++# ---------------------------------------------------------------- time (New York, no tz files)++def _nth_sunday(year, month, n):+ d = datetime.date(year, month, 1)+ d += datetime.timedelta(days=(6 - d.weekday()) % 7)+ return d + datetime.timedelta(weeks=n - 1)+++def eastern_offset(utc):+ """Hours from UTC for New York: -4 in daylight time, -5 otherwise.+ DST runs from 2:00 a.m. on the second Sunday of March to 2:00 a.m. on the+ first Sunday of November (US rule since 2007)."""+ y = utc.year+ start = datetime.datetime.combine(_nth_sunday(y, 3, 2), datetime.time(7, 0)) # 2:00 EST+ end = datetime.datetime.combine(_nth_sunday(y, 11, 1), datetime.time(6, 0)) # 2:00 EDT+ naive = utc.replace(tzinfo=None)+ return -4 if start <= naive < end else -5+++def to_eastern(utc):+ return utc.replace(tzinfo=None) + datetime.timedelta(hours=eastern_offset(utc))+++def eastern_to_utc(local):+ for off in (-4, -5):+ utc = local - datetime.timedelta(hours=off)+ if eastern_offset(utc) == off:+ return utc+ return local + datetime.timedelta(hours=5)+++def parse_now(text):+ """ISO time -> naive UTC. A time without an offset is taken as New York time."""+ if not text:+ return datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0, tzinfo=None)+ t = text.strip().replace("Z", "+00:00")+ try:+ dt = datetime.datetime.fromisoformat(t)+ except ValueError:+ raise SizeError("--now wants a time like \"2026-10-19 10:15\" (New York) or ...Z (UTC)")+ if dt.tzinfo is None:+ return eastern_to_utc(dt)+ return (dt - dt.utcoffset()).replace(tzinfo=None)+++def parse_utc(text):+ """"2026-10-19T14:52:13Z" -> naive UTC, or None."""+ if not text:+ return None+ try:+ dt = datetime.datetime.fromisoformat(str(text).strip().replace("Z", "+00:00"))+ except ValueError:+ return None+ if dt.tzinfo is not None:+ dt = (dt - dt.utcoffset()).replace(tzinfo=None)+ return dt+++def utc_iso(now_utc=None):+ now_utc = now_utc or datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)+ return now_utc.replace(microsecond=0).strftime("%Y-%m-%dT%H:%M:%SZ")+++# ---------------------------------------------------------------- inputs++def read_json(path, what):+ try:+ with open(path, encoding="utf-8") as fh:+ return json.load(fh)+ except FileNotFoundError:+ raise SizeError("no %s at %s" % (what, path))+ except json.JSONDecodeError as e:+ raise SizeError("%s is not valid JSON: %s" % (path, e))+++def load_config(path):+ cfg = dict(DEFAULTS)+ if path and os.path.exists(path):+ cfg.update(read_json(path, "config"))+ return cfg+++def _f(x):+ try:+ return float(x)+ except (TypeError, ValueError):+ return None+++def parse_weights(data):+ """Accept a weights file, a {ticker: weight} dict or a list of rows.++ Returns [{"ticker", "name", "weight"}] with weight as a float."""+ if isinstance(data, dict) and "weights" in data:+ data = data["weights"]+ rows = []+ if isinstance(data, dict):+ for t, w in data.items():+ rows.append({"ticker": t, "name": "", "weight": w})+ elif isinstance(data, list):+ for i, r in enumerate(data):+ if not isinstance(r, dict):+ raise SizeError("weights[%d] is not an object" % i)+ t = r.get("ticker") or r.get("symbol")+ w = r.get("weight", r.get("weight_pct", r.get("pct")))+ if not t or w is None:+ raise SizeError("weights[%d] needs a ticker and a weight" % i)+ rows.append({"ticker": t, "name": r.get("name", ""), "weight": w})+ else:+ raise SizeError("weights must be a list or an object")+ out = []+ for r in rows:+ try:+ w = float(r["weight"])+ except (TypeError, ValueError):+ raise SizeError("weight for %s is not a number: %r" % (r["ticker"], r["weight"]))+ out.append({"ticker": str(r["ticker"]).strip().upper(), "name": r["name"] or "", "weight": w})+ return out+++def weights_from_arg(text):+ """AAPL=22.04,AXP=17.14 -> {ticker: weight}"""+ out = {}+ for part in text.split(","):+ part = part.strip()+ if not part:+ continue+ if "=" not in part:+ raise SizeError("--weights wants TICKER=WEIGHT pairs, got %r" % part)+ t, w = part.split("=", 1)+ out[t.strip().upper()] = w.strip()+ return out+++def load_prices(path):+ if not path:+ return {}+ data = read_json(path, "prices")+ prices = data.get("prices", data) if isinstance(data, dict) else {}+ out = {}+ for t, p in prices.items():+ try:+ out[str(t).upper()] = float(p)+ except (TypeError, ValueError):+ continue+ return out+++def price_time(doc, sym):+ """When this symbol's price is from: the quote's own time (detail[sym].time), else when it+ was fetched (detail[sym].fetched), else the file's as_of."""+ det = ((doc or {}).get("detail") or {}).get(sym) or {}+ for key in ("time", "fetched"):+ t = parse_utc(det.get(key))+ if t:+ return t+ return parse_utc((doc or {}).get("as_of"))+++def fresh_price(doc, sym, now_utc, minutes=FRESH_MINUTES):+ """(price, fetched_utc, fresh) for sym from a prices.json doc, or (None, None, False)."""+ if not isinstance(doc, dict):+ return None, None, False+ p = _f((doc.get("prices") or {}).get(sym))+ if p is None or p <= 0:+ return None, None, False+ t = price_time(doc, sym)+ if t is None:+ return p, None, False+ age = (now_utc - t).total_seconds()+ return p, t, -60 <= age <= minutes * 60+++# ---------------------------------------------------------------- money helpers++def round_cent(x):+ """Round a price to the cent (half up)."""+ return math.floor(float(x) * 100 + 0.5 + EPS) / 100.0+++def shares_for(usd, per_share):+ """Whole shares that fit in usd at per_share, in exact integer cents."""+ u, p = int(round(float(usd) * 100)), int(round(float(per_share) * 100))+ if p <= 0 or u <= 0:+ return 0+ return u // p+++def _price(x):+ """358.32 -> "358.32": Alpaca wants prices as strings."""+ return "%.2f" % round_cent(x)+++def _num(x):+ """1250 -> "1250", 1118.13 -> "1118.13" (Alpaca wants these as strings)."""+ x = round(float(x), 2)+ if abs(x - round(x)) < 0.005:+ return str(int(round(x)))+ return "%.2f" % x+++def money(x):+ x = float(x)+ if abs(x - round(x)) < 0.005:+ return "$" + "{:,.0f}".format(round(x))+ return "$" + "{:,.2f}".format(x)+++# ---------------------------------------------------------------- plan mode (the default)++def size_trade(plan, cfg, budget=None, limit=None, price=None, cash=None, today=None):+ """Pure function: one plan + your rules -> the sizing (a dict). qty may be 0.++ limit the limit price for a limit order (None = market)+ price a FRESH latest price; a market order is sized at the higher of it and the plan's entry+ cash the cash in trader/portfolio.json, if there is one+ today New York date (YYYY-MM-DD); a plan for another day is refused"""+ c = dict(DEFAULTS)+ c.update(cfg or {})+ if not isinstance(plan, dict):+ raise SizeError("the plan is not a JSON object")+ sym = str(plan.get("symbol") or "").strip().upper()+ if not sym:+ raise SizeError("the plan has no symbol (run trader-exit)")+ side = str(plan.get("side") or "buy").strip().lower()+ if side != "buy":+ raise SizeError("this pack sizes long (buy) day trades only; the plan says %r" % side)+ if today and plan.get("date") and str(plan["date"]) != today:+ raise SizeError("the plan is for %s and today is %s in New York: make a new plan with trader-exit"+ % (plan["date"], today))+ entry_plan, stop, target = _f(plan.get("entry")), _f(plan.get("stop")), _f(plan.get("target"))+ for name, v in (("entry", entry_plan), ("stop", stop), ("target", target)):+ if v is None or v <= 0:+ raise SizeError("the plan needs a positive %s (run trader-exit); a bracket order needs entry, "+ "stop and target" % name)+ blocked = {str(b).upper() for b in (c.get("blocked") or [])}+ if sym in blocked:+ raise SizeError("%s is on your blocked list" % sym)++ budget = float(budget if budget is not None else (c.get("budget") or 0))+ if budget <= 0:+ raise SizeError("no budget: pass --budget or set \"budget\" in trader/config.json")+ buf_pct = float(c.get("cash_buffer_pct") or 0)+ if not 0 <= buf_pct < 100:+ raise SizeError("cash_buffer_pct must be between 0 and 100")++ if limit is not None:+ ref, ref_from = round_cent(limit), "limit"+ elif price is not None and round_cent(price) > round_cent(entry_plan):+ ref, ref_from = round_cent(price), "price"+ else:+ ref, ref_from = round_cent(entry_plan), "plan"+ stop, target = round_cent(stop), round_cent(target)+ if stop >= ref:+ raise SizeError("the stop %s is not below the entry %s; a long trade needs its stop underneath"+ % (_price(stop), _price(ref)))+ if target <= ref:+ raise SizeError("the target %s is not above the entry %s: the move has already happened. "+ "Skip it or make a new plan with trader-exit" % (_price(target), _price(ref)))+ risk_c = int(round((ref - stop) * 100))+ reward_c = int(round((target - ref) * 100))+ risk = risk_c / 100.0++ cash_buffer = round(budget * buf_pct / 100.0, 2)+ available = budget - cash_buffer+ cash_note = "budget %s minus the %s cash buffer" % (money(budget), money(cash_buffer))+ if cash is not None and cash - cash_buffer < available - 0.005:+ available = cash - cash_buffer+ cash_note = "cash %s in trader/portfolio.json minus the %s buffer" % (money(cash), money(cash_buffer))+ available = max(round(available, 2), 0.0)++ limits = []+ max_loss = _f(c.get("max_loss_per_trade_usd"))+ if max_loss:+ limits.append({"name": "max loss", "usd": max_loss, "per": risk, "shares": shares_for(max_loss, risk),+ "how": "%s max loss / %s risk a share" % (money(max_loss), _price(risk))})+ cap_pct = _f(c.get("max_position_pct"))+ if cap_pct:+ cap = round(budget * cap_pct / 100.0, 2)+ limits.append({"name": "position cap", "usd": cap, "per": ref, "shares": shares_for(cap, ref),+ "how": "%s%% of %s = %s / %s" % (_num(cap_pct), money(budget), money(cap), _price(ref))})+ max_order = _f(c.get("max_order_usd"))+ if max_order:+ limits.append({"name": "max order", "usd": max_order, "per": ref, "shares": shares_for(max_order, ref),+ "how": "%s / %s" % (money(max_order), _price(ref))})+ limits.append({"name": "cash", "usd": available, "per": ref, "shares": shares_for(available, ref),+ "how": "%s = %s / %s" % (cash_note, money(available), _price(ref))})++ qty = max(0, min(l["shares"] for l in limits))+ bound = [l["name"] for l in limits if l["shares"] == qty]+ for l in limits:+ l["binds"] = l["name"] == bound[0]+ cost = round(qty * ref, 2)+ loss = round(qty * risk_c / 100.0, 2)+ refusal = None+ if qty == 0:+ if bound[0] == "max loss":+ refusal = ("one share risks %s (entry %s minus stop %s), more than your %s max loss per trade. "+ "No order. Skip this trade, or plan a closer stop with trader-exit."+ % (money(risk), _price(ref), _price(stop), money(max_loss)))+ else:+ refusal = ("one share of %s costs %s, more than your %s limit (%s). No order."+ % (sym, money(ref), bound[0], limits[[l["name"] for l in limits].index(bound[0])]["how"]))+ elif _f(c.get("min_reward_risk")) and reward_c < _f(c["min_reward_risk"]) * risk_c - EPS:+ refusal = ("reward:risk %.2f (target %s, entry %s, stop %s) is under your minimum %s, so trader-risk "+ "would block it. No order. Skip it, or make a new plan with trader-exit."+ % (reward_c / float(risk_c), _price(target), _price(ref), _price(stop), _num(c["min_reward_risk"])))+ elif cost < float(c.get("min_order_usd") or 0) - 0.005:+ refusal = ("%d share%s of %s is %s, under your %s minimum order. No order."+ % (qty, "" if qty == 1 else "s", sym, money(cost), money(c["min_order_usd"])))+ return {+ "symbol": sym, "side": "buy", "setup": plan.get("setup", ""), "date": plan.get("date"),+ "entry_time": plan.get("entry_time", ""), "entry_plan": round_cent(entry_plan),+ "entry": ref, "entry_from": ref_from, "stop": stop, "target": target,+ "risk_per_share": risk, "reward_risk": round(reward_c / float(risk_c), 2),+ "stop_label": plan.get("stop_label", ""), "target_label": plan.get("target_label", ""),+ "budget": budget, "cash_buffer_pct": buf_pct, "cash_buffer": cash_buffer, "cash_available": available,+ "max_loss_per_trade_usd": max_loss, "limits": limits, "qty": qty, "bound_by": bound[0],+ "cost": cost, "max_loss": loss, "flat_by": plan.get("flat_by") or c.get("flat_by"),+ "order_type": "limit" if limit is not None else "market", "refusal": refusal,+ }+++def bracket_order(s):+ """The one proposed order, Alpaca place_stock_order fields (strings) plus why and plan."""+ if s["refusal"] or s["qty"] <= 0:+ return None+ o = {"symbol": s["symbol"], "side": "buy", "qty": str(int(s["qty"])), "type": s["order_type"],+ "time_in_force": "day"}+ if s["order_type"] == "limit":+ o["limit_price"] = _price(s["entry"])+ setup = SETUP_WORDS.get(s["setup"], s["setup"] or "day trade")+ why = ("%s on %s: %d shares, bound by your %s (%d x %s = %s at the stop)"+ % (setup, s["symbol"], s["qty"], {"max loss": "%s max loss per trade" % money(s["max_loss_per_trade_usd"] or 0),+ "position cap": "position cap", "max order": "max order",+ "cash": "cash after the buffer"}[s["bound_by"]],+ s["qty"], _price(s["risk_per_share"]), money(s["max_loss"])))+ o.update({+ "order_class": "bracket",+ "take_profit_limit_price": _price(s["target"]),+ "stop_loss_stop_price": _price(s["stop"]),+ "why": why,+ "plan": {"entry": s["entry"], "stop": s["stop"], "target": s["target"],+ "risk_per_share": s["risk_per_share"], "max_loss": s["max_loss"], "setup": s["setup"],+ "entry_time": s["entry_time"], "flat_by": s["flat_by"]},+ })+ return o+++def plan_report(s, order, notes=()):+ lines = []+ setup = SETUP_WORDS.get(s["setup"], s["setup"] or "setup")+ lines.append("%s buy, %s, entry %s%s" % (s["symbol"], setup, _price(s["entry_plan"]),+ (" at " + s["entry_time"]) if s["entry_time"] else ""))+ lines.append("Stop %s%s. Target %s%s." % (_price(s["stop"]), (": " + s["stop_label"]) if s["stop_label"] else "",+ _price(s["target"]),+ (": " + s["target_label"]) if s["target_label"] else ""))+ for n in notes:+ lines.append(n)+ src = {"plan": "the plan's entry", "price": "the latest price, above the plan's entry",+ "limit": "your limit price"}[s["entry_from"]]+ lines.append("Sized at %s (%s). Risk %s a share (entry %s minus stop %s). Reward:risk %.2f."+ % (_price(s["entry"]), src, _price(s["risk_per_share"]), _price(s["entry"]), _price(s["stop"]),+ s["reward_risk"]))+ lines.append("")+ lines.append("Limits (whole shares; the smallest one wins):")+ for l in s["limits"]:+ lines.append(" %-13s %-58s %3d shares%s" % (l["name"], l["how"], l["shares"],+ " <- binds" if l["binds"] else ""))+ lines.append("")+ if order is None:+ lines.append("No order: " + s["refusal"])+ lines.append("Education and tooling, not financial advice.")+ return "\n".join(lines)+ lines.append("Size: %d shares of %s = %s at %s. Max loss at the stop: %d x %s = %s."+ % (s["qty"], s["symbol"], money(s["cost"]), _price(s["entry"]), s["qty"],+ _price(s["risk_per_share"]), money(s["max_loss"])))+ lines.append("A stop is an order, not a promise: in a fast market it can fill below %s." % _price(s["stop"]))+ lines.append("")+ lines.append("Proposed bracket order (place_stock_order arguments, nothing has been placed):")+ how = "limit %s" % order["limit_price"] if order["type"] == "limit" else "market"+ lines.append(" buy %s %s, %s, day, take-profit %s, stop-loss %s"+ % (order["qty"], order["symbol"], how, order["take_profit_limit_price"],+ order["stop_loss_stop_price"]))+ if s["flat_by"]:+ lines.append("Flat by %s New York: anything still open then gets closed (trader-alerts rings, "+ "trader-broker flatten)." % s["flat_by"])+ lines.append("")+ lines.append("Next: trader-risk checks it, then trader-broker asks you yes or no.")+ lines.append("Education and tooling, not financial advice.")+ return "\n".join(lines)+++# ---------------------------------------------------------------- weights mode (v1)++def normalise(rows, blocked=(), top=None):+ """Drop blocked and non-positive weights, keep the top N, renormalise to 100."""+ blocked = {str(b).upper() for b in (blocked or [])}+ dropped, keep, seen = [], [], set()+ for r in rows:+ if r["ticker"] in seen:+ raise SizeError("%s is listed twice in the weights" % r["ticker"])+ seen.add(r["ticker"])+ if r["ticker"] in blocked:+ dropped.append({"ticker": r["ticker"], "reason": "on your blocked list"})+ elif r["weight"] <= 0:+ dropped.append({"ticker": r["ticker"], "reason": "weight is zero or negative"})+ else:+ keep.append(dict(r))+ keep.sort(key=lambda r: -r["weight"])+ if top:+ for r in keep[top:]:+ dropped.append({"ticker": r["ticker"], "reason": "outside the top %d" % top})+ keep = keep[:top]+ total = sum(r["weight"] for r in keep)+ for r in keep:+ r["source_weight"] = r["weight"]+ r["weight"] = 100.0 * r["weight"] / total if total else 0.0+ return keep, dropped+++def allocate(rows, investable, cap):+ """Exact (unrounded) dollars per ticker with the cap enforced.++ Proportional to weight; any stock over the cap is pinned at the cap and+ the rest of the money is shared over the others, repeated until no stock+ is over. Returns ({ticker: dollars}, set of capped tickers)."""+ alloc, capped = {}, set()+ active = [r for r in rows]+ money_left = investable+ while active:+ wsum = sum(r["weight"] for r in active)+ trial = {r["ticker"]: money_left * r["weight"] / wsum for r in active}+ over = [r for r in active if trial[r["ticker"]] > cap + EPS]+ if not over:+ alloc.update(trial)+ break+ for r in over:+ alloc[r["ticker"]] = cap+ capped.add(r["ticker"])+ money_left -= cap+ active = [r for r in active if r["ticker"] not in capped]+ if money_left <= EPS:+ for r in active:+ alloc[r["ticker"]] = 0.0+ break+ return alloc, capped+++def round_to_unit(exact, capped, order, cap, unit):+ """Round to whole dollars (unit 1) or cents (unit 0.01) and keep the total.++ The total placed is the exact total rounded DOWN to the unit, so it never+ spends money you do not have. Each slice is rounded to the nearest unit,+ then the difference (usually one unit) goes to the biggest stock that is+ not capped, then the next, never pushing anyone over the cap."""+ def units(x):+ return int(math.floor(x / unit + EPS))++ cap_u = units(cap)+ total_u = units(sum(exact.values()))+ out = {}+ for t, v in exact.items():+ out[t] = cap_u if t in capped else int(math.floor(v / unit + 0.5 + EPS))+ diff = total_u - sum(out.values())+ takers = [t for t in order if t not in capped]+ guard = 0+ while diff != 0 and takers and guard < 100000:+ moved = False+ for t in takers:+ if diff == 0:+ break+ if diff > 0 and out[t] + 1 <= cap_u:+ out[t] += 1+ diff -= 1+ moved = True+ elif diff < 0 and out[t] > 0:+ out[t] -= 1+ diff += 1+ moved = True+ if not moved:+ break+ guard += 1+ return {t: round(u * unit, 2) for t, u in out.items()}+++def whole_shares(dollars, prices, order, cap, cash):+ """Whole shares: floor each slice, then buy one more share at a time for the+ stock furthest below its slice while cash lasts and the cap holds."""+ shares = {}+ for t in order:+ shares[t] = int(math.floor(dollars[t] / prices[t] + EPS)) if dollars[t] > 0 else 0+ spent = sum(shares[t] * prices[t] for t in order)+ left = cash - spent+ while True:+ best, gap = None, None+ for t in order:+ p = prices[t]+ if p > left + EPS or (shares[t] + 1) * p > cap + EPS:+ continue+ g = dollars[t] - shares[t] * p+ if best is None or g > gap + EPS:+ best, gap = t, g+ if best is None:+ break+ shares[best] += 1+ left -= prices[best]+ return shares+++def size(rows, cfg, budget=None, prices=None, whole=None, cents=False, top=None):+ """Weights mode. Pure function: weights + rules -> the full sizing result (a dict)."""+ budget = float(budget if budget is not None else (cfg.get("budget") or 0))+ if budget <= 0:+ raise SizeError("no budget: pass --budget or set \"budget\" in trader/config.json")+ buf_pct = float(cfg.get("cash_buffer_pct", 10))+ cap_pct = float(cfg.get("max_position_pct", 25))+ min_order = float(cfg.get("min_order_usd", 5) or 0)+ if not 0 <= buf_pct < 100:+ raise SizeError("cash_buffer_pct must be between 0 and 100")+ if not 0 < cap_pct <= 100:+ raise SizeError("max_position_pct must be above 0 and at most 100")+ if whole is None:+ whole = not cfg.get("fractional", True)+ prices = prices or {}++ keep, dropped = normalise(rows, cfg.get("blocked"), top)+ if not keep:+ raise SizeError("nothing to size: no weights left after the blocked list")++ cash_buffer = round(budget * buf_pct / 100.0, 2)+ investable = round(budget - cash_buffer, 2)+ cap = round(budget * cap_pct / 100.0, 2)+ unit = 0.01 if (cents or whole) else 1.0++ if whole:+ missing = [r["ticker"] for r in keep if not prices.get(r["ticker"])]+ if missing:+ raise SizeError("whole shares need a price for: %s (add them to trader/prices.json, "+ "e.g. with trader-alerts: alerts.py quote %s --write)"+ % (", ".join(missing), " ".join(missing)))++ while True:+ live = [dict(r) for r in keep]+ tot = sum(r["source_weight"] for r in live)+ for r in live:+ r["weight"] = 100.0 * r["source_weight"] / tot+ exact, capped = allocate(live, investable, cap)+ order = [r["ticker"] for r in sorted(live, key=lambda r: -exact[r["ticker"]])]+ dollars = round_to_unit(exact, capped, order, cap, unit)+ shares = None+ if whole:+ shares = whole_shares(dollars, prices, order, cap, sum(dollars.values()))+ dollars = {t: round(shares[t] * prices[t], 2) for t in order}+ small = [r for r in live if dollars[r["ticker"]] < min_order - EPS]+ if not small:+ break+ worst = min(small, key=lambda r: (r["source_weight"], r["ticker"]))+ if whole and shares is not None and shares[worst["ticker"]] == 0 and prices.get(worst["ticker"], 0) > 0:+ reason = ("one share costs $%s, more than its slice; it cannot be bought in whole shares"+ % _num(prices[worst["ticker"]]))+ else:+ reason = "its slice ($%s) is under your $%s minimum order" % (+ _num(dollars[worst["ticker"]]), _num(min_order))+ dropped.append({"ticker": worst["ticker"], "reason": reason})+ keep = [r for r in keep if r["ticker"] != worst["ticker"]]+ if not keep:+ raise SizeError("every slice is under your minimum order; raise the budget or hold fewer stocks")++ positions = []+ for r in sorted(live, key=lambda r: -r["weight"]):+ t = r["ticker"]+ p = {"ticker": t, "name": r["name"], "weight": round(r["weight"], 2),+ "source_weight": r["source_weight"], "dollars": dollars[t],+ "capped": t in capped}+ if prices.get(t):+ p["price"] = prices[t]+ p["shares"] = shares[t] if whole else round(dollars[t] / prices[t], 4)+ positions.append(p)+ invested = round(sum(p["dollars"] for p in positions), 2)+ return {+ "budget": budget, "cash_buffer_pct": buf_pct, "cash_buffer": cash_buffer,+ "investable": investable, "max_position_pct": cap_pct, "cap": cap,+ "min_order_usd": min_order, "whole_shares": bool(whole),+ "positions": positions, "invested": invested,+ "idle": round(investable - invested, 2), "dropped": dropped,+ }+++def orders_from(result, source=""):+ """Weights mode: proposed buy orders, one per position, in place_stock_order shape."""+ out = []+ for p in result["positions"]:+ if p["dollars"] <= 0:+ continue+ why = "%.2f%% of the split" % p["weight"]+ if source:+ why = "%s, weights from %s" % (why, source)+ if p["capped"]:+ why += "; capped at %s%% of the %s budget" % (_num(result["max_position_pct"]), money(result["budget"]))+ o = {"symbol": p["ticker"], "side": "buy"}+ if result["whole_shares"]:+ o["qty"] = str(int(p["shares"]))+ else:+ o["notional"] = _num(p["dollars"])+ o.update({"type": "market", "time_in_force": "day", "why": why})+ out.append(o)+ return out+++def report(result, orders, source=""):+ """Weights mode table."""+ r = result+ lines = []+ if source:+ lines.append("Weights from: %s" % source)+ lines.append("Budget %s, cash buffer %s%% = %s, investing %s, cap %s%% = %s per stock"+ % (money(r["budget"]), _num(r["cash_buffer_pct"]), money(r["cash_buffer"]),+ money(r["investable"]), _num(r["max_position_pct"]), money(r["cap"])))+ lines.append("")+ has_price = any("price" in p for p in r["positions"])+ head = "%-7s %-22s %8s %11s" % ("ticker", "name", "weight", "dollars")+ if has_price:+ head += " %10s %10s" % ("price", "shares")+ lines.append(head + " note")+ for p in r["positions"]:+ row = "%-7s %-22s %7.2f%% %11s" % (p["ticker"], (p["name"] or "")[:22], p["weight"], money(p["dollars"]))+ if has_price:+ row += " %10s %10s" % (money(p["price"]) if "price" in p else "", p.get("shares", ""))+ if p["capped"]:+ row += " capped at %s%%" % _num(r["max_position_pct"])+ lines.append(row)+ lines.append("%-7s %-22s %8s %11s" % ("", "invested", "", money(r["invested"])))+ lines.append("%-7s %-22s %8s %11s" % ("", "cash buffer", "", money(r["cash_buffer"])))+ lines.append("%-7s %-22s %8s %11s" % ("", "left idle", "", money(r["idle"])))+ if r["idle"] >= 1:+ lines.append("")+ lines.append("Left idle %s: %s" % (money(r["idle"]), (+ "whole shares do not divide evenly" if r["whole_shares"]+ else "every stock is at its cap; add stocks or raise max_position_pct")))+ for d in r["dropped"]:+ lines.append("Dropped %s: %s" % (d["ticker"], d["reason"]))+ lines.append("")+ lines.append("Proposed orders (place_stock_order arguments, nothing has been placed):")+ for o in orders:+ amount = ("notional \"%s\"" % o["notional"]) if "notional" in o else ("qty \"%s\"" % o["qty"])+ lines.append(" %s %s %s, %s, %s" % (o["side"], o["symbol"], amount, o["type"], o["time_in_force"]))+ lines.append("")+ lines.append("These buys have no stop. trader-risk blocks them while \"require_stop\" is true and applies "+ "your day-trade limits to every buy.")+ lines.append("Next: trader-risk checks every order, then trader-broker asks you yes or no for each one.")+ lines.append("Education and tooling, not financial advice.")+ return "\n".join(lines)+++# ---------------------------------------------------------------- orders file++def write_orders(path, orders, cfg, source="", now_utc=None):+ d = os.path.dirname(path)+ if d:+ os.makedirs(d, exist_ok=True)+ doc = {+ "created_by": "trader-budget",+ "created_at": utc_iso(now_utc),+ "status": "proposed",+ "paper": bool(cfg.get("paper", True)),+ "note": ("Proposals only. Nothing is placed until trader-risk passes each order "+ "and you say yes to it in the chat."),+ "source": source,+ "orders": orders,+ }+ tmp = path + ".tmp"+ with open(tmp, "w", encoding="utf-8") as fh:+ json.dump(doc, fh, indent=2)+ fh.write("\n")+ os.replace(tmp, path)+++# ---------------------------------------------------------------- main++def run_plan(a, cfg):+ now = parse_now(a.now)+ today = to_eastern(now).date().isoformat()+ plan = read_json(a.plan, "plan (run trader-exit first, or use --weights for a split)")+ limit = None+ if a.limit is not None:+ if a.limit == "plan":+ limit = _f((plan or {}).get("entry"))+ else:+ limit = _f(a.limit)+ if limit is None or limit <= 0:+ raise SizeError("--limit wants a price, like --limit 364.00")+ sym = str((plan or {}).get("symbol") or "").upper()+ notes, price = [], None+ ppath = a.prices or ("trader/prices.json" if os.path.exists("trader/prices.json") else None)+ if ppath and limit is None and sym:+ pdoc = read_json(ppath, "prices")+ p, t, fresh = fresh_price(pdoc, sym, now)+ if p is not None and fresh:+ price = p+ if round_cent(p) > round_cent(_f(plan.get("entry")) or 0):+ notes.append("%s last %s (as of %s New York) is above the plan's entry %s, so the risk "+ "is bigger: sized at %s." % (sym, _price(p), to_eastern(t).strftime("%H:%M"),+ _price(plan.get("entry")), _price(p)))+ elif p is not None:+ notes.append("%s in %s is %s: not used (older than %d minutes). Sized at the plan's entry."+ % (sym, ppath, ("from " + to_eastern(t).strftime("%Y-%m-%d %H:%M") + " New York")+ if t else "undated", FRESH_MINUTES))+ cash = None+ if a.portfolio and os.path.exists(a.portfolio):+ pf = read_json(a.portfolio, "portfolio")+ cash = _f(pf.get("cash")) if isinstance(pf, dict) else None+ s = size_trade(plan, cfg, a.budget, limit, price, cash, today)+ order = bracket_order(s)+ if order and a.write:+ src = "trader/plan.json (%s %s %s)" % (s["symbol"], s["setup"] or "plan", s["date"] or today)+ write_orders(a.write, [order], cfg, src, now)+ if a.json:+ print(json.dumps({"sizing": s, "orders": [order] if order else [], "notes": notes}, indent=2))+ else:+ print(plan_report(s, order, notes))+ if order and a.write:+ print("Wrote 1 proposed bracket order to %s" % a.write)+ return 0 if order else 1+++def run_weights(a, cfg):+ source = ""+ if a.weights:+ rows = parse_weights(weights_from_arg(a.weights))+ else:+ data = read_json(a.targets, "weights file")+ rows = parse_weights(data)+ if isinstance(data, dict):+ source = data.get("source", "")+ prices = load_prices(a.prices)+ if not prices and os.path.exists("trader/prices.json") and not a.prices:+ prices = load_prices("trader/prices.json")+ whole = True if a.whole_shares else None+ result = size(rows, cfg, a.budget, prices, whole, a.cents, a.top)+ orders = orders_from(result, source)+ if a.write:+ write_orders(a.write, orders, cfg, source, parse_now(a.now))+ if a.json:+ print(json.dumps({"result": result, "orders": orders}, indent=2))+ else:+ print(report(result, orders, source))+ if a.write:+ print("Wrote %d proposed orders to %s" % (len(orders), a.write))+ return 0+++def main(argv=None):+ ap = argparse.ArgumentParser(description="Size a day trade to your budget and max loss (trader-budget).")+ ap.add_argument("--plan", default="trader/plan.json", help="the trade plan (default trader/plan.json)")+ ap.add_argument("--config", default="trader/config.json", help="rules (default trader/config.json)")+ ap.add_argument("--budget", type=float, help="override the budget in the config")+ ap.add_argument("--limit", nargs="?", const="plan", metavar="PRICE",+ help="a limit order instead of market, at the plan's entry or at PRICE")+ ap.add_argument("--prices", help="prices JSON (default trader/prices.json if it exists)")+ ap.add_argument("--portfolio", default="trader/portfolio.json",+ help="your account; its cash caps the size if it exists")+ ap.add_argument("--now", help="pretend it is this New York time, e.g. \"2026-10-19 10:15\"")+ ap.add_argument("--write", nargs="?", const="trader/orders.json", metavar="PATH",+ help="write the proposed order (default trader/orders.json)")+ ap.add_argument("--json", action="store_true", help="print JSON instead of the report")+ g = ap.add_argument_group("weights mode (split a budget across a list)")+ g.add_argument("--weights", help="inline weights: AAPL=22.04,AXP=17.14")+ g.add_argument("--targets", help="a weights file: {\"weights\": [{\"ticker\", \"weight\"}]}")+ g.add_argument("--top", type=int, help="keep only the N biggest weights")+ g.add_argument("--whole-shares", action="store_true", help="whole shares only (needs --prices)")+ g.add_argument("--cents", action="store_true", help="size to the cent instead of whole dollars")+ a = ap.parse_args(argv)+ try:+ cfg = load_config(a.config)+ if a.weights or a.targets:+ return run_weights(a, cfg)+ if a.top or a.whole_shares or a.cents:+ raise SizeError("--top, --whole-shares and --cents work with --weights or --targets")+ return run_plan(a, cfg)+ except SizeError as e:+ print("size.py: %s" % e, file=sys.stderr)+ return 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/trader-budget/targets.example.json b/trader-budget/targets.example.jsonnew file mode 100644index 0000000..03c296d--- /dev/null+++ b/trader-budget/targets.example.json@@ -0,0 +1,11 @@+{+ "source": "Berkshire Hathaway Inc 13F-HR, Q2 2026 (period 2026-06-30, filed 2026-08-14, accession 0001193125-26-352200), top 5 renormalised",+ "as_of": "2026-06-30",+ "weights": [+ {"ticker": "AAPL", "name": "Apple", "weight": 30.67, "pct_of_13f": 22.04},+ {"ticker": "AXP", "name": "American Express", "weight": 23.85, "pct_of_13f": 17.14},+ {"ticker": "GOOGL", "name": "Alphabet", "weight": 17.56, "pct_of_13f": 12.62},+ {"ticker": "KO", "name": "Coca-Cola", "weight": 15.11, "pct_of_13f": 10.86},+ {"ticker": "BAC", "name": "Bank of America", "weight": 12.80, "pct_of_13f": 9.20}+ ]+}diff --git a/trader-entry/SKILL.md b/trader-entry/SKILL.mdnew file mode 100644index 0000000..8eb6462--- /dev/null+++ b/trader-entry/SKILL.md@@ -0,0 +1,144 @@+---+name: trader-entry+description: >-+ Entry Timer. Watches a setup bar by bar and tells you the moment to get in.+ Reads free Yahoo 1-minute or 5-minute bars, builds the opening range (the+ first 15 minutes by default) and calls the entry on the first completed bar+ that CLOSES above the range high, or above a level you give it (like a+ 20-day high from the scanner), with an optional volume check. Says waiting+ and how far, triggered with the time and the price, expired, or not open+ yet, and writes trader/entry.json for /trader-exit. Long side only. It never+ places an order. Use when the user says "tell me when to get in", "watch+ TSLA", "has it broken out", "did it break the opening range", "entry+ signal", "time my entry", "check my watchlist", or after /trader-scanner+ and /trader-news, before /trader-exit.+argument-hint: "[TICKER] [--setup orb|level] [--interval 5m|1m]"+---++# trader-entry++The Entry Timer turns a setup into one moment: the bar that confirms it. It+reads bars, 1-minute or 5-minute, and waits for each one to finish. A price+that pokes above the high in the middle of a bar is not an entry. A bar that+CLOSES above it is. Then it says the time and the price, writes them down for+the Exit Planner, and stops. It never buys anything. Day trading loses most+people money, and a clean signal does not change that.++`${CLAUDE_SKILL_DIR}` below is this skill's folder (where this SKILL.md lives).++```bash+python3 "${CLAUDE_SKILL_DIR}/entry.py" check TSLA # 15-minute opening range, 5-minute bars+python3 "${CLAUDE_SKILL_DIR}/entry.py" check TSLA --write # also save trader/entry.json+python3 "${CLAUDE_SKILL_DIR}/entry.py" check TSLA --setup level --level 371.20+python3 "${CLAUDE_SKILL_DIR}/entry.py" check TSLA --interval 1m --min-volume-x 1.5+python3 "${CLAUDE_SKILL_DIR}/entry.py" watch TSLA --until 15:30 # one line per closed bar, stops on the trigger+python3 "${CLAUDE_SKILL_DIR}/entry.py" watchlist # every hit in trader/watchlist.json+```++Other flags: `--or-minutes N` (default 15), `--json`, `--offline FILE` (a+saved Yahoo chart JSON, `.json` or `.json.gz`, or a folder of+`<TICKER>.json`), `--now "2026-10-19 10:15"` (New York time) to replay a day.+`watch` with `--now` or `--offline` runs on a simulated clock and replays the+day bar by bar without waiting.++## What it reads and writes++| file | what |+| --- | --- |+| `trader/watchlist.json` | the scanner's hits (`hits[].symbol`), for `watchlist` |+| `trader/config.json` | `no_entries_before` (09:45) and `no_entries_after` (15:30), New York time. Optional |+| Yahoo chart API | today's bars, `range=1d&interval=5m` (or `1m`): free, unofficial, can lag |+| `trader/entry.json` | with `check --write`, or when `watch` triggers: symbol, setup, status, time, bar, price, level, opening range |++## The rule++- **Opening range (orb).** The high and low of the first 15 minutes: the+ 9:30, 9:35 and 9:40 five-minute bars, or fifteen 1-minute bars. The level+ to beat is the range high.+- **Level.** A price you give, like a 20-day high from `/trader-scanner`.+- **The trigger** is the first completed bar after the range that CLOSES+ above the level. A wick above is not a trigger. A close exactly at the+ level is not above it.+- **The time** is that bar's close time (the 10:10 bar closes at 10:15 AM).+ The price is its close, to the cent.+- **Only closed bars count.** A bar is closed when the clock passes its start+ plus 5 (or 1) minutes and Yahoo has caught up to that moment (it waits a+ minute at most). Yahoo's live tick, like 10:49:45, is never a bar.+- **Volume, if you want it.** `--min-volume-x 1.5` also needs the trigger+ bar's volume at 1.5 times the range bars' average. The 9:30 bar holds the+ opening auction, so 1.0 is already strict.+- **Time limits.** No entries before 9:45 or after 15:30 (config). On a 1:00+ p.m. early close the cutoff moves up with the close, to 12:30.+- **What it says.** Waiting (and how far the last close is from the level),+ triggered, expired, or no data. Before 9:30: not open yet. Before 9:45: the+ range is still forming. Weekends and NYSE holidays: the market is closed.++## Steps++1. Get the symbol from the user, or run `entry.py watchlist` after+ `/trader-scanner`. Check `/trader-news` for it first.+2. Run `entry.py check SYMBOL`. Tell the user the status in one line:+ waiting and how far, triggered at what time and price, or expired.+3. To wait for it, Claude can run `entry.py watch SYMBOL --until 15:30` in+ the background, or `entry.py check SYMBOL --write` on a `/loop` every 5+ minutes. `watch` wakes just after each bar closes, prints one line per+ bar, and exits 0 on the trigger (it writes `trader/entry.json`) or 1 when+ the setup expires. Keep the computer awake while it watches: a sleeping+ laptop pauses it, and it catches up, late, when it wakes.+4. When it triggers, say the time and the price, and that nothing was placed.+ If the trigger is more than a bar old, say that too: a late entry is a+ different trade.+5. Hand off to `/trader-exit` to set the stop and the target BEFORE anything+ is bought.++## Example: the reel++TSLA, Monday 2026-10-19, 5-minute bars. The opening range is 354.47 to+362.18. At 10:12 the 10:10 bar is still open, so it waits:++```+WAITING last close $361.68 (10:05 bar), $0.50 under the range high $362.18 (-0.14%).+The 10:10 bar is still forming ($364.18 so far, closes 10:15 AM); it does not count until it closes.+```++At 10:15 the bar has closed:++```+TSLA Mon 2026-10-19 10:15 ET opening-range breakout (15-minute range) on 5-minute bars (Yahoo, free, can lag)+Opening range 9:30-9:45: high $362.18, low $354.47 (3 of 3 bars).+TRIGGERED 10:15 AM at $364.18: the 10:10 bar (bar 8) closed above the range high $362.18 (+0.55%).+This is the moment to get in, if you take the trade. Nothing was placed.+Next: set the stop and target BEFORE you buy: /trader-exit (exit.py plan --from trader/entry.json).+```++With `--min-volume-x 1` the 10:10 bar is too thin (0.60x the range's volume)+and the trigger moves to 10:35 AM at 365.75 (the 10:30 bar, 7.98x).++## Rules++- Bar by bar, on free Yahoo 1-minute or 5-minute bars. They are unofficial+ and can lag. Say so when a minute matters.+- A signal is information, not an order, and not a promise. Nothing here+ promises winning trades or money.+- Long side only. v2 plans longs only. If the user wants a short, say that.+- One trigger per setup per day: the first close above. Later closes do not+ reset it.+- Never call an entry early because a bar looks like it will close above.++## What it never does++It never places an order, never sizes a position, never sets the stop (that+is `/trader-exit`), never moves the level after the fact, and never counts a+bar that has not closed. It never runs `/trader-broker` from a background+watch: nobody is there to say yes.++## Safety++- Education and tooling, not financial advice. A PASS is a rules check, not a recommendation.+- Paper trading by default (`"paper": true`). Going live is the user's own decision, in their own config.+- Nothing in this pack places an order except trader-broker, and only when all three hold: trader-risk+ passed that exact order today, the user typed an explicit yes for that one order in the chat, and the+ user clicked Allow once on Claude's own card because the order tool is set to "Needs approval"+ (Customize > Connectors > tool permissions). Never set an order tool to "Always allow".+- No options, margin, short selling or leverage unless the config allows it and the user confirms.+- Broker keys live in environment variables or the Claude Desktop config, never in the chat.diff --git a/trader-entry/entry.py b/trader-entry/entry.pynew file mode 100644index 0000000..fa0ccc5--- /dev/null+++ b/trader-entry/entry.py@@ -0,0 +1,960 @@+#!/usr/bin/env python3+"""Entry Timer for trader-entry: watches a setup bar by bar and says the+moment to get in. Standard library only. Long side only. It never places an order.++ python3 entry.py check TSLA # opening-range breakout, 5-minute bars+ python3 entry.py check TSLA --now "2026-10-19 10:15" --offline TSLA.json+ python3 entry.py check TSLA --setup level --level 371.20 # first close above a price+ python3 entry.py check TSLA --interval 1m --min-volume-x 1.5 --write+ python3 entry.py watch TSLA --every 30 --until 15:30 # one line per closed bar+ python3 entry.py watchlist # every hit in trader/watchlist.json++Setups (v2 plans longs only):+ orb opening-range breakout. The range is the high and low of the first+ --or-minutes (default 15: the 9:30, 9:35 and 9:40 five-minute bars).+ It triggers on the first COMPLETED bar after the range that CLOSES+ above the range high. A wick above the high is not a trigger.+ level the first completed bar that closes above --level (for example a+ 20-day high from trader-scanner).+ --min-volume-x X the trigger bar also needs at least X times the average+ volume of the opening-range bars (the 9:30 bar carries the opening+ auction, so 1.0 is already a high bar).++A trigger's time is the trigger bar's CLOSE time (the 10:10 bar closes at+10:15 AM) and its price is that close, to the cent. Only bars on the interval+grid count (Yahoo's live tick, e.g. 10:49:45, is dropped) and a bar counts only+once it has closed: now >= its start + the interval.++Statuses: triggered; waiting (not open yet, range still forming, or no close+above the level yet); expired (no trigger by no_entries_after, default 15:30;+on a 1:00 p.m. early close the cutoff moves up three hours with the close);+no-data (the market is closed today or Yahoo sent no bars).++trader/config.json (optional): "no_entries_before" (09:45) and+"no_entries_after" (15:30), New York time.++watch wakes just after each bar closes (bars only change then), re-polls every+--every seconds (default 30) while Yahoo has not posted the new bar, prints one+line per closed bar and stops on a trigger (exit 0, writes trader/entry.json),+on expiry, at the close or at --until (exit 1). With --now or --offline it runs+on a simulated clock and replays the day without sleeping.++Data: Yahoo's free chart JSON (unofficial, can lag, bars not single trades)+ https://query2.finance.yahoo.com/v8/finance/chart/TSLA?range=1d&interval=5m+ falls back to query1 on HTTP 429 or 5xx; a 429 gets one retry after a pause.+ --offline PATH reads a saved chart JSON (.json or .json.gz) instead, or+ PATH/<TICKER>.json when PATH is a folder. Without --now, an offline file is+ read as of its own time (meta.regularMarketTime).++Exit codes: check 0 = triggered, 1 = anything else or an error. watch 0 on a+trigger, 1 otherwise. watchlist 0 when at least one symbol triggered.+"""++import argparse+import datetime+import gzip+import json+import os+import re+import sys+import time+import urllib.error+import urllib.request++UA = "Mozilla/5.0 (compatible; day-trader-skill/2.0; +https://github.com/Jakeschincariol/day-trader-skill)"+PAUSE = 0.5 # seconds between requests to the free endpoint+BACKOFF = 5.0 # seconds before the one retry after an HTTP 429+GRACE = 2 # seconds after a bar closes before watch asks for it+SETTLE = 60 # seconds a closed bar may wait for Yahoo's data to catch up+HOSTS = ("query2", "query1")+INTERVALS = {"1m": 60, "5m": 300}+DEFAULTS = {"no_entries_before": "09:45", "no_entries_after": "15:30"}+EPOCH = datetime.datetime(1970, 1, 1)++NYSE_HOLIDAYS = {+ "2026-01-01": "New Year's Day",+ "2026-01-19": "Martin Luther King, Jr. Day",+ "2026-02-16": "Washington's Birthday",+ "2026-04-03": "Good Friday",+ "2026-05-25": "Memorial Day",+ "2026-06-19": "Juneteenth National Independence Day",+ "2026-07-03": "Independence Day (observed)",+ "2026-09-07": "Labor Day",+ "2026-11-26": "Thanksgiving Day",+ "2026-12-25": "Christmas Day",+ "2027-01-01": "New Year's Day",+ "2027-01-18": "Martin Luther King, Jr. Day",+ "2027-02-15": "Washington's Birthday",+ "2027-03-26": "Good Friday",+ "2027-05-31": "Memorial Day",+ "2027-06-18": "Juneteenth National Independence Day (observed)",+ "2027-07-05": "Independence Day (observed)",+ "2027-09-06": "Labor Day",+ "2027-11-25": "Thanksgiving Day",+ "2027-12-24": "Christmas Day (observed)",+}+NYSE_EARLY_CLOSE = { # 1:00 p.m. ET+ "2026-11-27": "day after Thanksgiving",+ "2026-12-24": "Christmas Eve",+ "2027-11-26": "day after Thanksgiving",+}+CALENDAR_YEARS = (2026, 2027)+OPEN = datetime.time(9, 30)+CLOSE = datetime.time(16, 0)+EARLY = datetime.time(13, 0)+++class EntryError(Exception):+ pass+++# ---------------------------------------------------------------- time++def _nth_sunday(year, month, n):+ d = datetime.date(year, month, 1)+ d += datetime.timedelta(days=(6 - d.weekday()) % 7)+ return d + datetime.timedelta(weeks=n - 1)+++def eastern_offset(utc):+ """Hours from UTC for New York: -4 in daylight time, -5 otherwise.+ DST runs from 2:00 a.m. on the second Sunday of March to 2:00 a.m. on the+ first Sunday of November (US rule since 2007)."""+ y = utc.year+ start = datetime.datetime.combine(_nth_sunday(y, 3, 2), datetime.time(7, 0)) # 2:00 EST+ end = datetime.datetime.combine(_nth_sunday(y, 11, 1), datetime.time(6, 0)) # 2:00 EDT+ naive = utc.replace(tzinfo=None)+ return -4 if start <= naive < end else -5+++def to_eastern(utc):+ return utc.replace(tzinfo=None) + datetime.timedelta(hours=eastern_offset(utc))+++def eastern_to_utc(local):+ for off in (-4, -5):+ utc = local - datetime.timedelta(hours=off)+ if eastern_offset(utc) == off:+ return utc+ return local + datetime.timedelta(hours=5)+++def utc_now():+ return datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0, tzinfo=None)+++def utc_of(ts):+ """Unix seconds -> naive UTC, without the machine's time zone."""+ return EPOCH + datetime.timedelta(seconds=int(ts))+++def ts_of(utc):+ return int((utc.replace(tzinfo=None) - EPOCH).total_seconds())+++def iso(utc):+ return utc.strftime("%Y-%m-%dT%H:%M:%SZ")+++def parse_now(text):+ """--now -> naive UTC. "2026-10-19 10:15" (or ...T10:15, or just 10:15 for+ today) is New York time; an offset or Z makes it absolute."""+ if not text:+ return utc_now()+ t = text.strip()+ if t.upper().endswith(" ET"):+ t = t[:-3].strip()+ if re.match(r"^\d{1,2}:\d{2}$", t):+ t = "%s %s" % (to_eastern(utc_now()).date().isoformat(), t.zfill(5))+ t = t.replace("Z", "+00:00")+ try:+ dt = datetime.datetime.fromisoformat(t)+ except ValueError:+ raise EntryError('--now wants a New York time like "2026-10-19 10:15" (or ...Z for UTC)')+ if dt.tzinfo is None:+ return eastern_to_utc(dt)+ return (dt - dt.utcoffset()).replace(tzinfo=None)+++def parse_hhmm(text, what):+ m = re.match(r"^\s*(\d{1,2}):(\d{2})\s*$", str(text))+ if not m or int(m.group(1)) > 23 or int(m.group(2)) > 59:+ raise EntryError("%s wants a New York time like 15:30, not %r" % (what, text))+ return datetime.time(int(m.group(1)), int(m.group(2)))+++def hm(t):+ """10:10, 09:45: the contract's wall-clock form."""+ return "%02d:%02d" % (t.hour, t.minute)+++def short(t):+ """9:45, 10:10: for sentences."""+ return "%d:%02d" % (t.hour, t.minute)+++def ampm(t):+ h = t.hour % 12 or 12+ return "%d:%02d %s" % (h, t.minute, "AM" if t.hour < 12 else "PM")+++def trading_day(d):+ """(is_trading_day, reason). Weekends and the NYSE holiday list."""+ if d.weekday() >= 5:+ return False, "weekend"+ name = NYSE_HOLIDAYS.get(d.isoformat())+ if name:+ return False, "NYSE holiday: " + name+ return True, ""+++def session(d):+ """(open_time, close_time) in New York time, or None if closed all day."""+ ok, _ = trading_day(d)+ if not ok:+ return None+ return OPEN, (EARLY if d.isoformat() in NYSE_EARLY_CLOSE else CLOSE)+++def next_open(d):+ nd = d + datetime.timedelta(days=1)+ for _ in range(15):+ if session(nd):+ return "%s 09:30" % nd.isoformat()+ nd += datetime.timedelta(days=1)+ return None+++# ---------------------------------------------------------------- Yahoo++def yahoo_symbol(sym):+ return sym.upper().replace(".", "-")+++def chart_path(sym, rng, interval):+ return "/v8/finance/chart/%s?range=%s&interval=%s" % (yahoo_symbol(sym), rng, interval)+++def chart_range(day, today, interval):+ """The smallest Yahoo range that still holds the session of `day`."""+ back = (today - day).days+ if back <= 0:+ return "1d"+ if back <= 6:+ return "5d"+ if interval == "1m":+ raise EntryError("Yahoo keeps 1-minute bars for about a week: use --interval 5m for %s" % day)+ if back <= 28:+ return "1mo"+ if back <= 58:+ return "60d"+ raise EntryError("Yahoo keeps 5-minute bars for about 60 days: %s is too far back" % day)+++def _open_url(url, timeout=20):+ req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "application/json"})+ with urllib.request.urlopen(req, timeout=timeout) as r:+ return r.read().decode("utf-8", "replace")+++def _sleep(seconds):+ time.sleep(seconds)+++def yahoo_get(path):+ """GET a Yahoo path: query2 first, query1 when query2 answers 429 or 5xx.+ An HTTP 429 gets one retry on the same host after BACKOFF seconds."""+ last = "no answer"+ for host in HOSTS:+ url = "https://%s.finance.yahoo.com%s" % (host, path)+ for attempt in (0, 1):+ try:+ return _open_url(url)+ except urllib.error.HTTPError as e:+ code, body = e.code, None+ try:+ if code == 404: # Yahoo says why in the body: an unknown ticker+ body = e.read().decode("utf-8", "replace")+ except Exception:+ body = None+ finally:+ e.close()+ if code == 404:+ if body:+ return body+ raise EntryError("Yahoo has no chart at %s (HTTP 404)" % url.split("?")[0])+ last = "HTTP %d" % code+ if code == 429 and attempt == 0:+ _sleep(BACKOFF)+ continue+ if code == 429 or code >= 500:+ break+ raise EntryError("Yahoo answered HTTP %d for %s" % (code, url.split("?")[0]))+ except urllib.error.URLError as e:+ last = "could not connect: %s" % (e.reason,)+ break+ except OSError as e:+ last = "network error: %s" % (e,)+ break+ raise EntryError("Yahoo did not answer (%s on query2 and query1): wait a minute and try again" % last)+++def parse_chart(text, sym):+ """Yahoo chart JSON v8 -> {symbol, meta, bars, prev_close, data_time}.+ Bars with a null close are dropped here; off-grid ticks later."""+ try:+ data = json.loads(text)+ res = data["chart"]["result"]+ except (ValueError, KeyError, TypeError):+ raise EntryError("Yahoo returned something unexpected for %s" % sym)+ if not res:+ err = (data.get("chart") or {}).get("error") or {}+ raise EntryError("Yahoo has no data for %s: %s" % (sym, err.get("description") or "unknown ticker"))+ r = res[0] or {}+ meta = r.get("meta") or {}+ q = ((r.get("indicators") or {}).get("quote") or [{}])[0] or {}++ def at(key, i):+ arr = q.get(key) or []+ return arr[i] if i < len(arr) else None++ bars = []+ for i, t in enumerate(r.get("timestamp") or []):+ c = at("close", i)+ if t is None or c is None:+ continue+ o, h, lo = at("open", i), at("high", i), at("low", i)+ bars.append({"t": int(t), "o": float(c if o is None else o), "h": float(c if h is None else h),+ "l": float(c if lo is None else lo), "c": float(c), "v": int(at("volume", i) or 0)})+ return {"symbol": str(meta.get("symbol") or sym).upper(), "meta": meta, "bars": bars,+ "prev_close": meta.get("previousClose") or meta.get("chartPreviousClose"),+ "data_time": meta.get("regularMarketTime")}+++def read_text(path):+ if path.endswith(".gz"):+ with gzip.open(path, "rt", encoding="utf-8") as fh:+ return fh.read()+ with open(path, encoding="utf-8") as fh:+ return fh.read()+++def offline_file(path, sym):+ if os.path.isdir(path):+ for name in (sym + ".json", sym + ".json.gz", yahoo_symbol(sym) + ".json", yahoo_symbol(sym) + ".json.gz"):+ p = os.path.join(path, name)+ if os.path.exists(p):+ return p+ raise EntryError("no offline file for %s in %s (want %s.json)" % (sym, path, sym))+ if not os.path.exists(path):+ raise EntryError("no offline file %s" % path)+ return path+++def get_chart(sym, interval, day=None, offline=None, today=None):+ """Bars for one ticker, from Yahoo (range=1d for today) or a saved file."""+ sym = sym.upper()+ if offline:+ f = offline_file(offline, sym)+ try:+ text = read_text(f)+ except (OSError, ValueError) as e:+ raise EntryError("could not read %s: %s" % (f, e))+ else:+ today = today or to_eastern(utc_now()).date()+ text = yahoo_get(chart_path(sym, chart_range(day or today, today, interval), interval))+ ch = parse_chart(text, sym)+ if ch["symbol"] != yahoo_symbol(sym):+ raise EntryError("the chart file holds %s, not %s" % (ch["symbol"], sym))+ gran = ch["meta"].get("dataGranularity")+ if gran and gran != interval:+ raise EntryError("%s has %s bars, not %s: use --interval %s" % (sym, gran, interval, gran))+ return ch+++# ---------------------------------------------------------------- the rule++def read_config(path):+ cfg = dict(DEFAULTS)+ if path and os.path.exists(path):+ try:+ with open(path, encoding="utf-8") as fh:+ doc = json.load(fh)+ except ValueError as e:+ raise EntryError("%s is not valid JSON: %s" % (path, e))+ for k in DEFAULTS:+ if doc.get(k):+ cfg[k] = doc[k]+ for k in DEFAULTS:+ parse_hhmm(cfg[k], k)+ return cfg+++def r2(x):+ return None if x is None else round(float(x), 2) + 0.0 # + 0.0 turns -0.0 into 0.0+++def early_cutoff(day, t, close_dt):+ """A cutoff on an early-close day moves up with the close: 15:30 (30 minutes+ before a 16:00 close) becomes 12:30 before a 1:00 p.m. close. A cutoff that+ is already before the early close stays."""+ at = datetime.datetime.combine(day, t)+ if at < close_dt:+ return at+ moved = at - (datetime.datetime.combine(day, CLOSE) - close_dt)+ return moved if moved.time() > OPEN else close_dt+++def evaluate(chart, now_utc, setup="orb", or_minutes=15, interval="5m", level=None,+ min_volume_x=None, cfg=None):+ """Pure function: the setup's status at now_utc from one session's bars."""+ cfg = cfg or dict(DEFAULTS)+ if interval not in INTERVALS:+ raise EntryError("--interval is 5m or 1m")+ step = INTERVALS[interval]+ if or_minutes <= 0 or (or_minutes * 60) % step:+ raise EntryError("--or-minutes must be a whole number of %s bars" % interval)+ if setup not in ("orb", "level"):+ raise EntryError("--setup is orb or level")+ if setup == "level" and level is None:+ raise EntryError("--setup level needs --level PRICE (for example a 20-day high)")+ n_or = or_minutes * 60 // step+ local = to_eastern(now_utc)+ day = local.date()+ res = {"symbol": chart["symbol"], "setup": setup, "side": "buy", "date": day.isoformat(),+ "interval": interval, "or_minutes": or_minutes, "now": local.strftime("%Y-%m-%d %H:%M:%S"), "status": "waiting",+ "phase": "", "reason": "", "opening_range": None, "level": None, "trigger": None,+ "last": None, "forming": None, "min_volume_x": min_volume_x,+ "prev_close": chart.get("prev_close"), "calendar_known": day.year in CALENDAR_YEARS, "_bars": []}+ dt = chart.get("data_time")+ res["data_time"] = to_eastern(utc_of(dt)).strftime("%Y-%m-%d %H:%M:%S") if dt else None+ ok, why = trading_day(day)+ if not ok:+ res.update(status="no-data", phase="closed", reason="the NYSE is closed today (%s)" % why,+ next_open=next_open(day))+ return res+ o, c = session(day)+ open_dt = datetime.datetime.combine(day, o)+ close_dt = datetime.datetime.combine(day, c)+ early = c != CLOSE+ before = datetime.datetime.combine(day, parse_hhmm(cfg["no_entries_before"], "no_entries_before"))+ cutoff = early_cutoff(day, parse_hhmm(cfg["no_entries_after"], "no_entries_after"), close_dt)+ or_end = open_dt + datetime.timedelta(minutes=or_minutes)+ res.update(opens=hm(o), closes=hm(c), early_close=NYSE_EARLY_CLOSE.get(day.isoformat()),+ no_entries_before=hm(before), no_entries_after=hm(cutoff))++ by_slot = {}+ for b in chart["bars"]:+ if b["t"] % step:+ continue # Yahoo's live tick (10:49:45) is not a bar+ et = to_eastern(utc_of(b["t"]))+ if et.date() != day or not (open_dt <= et < close_dt):+ continue+ slot = int((et - open_dt).total_seconds()) // step+ by_slot[slot] = dict(b, et=et, end=et + datetime.timedelta(seconds=step), slot=slot)+ bars, pending = [], None+ now_ts = ts_of(now_utc)+ top = max(by_slot) if by_slot else -1+ for slot in sorted(by_slot):+ b = by_slot[slot]+ end_ts = b["t"] + step+ if end_ts <= now_ts:+ # Closed by the clock. On live data it counts once Yahoo has caught up: its last+ # trade is at or after the close, a later bar exists, or a minute has passed.+ if dt is None or dt >= end_ts or slot < top or now_ts >= end_ts + SETTLE:+ bars.append(b)+ else:+ pending = b+ res["forming"] = {"bar_start": hm(b["et"]), "closes": ampm(b["end"]), "price": r2(b["c"])}+ res["lag_note"] = ("Yahoo's last trade is %s, before the %s bar's close: it counts once Yahoo "+ "catches up (a minute at most)" % (to_eastern(utc_of(dt)).strftime("%H:%M:%S"),+ short(b["et"])))+ elif b["et"] <= local:+ res["forming"] = {"bar_start": hm(b["et"]), "closes": ampm(b["end"]), "price": r2(b["c"])}+ res["_bars"] = bars+ res["bars_closed"] = len(bars)++ if local < open_dt:+ res.update(phase="pre-open", reason="the NYSE opens at 9:30%s" % (+ " and the %d-minute range is set at %s" % (or_minutes, short(or_end)) if setup == "orb" else ""))+ return res++ or_bars = [b for b in bars if b["slot"] < n_or]+ avg_vol = (sum(b["v"] for b in or_bars) / float(len(or_bars))) if or_bars else None+ if or_bars:+ res["opening_range"] = {"high": r2(max(b["h"] for b in or_bars)), "low": r2(min(b["l"] for b in or_bars)),+ "minutes": or_minutes, "bars": len(or_bars), "of": n_or,+ "complete": local >= or_end, "avg_volume": int(round(avg_vol))}+ if setup == "orb":+ if local < or_end:+ res.update(phase="forming", reason="%d of %d range bars closed; the range is set at %s" % (+ len(or_bars), n_or, short(or_end)))+ return res+ if not or_bars:+ res.update(status="no-data", phase="open", reason="Yahoo sent no bars for the opening range")+ return res+ lvl = max(b["h"] for b in or_bars)+ else:+ lvl = float(level)+ res["level"] = r2(lvl)++ first_slot = n_or if setup == "orb" else 0+ trig, thin = None, []+ for b in bars:+ if b["slot"] < first_slot or b["end"] < before or b["end"] > cutoff:+ continue+ if b["c"] > lvl:+ vx = (b["v"] / avg_vol) if avg_vol else None+ if min_volume_x and (vx is None or vx < min_volume_x):+ thin.append(b)+ continue+ trig = b+ break+ last = bars[-1] if bars else None+ if last:+ res["last"] = {"bar_start": hm(last["et"]), "close": r2(last["c"]),+ "vs_level_pct": r2(100.0 * (last["c"] / lvl - 1))}++ if trig:+ vx = (trig["v"] / avg_vol) if avg_vol else None+ res.update(status="triggered", phase="open" if local < close_dt else "after-close",+ reason="the %s bar closed above %s" % (short(trig["et"]), "the range high" if setup == "orb" else "the level"))+ res["trigger"] = {"time": ampm(trig["end"]), "close_time": hm(trig["end"]), "bar_start": hm(trig["et"]),+ "bar_index": trig["slot"], "price": r2(trig["c"]), "close": trig["c"],+ "volume": trig["v"], "volume_x": r2(vx), "pct_over": r2(100.0 * (trig["c"] / lvl - 1))}+ res["minutes_since"] = int((local - trig["end"]).total_seconds() // 60)+ if dt and utc_of(dt) < eastern_to_utc(trig["end"]):+ res["data_note"] = ("Yahoo's last trade is %s, before this bar closed: its close can still move a cent or two"+ % to_eastern(utc_of(dt)).strftime("%H:%M:%S"))+ return res+ if not bars:+ res.update(status="no-data", phase="open", reason="Yahoo sent no bars for %s yet" % day.isoformat())+ return res+ what = "close above the range high $%.2f" % lvl if setup == "orb" else "close above $%.2f" % lvl+ if local >= cutoff and not (pending and pending["end"] <= cutoff):+ res.update(status="expired", phase="after-close" if local >= close_dt else "after-cutoff",+ reason="no %s by %s, the last time for a new entry%s" % (+ what, short(cutoff), " (1:00 p.m. early close today)" if early else ""))+ return res+ res["phase"] = "open"+ if last["c"] > lvl and last in thin:+ res["reason"] = "the %s bar closed above at $%.2f but on %.2fx the range's volume, under your %.2fx" % (+ short(last["et"]), last["c"], last["v"] / avg_vol if avg_vol else 0, min_volume_x)+ elif last["c"] > lvl and last["end"] < before:+ res["reason"] = "the %s bar closed above at $%.2f, but no entries before %s (config)" % (+ short(last["et"]), last["c"], short(before))+ else:+ gap = lvl - last["c"]+ res["reason"] = "last close $%.2f (%s bar), $%.2f %s %s (%+.2f%%)" % (+ last["c"], short(last["et"]), abs(gap), "under" if gap >= 0 else "over",+ "the range high $%.2f" % lvl if setup == "orb" else "the level $%.2f" % lvl,+ 100.0 * (last["c"] / lvl - 1))+ return res+++def public(res):+ """The result without the internal bar list, ready for JSON."""+ return {k: v for k, v in res.items() if not k.startswith("_")}+++def entry_doc(res, now_utc):+ """trader/entry.json, the contract shape (plus a plain-words reason)."""+ t = res.get("trigger") or {}+ orr = res.get("opening_range")+ return {"created_by": "trader-entry", "symbol": res["symbol"], "setup": res["setup"], "side": "buy",+ "date": res["date"], "status": res["status"], "time": t.get("time"), "bar_start": t.get("bar_start"),+ "bar_index": t.get("bar_index"), "price": t.get("price"), "level": res.get("level"),+ "interval": res["interval"],+ "opening_range": {"high": orr["high"], "low": orr["low"], "minutes": orr["minutes"]} if orr else None,+ "source": "yahoo", "checked_at": iso(now_utc), "reason": res.get("reason")}+++def write_json(path, doc):+ d = os.path.dirname(path)+ if d:+ os.makedirs(d, exist_ok=True)+ with open(path, "w", encoding="utf-8") as fh:+ json.dump(doc, fh, indent=2)+ fh.write("\n")+++# ---------------------------------------------------------------- words++LABEL = {"triggered": "TRIGGERED", "waiting": "WAITING", "expired": "EXPIRED", "no-data": "NO DATA"}+PHASE_LABEL = {"pre-open": "NOT OPEN YET", "forming": "RANGE FORMING", "closed": "MARKET CLOSED"}+SHORT = {"pre-open": "not open", "forming": "forming", "closed": "closed"}+++def setup_name(res):+ if res["setup"] == "orb":+ return "opening-range breakout (%d-minute range)" % res["or_minutes"]+ return "close above $%.2f" % res["level"] if res["level"] is not None else "close above a level"+++def describe(res):+ """Plain lines for a person."""+ when = datetime.datetime.strptime(res["now"], "%Y-%m-%d %H:%M:%S")+ bars = "5-minute" if res["interval"] == "5m" else "1-minute"+ head = "%s %s %s ET %s on %s bars (Yahoo, free, can lag)" % (+ res["symbol"], when.strftime("%a %Y-%m-%d"), when.strftime("%H:%M"), setup_name(res), bars)+ if res.get("data_time") and res["data_time"] <= res["now"] and res["data_time"][:10] == res["date"]:+ head += ", data to %s" % res["data_time"][11:]+ out = [head]+ orr = res.get("opening_range")+ if orr:+ start = datetime.datetime.strptime(res["opens"], "%H:%M")+ end = start + datetime.timedelta(minutes=orr["minutes"])+ out.append("Opening range %s-%s: high $%.2f, low $%.2f (%d of %d bars%s)." % (+ short(start), short(end), orr["high"], orr["low"], orr["bars"], orr["of"],+ "" if orr["complete"] else ", still forming"))+ label = PHASE_LABEL.get(res["phase"]) or LABEL.get(res["status"], res["status"].upper())+ t = res.get("trigger")+ if t:+ out.append("TRIGGERED %s at $%.2f: the %s bar (bar %d) closed above %s $%.2f (%+.2f%%%s)." % (+ t["time"], t["price"], short(datetime.datetime.strptime(t["bar_start"], "%H:%M")), t["bar_index"],+ "the range high" if res["setup"] == "orb" else "the level", res["level"], t["pct_over"],+ (", %.2fx the range's volume" % t["volume_x"]) if res.get("min_volume_x") and t.get("volume_x") else ""))+ step = INTERVALS[res["interval"]] // 60+ if res.get("minutes_since", 0) > step and res.get("last"):+ out.append("That was %d minutes ago; the last close is $%.2f (%s bar). A late entry is a different "+ "trade: the price, the stop distance and the odds have moved." % (+ res["minutes_since"], res["last"]["close"], res["last"]["bar_start"]))+ if res.get("data_note"):+ out.append(res["data_note"] + ".")+ if res.get("minutes_since", 0) > step:+ out.append("Nothing was placed.")+ else:+ out.append("This is the moment to get in, if you take the trade. Nothing was placed.")+ out.append("Next: set the stop and target BEFORE you buy: /trader-exit "+ "(exit.py plan --from trader/entry.json).")+ else:+ out.append("%s %s." % (label, res["reason"]))+ f = res.get("forming")+ if res.get("lag_note") and res["status"] == "waiting":+ out.append(res["lag_note"] + ".")+ elif f and res["status"] == "waiting" and res["phase"] in ("open", "forming"):+ out.append("The %s bar is still forming ($%.2f so far, closes %s); it does not count until it closes." % (+ f["bar_start"].lstrip("0"), f["price"], f["closes"]))+ if res["status"] == "expired":+ out.append("No entry on this setup today. Nothing was placed.")+ if res.get("next_open"):+ out.append("Next open: %s New York." % res["next_open"])+ if res.get("early_close"):+ out.append("Early close today at 1:00 p.m. (%s): no new entries after %s." % (+ res["early_close"], res["no_entries_after"]))+ if not res.get("calendar_known"):+ out.append("Holiday list covers %s only: check nyse.com for this date." % " and ".join(map(str, CALENDAR_YEARS)))+ return out+++def bar_line(b, res):+ """One watch line for a bar that just closed."""+ start = short(b["et"])+ orr = res.get("opening_range") or {}+ lvl = res.get("level")+ t = res.get("trigger")+ n_or = orr.get("of") or 0+ if res["setup"] == "orb" and b["slot"] < n_or:+ seen = [x for x in res["_bars"] if x["slot"] <= b["slot"]]+ note = "range so far $%.2f to $%.2f" % (min(x["l"] for x in seen), max(x["h"] for x in seen))+ if b["slot"] == n_or - 1:+ note = "opening range set: high $%.2f, low $%.2f" % (orr["high"], orr["low"])+ elif t and t["bar_index"] == b["slot"]:+ note = "TRIGGERED: closed above $%.2f (%+.2f%%). Get in now if you take it: %s, $%.2f" % (+ lvl, t["pct_over"], t["time"], t["price"])+ elif lvl is None:+ note = ""+ elif b["c"] > lvl:+ note = "above $%.2f" % lvl+ if res["setup"] == "level" or b["slot"] >= n_or:+ avg = orr.get("avg_volume")+ if res.get("min_volume_x") and avg:+ note += ", but volume %.2fx is under %.2fx" % (b["v"] / float(avg), res["min_volume_x"])+ elif b["end"] < datetime.datetime.combine(b["et"].date(), parse_hhmm(res["no_entries_before"], "x")):+ note += ", but no entries before %s" % res["no_entries_before"]+ else:+ note = "$%.2f under $%.2f" % (lvl - b["c"], lvl)+ return "%5s bar closed $%.2f %s" % (start, b["c"], note)+++# ---------------------------------------------------------------- watch++class SimClock(object):+ """A clock that moves only when it sleeps: replays a day without waiting."""++ def __init__(self, start):+ self.t = start++ def now(self):+ return self.t++ def sleep(self, seconds):+ self.t += datetime.timedelta(seconds=max(1, int(round(seconds))))+++def watch_loop(provider, clock, sleep, emit, opts, every=30, until=None, max_errors=5, on_trigger=None):+ """Poll bar by bar until a trigger (0), expiry, the close or --until (1).+ provider(now_utc) -> chart, clock() -> naive UTC, sleep(seconds), emit(line).+ It sleeps in steps of at most `every` seconds and re-reads the clock each time,+ so a computer that dozed off catches up as soon as it wakes."""+ step = INTERVALS[opts.get("interval", "5m")]+ printed, errors, said_preopen, first = -1, 0, False, True+ next_fetch = None+ while True:+ now = clock()+ if next_fetch is not None and now < next_fetch:+ sleep(max(1, min(every, (next_fetch - now).total_seconds())))+ continue+ local = to_eastern(now)+ day = local.date()+ s = session(day)+ if not s:+ emit("%s: market closed today (%s). Nothing to watch." % (day.isoformat(), trading_day(day)[1]))+ return 1, None+ open_dt = datetime.datetime.combine(day, s[0])+ close_dt = datetime.datetime.combine(day, s[1])+ if local < open_dt + datetime.timedelta(seconds=step):+ if not said_preopen:+ emit("%s ET %s: watching from the first bar's close at %s." % (+ local.strftime("%H:%M"), "not open yet" if local < open_dt else "open, no bar closed yet",+ short(open_dt + datetime.timedelta(seconds=step))))+ said_preopen = True+ next_fetch = eastern_to_utc(open_dt) + datetime.timedelta(seconds=step + GRACE)+ continue+ try:+ chart = provider(now)+ errors = 0+ except EntryError as e:+ errors += 1+ emit("%s ET could not read bars: %s" % (local.strftime("%H:%M:%S"), e))+ if errors >= max_errors:+ emit("Stopping after %d failed reads in a row." % errors)+ return 1, None+ next_fetch = now + datetime.timedelta(seconds=every)+ continue+ res = evaluate(chart, now, **opts)+ bars = res["_bars"]+ lines = describe(res)+ fresh = first+ if first:+ emit(lines[0])+ if len(lines) > 1 and lines[1].startswith("Opening range"):+ emit(lines[1])+ if bars and not res.get("trigger"):+ emit(bar_line(bars[-1], res))+ printed = bars[-1]["slot"] if bars else -1+ first = False+ else:+ for b in bars:+ if b["slot"] > printed:+ emit(bar_line(b, res))+ printed = b["slot"]+ if res["status"] == "triggered":+ for line in lines[1:]:+ if line.startswith("Opening range") or (line.startswith("TRIGGERED") and not fresh):+ continue+ emit(line)+ if on_trigger:+ on_trigger(res, now)+ return 0, res+ if res["status"] == "expired" or local >= close_dt:+ emit("EXPIRED %s." % (res["reason"] or "the market closed without a trigger"))+ return 1, res+ if until and local >= until:+ emit("Stopped at --until %s without a trigger. %s." % (short(until), res["reason"]))+ return 1, res+ # sleep until just after the next bar closes; poll every `every` seconds if Yahoo is behind+ cur_slot = int((local - open_dt).total_seconds()) // step+ expected_last = cur_slot - 1+ behind = (not bars) or bars[-1]["slot"] < expected_last+ if behind:+ wait = every+ else:+ nxt = open_dt + datetime.timedelta(seconds=(cur_slot + 1) * step + GRACE)+ wait = (nxt - local).total_seconds()+ cutoff = datetime.datetime.combine(day, parse_hhmm(res.get("no_entries_after") or "15:30", "cutoff"))+ for stop_at in (until, cutoff, close_dt):+ if stop_at and stop_at > local:+ wait = min(wait, (stop_at - local).total_seconds())+ next_fetch = now + datetime.timedelta(seconds=max(1, wait))+++# ---------------------------------------------------------------- commands++def _opts(a, cfg):+ if a.side in ("sell", "short"):+ raise EntryError("v2 plans longs only: no short entries. Watch for a buy (--side buy) instead.")+ if a.setup == "orb" and a.level is not None:+ raise EntryError("--level is for --setup level (an orb's level is its range high)")+ if a.min_volume_x is not None and a.min_volume_x <= 0:+ raise EntryError("--min-volume-x must be above 0")+ if a.level is not None and a.level <= 0:+ raise EntryError("--level must be a price above 0")+ return {"setup": a.setup, "or_minutes": a.or_minutes, "interval": a.interval, "level": a.level,+ "min_volume_x": a.min_volume_x, "cfg": cfg}+++def _load(a, sym, now):+ """(chart, now). An offline file without --now is read as of its own time."""+ real_today = to_eastern(utc_now()).date()+ if a.offline and now is None:+ ch = get_chart(sym, a.interval, offline=a.offline)+ return ch, (utc_of(ch["data_time"]) if ch.get("data_time") else utc_now())+ now = now or utc_now()+ return get_chart(sym, a.interval, to_eastern(now).date(), a.offline, real_today), now+++def cmd_check(a):+ cfg = read_config(a.config)+ opts = _opts(a, cfg)+ sym = a.symbol.upper()+ chart, now = _load(a, sym, parse_now(a.now) if a.now else None)+ res = evaluate(chart, now, **opts)+ if a.write:+ write_json(a.write, entry_doc(res, now))+ if a.json:+ print(json.dumps(public(res), indent=2))+ else:+ for line in describe(res):+ print(line)+ if a.write:+ print("Wrote %s (status %s)." % (a.write, res["status"]))+ return 0 if res["status"] == "triggered" else 1+++def cmd_watch(a):+ cfg = read_config(a.config)+ opts = _opts(a, cfg)+ sym = a.symbol.upper()+ if a.every <= 0:+ raise EntryError("--every must be above 0 seconds")+ start = parse_now(a.now) if a.now else None+ if a.offline or start is not None:+ if start is None:+ start = _load(a, sym, None)[1]+ clock = SimClock(start)+ now_fn, sleep_fn = clock.now, clock.sleep+ else:+ now_fn, sleep_fn = utc_now, _sleep+ real_today = to_eastern(utc_now()).date()++ def provider(now):+ return get_chart(sym, a.interval, to_eastern(now).date(), a.offline, real_today)++ until = None+ if a.until:+ t = parse_hhmm(a.until, "--until")+ until = datetime.datetime.combine(to_eastern(now_fn()).date(), t)++ def on_trigger(res, now):+ write_json(a.out, entry_doc(res, now))+ print("Wrote %s." % a.out, flush=True)++ def emit(line):+ print(line, flush=True)++ code, _ = watch_loop(provider, now_fn, sleep_fn, emit, opts, every=a.every, until=until,+ on_trigger=on_trigger)+ return code+++def cmd_watchlist(a):+ cfg = read_config(a.config)+ opts = _opts(a, cfg)+ if not os.path.exists(a.watchlist):+ raise EntryError("no watchlist at %s: run /trader-scanner first (it writes the hits there)" % a.watchlist)+ try:+ with open(a.watchlist, encoding="utf-8") as fh:+ doc = json.load(fh)+ except ValueError as e:+ raise EntryError("%s is not valid JSON: %s" % (a.watchlist, e))+ hits = [h for h in (doc.get("hits") or []) if isinstance(h, dict) and h.get("symbol")]+ if not hits:+ raise EntryError("no hits in %s: the scanner found nothing to watch" % a.watchlist)+ if a.offline and not os.path.isdir(a.offline):+ raise EntryError("watchlist --offline wants a folder of <TICKER>.json files")+ now = parse_now(a.now) if a.now else None+ rows = []+ for i, h in enumerate(hits):+ sym = str(h["symbol"]).upper()+ o = dict(opts)+ if a.setup == "level" and o["level"] is None:+ o["level"] = h.get("level")+ try:+ if a.setup == "level" and o["level"] is None:+ raise EntryError("needs a level: --level PRICE or a \"level\" in the watchlist")+ if i and not a.offline:+ _sleep(PAUSE)+ chart, when = _load(a, sym, now)+ rows.append((sym, evaluate(chart, when, **o), None))+ except EntryError as e:+ rows.append((sym, None, str(e)))+ if a.json:+ print(json.dumps([{"symbol": s, "result": public(r) if r else None, "error": e} for s, r, e in rows], indent=2))+ else:+ print("%-6s %-9s %-8s %-8s %-9s %-9s %s" % ("SYMBOL", "STATUS", "TIME", "PRICE", "LEVEL", "LAST", "VS LEVEL"))+ for s, r, e in rows:+ if e:+ print("%-6s error: %s" % (s, e))+ continue+ t = r.get("trigger") or {}+ last = r.get("last") or {}+ status = SHORT.get(r["phase"], r["status"]) if r["status"] != "triggered" else "triggered"+ print("%-6s %-9s %-8s %-8s %-9s %-9s %s" % (+ s, status[:9], t.get("time") or "-", ("$%.2f" % t["price"]) if t else "-",+ ("$%.2f" % r["level"]) if r.get("level") is not None else "-",+ ("$%.2f" % last["close"]) if last else "-",+ ("%+.2f%%" % last["vs_level_pct"]) if last.get("vs_level_pct") is not None else "-"))+ n = sum(1 for _, r, _ in rows if r and r["status"] == "triggered")+ print("%d of %d triggered. Pick one, then: entry.py check <TICKER> --write, and /trader-exit." % (n, len(rows)))+ print("Free Yahoo bars, unofficial and can lag. Nothing was placed.")+ return 0 if any(r and r["status"] == "triggered" for _, r, _ in rows) else 1+++def main(argv=None):+ ap = argparse.ArgumentParser(description="Entry Timer (trader-entry): watches a setup bar by bar.")+ sub = ap.add_subparsers(dest="cmd")++ def common(p):+ p.add_argument("--setup", choices=["orb", "level"], default="orb")+ p.add_argument("--or-minutes", type=int, default=15, help="opening range length (default 15)")+ p.add_argument("--interval", choices=["5m", "1m"], default="5m")+ p.add_argument("--level", type=float, help="the price to close above (--setup level)")+ p.add_argument("--min-volume-x", type=float, help="trigger bar volume vs the range bars' average")+ p.add_argument("--side", default="buy", choices=["buy", "long", "sell", "short"], help="v2: buy only")+ p.add_argument("--now", help='pretend it is this New York time, e.g. "2026-10-19 10:15"')+ p.add_argument("--offline", metavar="PATH", help="saved Yahoo chart JSON (.json/.json.gz) or a folder")+ p.add_argument("--config", default="trader/config.json")++ p = sub.add_parser("check", help="the setup's status right now")+ p.add_argument("symbol")+ common(p)+ p.add_argument("--write", nargs="?", const="trader/entry.json", metavar="PATH",+ help="save the result (default trader/entry.json)")+ p.add_argument("--json", action="store_true")+ p = sub.add_parser("watch", help="poll bar by bar until it triggers or expires")+ p.add_argument("symbol")+ common(p)+ p.add_argument("--every", type=float, default=30, help="seconds between polls while Yahoo is behind")+ p.add_argument("--until", help="stop at this New York time (HH:MM)")+ p.add_argument("--out", default="trader/entry.json", help="where a trigger is written")+ p = sub.add_parser("watchlist", help="check every hit in trader/watchlist.json")+ common(p)+ p.add_argument("--watchlist", default="trader/watchlist.json")+ p.add_argument("--json", action="store_true")+ a = ap.parse_args(argv)+ if not a.cmd:+ ap.print_help()+ return 1+ try:+ return {"check": cmd_check, "watch": cmd_watch, "watchlist": cmd_watchlist}[a.cmd](a)+ except EntryError as e:+ print("entry.py: %s" % e, file=sys.stderr)+ return 1+ except KeyboardInterrupt:+ print("entry.py: stopped.", file=sys.stderr)+ return 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/trader-exit/SKILL.md b/trader-exit/SKILL.mdnew file mode 100644index 0000000..3ba6e92--- /dev/null+++ b/trader-exit/SKILL.md@@ -0,0 +1,132 @@+---+name: trader-exit+description: >-+ Exit Planner. Sets your stop and your target before you enter, so you know+ when to get out. Reads the entry from trader-entry (or a price you give),+ puts the stop at the opening-range midpoint by default (or the range low,+ your price, a percent, or a multiple of the ATR), rounds it down to the+ cent, and sets the target at 2R (or 1R, or your price). Refuses a stop at or+ above the entry, a target at or below it, or a stop too tight to survive the+ spread, and says why. Writes trader/plan.json for the Time Machine, the+ Budget Manager and Price Alerts. Long side only. Use when the user says+ "where's my stop", "set my stop and target", "plan the exit", "when do I get+ out", "stop loss", "what's my R", "risk reward", or right after+ /trader-entry triggers, before /trader-timemachine.+argument-hint: "[--stop or-mid|or-low|price:X|pct:X|atr:K] [--target 2R|1R|price:X]"+---++# trader-exit++The Exit Planner decides how a trade ends before it starts. The stop is where+the setup has failed. The target is where you take what you came for. Both+are set BEFORE the entry, written down and handed on, so nobody has to decide+anything in the middle of a fast move. A stop is a plan, not a guarantee: a+gap or a fast market can fill past it. Day trading loses most people money,+and a neat plan does not change that.++`${CLAUDE_SKILL_DIR}` below is this skill's folder (where this SKILL.md lives).++```bash+python3 "${CLAUDE_SKILL_DIR}/exit.py" plan # trader/entry.json: midpoint stop, 2R target+python3 "${CLAUDE_SKILL_DIR}/exit.py" plan --stop or-mid --target 1R --write+python3 "${CLAUDE_SKILL_DIR}/exit.py" plan --stop atr:1.5 # needs the session's bars (Yahoo or --offline)+python3 "${CLAUDE_SKILL_DIR}/exit.py" plan --symbol TSLA --entry 364.18 --or-high 362.18 --or-low 354.47+python3 "${CLAUDE_SKILL_DIR}/exit.py" show # the current trader/plan.json+```++Other flags: `--flat-by 15:55`, `--json`, `--now "2026-10-19 10:15"` (New+York time), `--entry PRICE` with a waiting entry.json to plan ahead, `--setup+level`, `--offline FILE` (a saved Yahoo chart JSON for an ATR stop).++## What it reads and writes++| file | what |+| --- | --- |+| `trader/entry.json` | the trigger from trader-entry: symbol, entry price, time, bar, opening range |+| `trader/config.json` | `flat_by` (15:55) and `min_reward_risk` (1.0: a note here, trader-risk enforces it) |+| Yahoo chart API | only for an `atr:K` stop: the session's bars up to the entry bar, free and unofficial |+| `trader/plan.json` | with `--write`: entry, stop and its rule, target and its R, risk a share, reward:risk, flat by. trader-timemachine, trader-budget and trader-alerts read it |++## Stops and targets++| stop | where it goes |+| --- | --- |+| `or-mid` | the opening-range midpoint (the default for an opening-range breakout) |+| `or-low` | the opening-range low: wider, so fewer shares for the same max loss |+| `price:X` | your price |+| `pct:X` | X percent under the entry |+| `atr:K` | K times the 14-bar ATR under the entry, on the session's bars up to the entry bar. With fewer than 14 bars by then it averages all of them and says so |++A level setup has no opening range to lean on, so it needs a stop you name.++- **Rounding.** The stop rounds AWAY from the entry to the cent (down, for a+ long). Risk = entry minus stop. Target = entry + R x risk, rounded half up+ to the cent. `2R` by default; `1R`, `1.5R` or `price:X` also work.+- **Refused, with the reason.** A stop at or above the entry. A target at or+ below it. A risk under 0.05% of the price: too tight to survive the+ spread, normal wiggle would stop you out. An entry.json that has not+ triggered (unless you give `--entry`). A short: v2 plans longs only.+- **Flat by.** 15:55 by default (or `flat_by` in the config). Out by then,+ win or lose, no overnight hold. On a 1:00 p.m. early close it moves up to+ 12:55. An entry at or after the flat-by time is refused.++## Steps++1. Run it right after `/trader-entry` triggers. Before that, `--entry PRICE`+ plans ahead at the level you expect.+2. Use the default stop for an opening-range breakout unless the user names+ another. A level setup needs one: ask.+3. Run `exit.py plan --write`. Read back the entry, the stop and its rule,+ the target and its rule, the risk a share, reward:risk and flat by.+4. If it refuses, say the reason and the fix (a wider stop, a farther+ target). Never loosen anything on your own.+5. Say once that the stop is a plan, not a guarantee.+6. Hand off to `/trader-timemachine` to replay the plan, then `/trader-budget`+ to size it to the max loss per trade. Offer `/trader-alerts` for the stop,+ the target and the flat-by time. Claude can keep `entry.py watch` running+ in the background or on a `/loop` until a setup triggers, then come here.++## Example: the reel++TSLA, Monday 2026-10-19. The entry is 364.18 at 10:15 AM (the 10:10 bar,+bar 8) and the opening range is 354.47 to 362.18. `exit.py plan --stop+or-mid --target 1R --write`:++```+Exit plan: TSLA long, Mon 2026-10-19, opening-range breakout on 5-minute bars+ Entry $364.18 at 10:15 AM (bar 8)+ Stop $358.32 opening-range midpoint: ($362.18 + $354.47) / 2 = $358.325, rounded down+ Target $370.04 1R (one times the risk)+ Risk a share $5.86 (1.61% of the entry)+ Reward:risk 1.0+ Flat by 15:55 ET, win or lose: no overnight hold+```++The default 2R target would be 364.18 + 2 x 5.86 = 375.90. trader-budget then+sizes it: a $50 max loss per trade buys floor(50 / 5.86) = 8 shares.++## Rules++- The stop and the target are set before the entry, never after.+- Never move a stop further from the entry once the trade is on.+- Plain numbers only: entry, stop, target, risk a share, reward:risk. It+ never prints a P&L or a return.+- Nothing here promises winning trades or money. A 1R target is not a+ prediction that the price gets there.+- Long side only. v2 plans longs only.++## What it never does++It never places an order, never sizes a position, never widens a stop to+make a plan pass, and never calls a stop a guarantee.++## Safety++- Education and tooling, not financial advice. A PASS is a rules check, not a recommendation.+- Paper trading by default (`"paper": true`). Going live is the user's own decision, in their own config.+- Nothing in this pack places an order except trader-broker, and only when all three hold: trader-risk+ passed that exact order today, the user typed an explicit yes for that one order in the chat, and the+ user clicked Allow once on Claude's own card because the order tool is set to "Needs approval"+ (Customize > Connectors > tool permissions). Never set an order tool to "Always allow".+- No options, margin, short selling or leverage unless the config allows it and the user confirms.+- Broker keys live in environment variables or the Claude Desktop config, never in the chat.diff --git a/trader-exit/exit.py b/trader-exit/exit.pynew file mode 100644index 0000000..e85a6ba--- /dev/null+++ b/trader-exit/exit.py@@ -0,0 +1,735 @@+#!/usr/bin/env python3+"""Exit Planner for trader-exit: sets the stop and the target BEFORE you+enter, so you know when to get out. Standard library only. Long side only.+It never places an order.++ python3 exit.py plan # from trader/entry.json: or-mid stop, 2R target+ python3 exit.py plan --stop or-mid --target 1R --write # the reel: stop 358.32, target 370.04+ python3 exit.py plan --symbol TSLA --entry 364.18 --or-high 362.18 --or-low 354.47+ python3 exit.py plan --stop atr:1.5 --offline TSLA.json # ATR needs the session's bars+ python3 exit.py plan --symbol NVDA --entry 190.25 --setup level --stop pct:1+ python3 exit.py show # the current trader/plan.json++Stops (a long's stop rounds DOWN to the cent, away from the entry):+ or-mid the opening-range midpoint (the default for an orb entry)+ or-low the opening-range low+ price:X your price+ pct:X X percent under the entry+ atr:K K times the 14-bar ATR under the entry, on the session's bars up+ to the entry bar (--offline FILE or Yahoo). With fewer than 14+ bars by then it averages all of them and says so.+ A level setup has no opening-range default: give a stop.++Targets (round half up to the cent):+ 2R (default), 1R, 1.5R ... entry + R x risk, where risk = entry - stop+ price:X your price++Refused, with the reason: a stop at or above the entry, a target at or below+it, a risk under 0.05% of the price (too tight to survive the spread), an+entry.json that has not triggered (unless you give --entry), a short (v2+plans longs only).++flat_by (default 15:55, or "flat_by" in trader/config.json): out by then, win+or lose. On a 1:00 p.m. early close it moves up with the close (12:55).+"min_reward_risk" in the config (default 1.0) only warns here; trader-risk+enforces it.++A stop is a plan, not a guarantee: a gap or a fast market can fill past it.+Exit codes: plan 0 = a plan, 1 = refused or an error. show 0 = a plan exists.+"""++import argparse+import datetime+import gzip+import json+import os+import re+import sys+import time+import urllib.error+import urllib.request+from decimal import Decimal, InvalidOperation, ROUND_FLOOR, ROUND_HALF_UP++UA = "Mozilla/5.0 (compatible; day-trader-skill/2.0; +https://github.com/Jakeschincariol/day-trader-skill)"+BACKOFF = 5.0+HOSTS = ("query2", "query1")+INTERVALS = {"1m": 60, "5m": 300}+DEFAULTS = {"flat_by": "15:55", "min_reward_risk": 1.0}+ATR_BARS = 14+MIN_RISK_PCT = Decimal("0.05") # risk under 0.05% of the price is inside the spread's noise+CENT = Decimal("0.01")+EPOCH = datetime.datetime(1970, 1, 1)+NOTE = "A stop is a plan, not a guarantee: a gap or a fast market can fill past it."++NYSE_HOLIDAYS = {+ "2026-01-01": "New Year's Day",+ "2026-01-19": "Martin Luther King, Jr. Day",+ "2026-02-16": "Washington's Birthday",+ "2026-04-03": "Good Friday",+ "2026-05-25": "Memorial Day",+ "2026-06-19": "Juneteenth National Independence Day",+ "2026-07-03": "Independence Day (observed)",+ "2026-09-07": "Labor Day",+ "2026-11-26": "Thanksgiving Day",+ "2026-12-25": "Christmas Day",+ "2027-01-01": "New Year's Day",+ "2027-01-18": "Martin Luther King, Jr. Day",+ "2027-02-15": "Washington's Birthday",+ "2027-03-26": "Good Friday",+ "2027-05-31": "Memorial Day",+ "2027-06-18": "Juneteenth National Independence Day (observed)",+ "2027-07-05": "Independence Day (observed)",+ "2027-09-06": "Labor Day",+ "2027-11-25": "Thanksgiving Day",+ "2027-12-24": "Christmas Day (observed)",+}+NYSE_EARLY_CLOSE = { # 1:00 p.m. ET+ "2026-11-27": "day after Thanksgiving",+ "2026-12-24": "Christmas Eve",+ "2027-11-26": "day after Thanksgiving",+}+OPEN = datetime.time(9, 30)+CLOSE = datetime.time(16, 0)+EARLY = datetime.time(13, 0)+++class PlanError(Exception):+ pass+++# ---------------------------------------------------------------- time++def _nth_sunday(year, month, n):+ d = datetime.date(year, month, 1)+ d += datetime.timedelta(days=(6 - d.weekday()) % 7)+ return d + datetime.timedelta(weeks=n - 1)+++def eastern_offset(utc):+ """Hours from UTC for New York: -4 in daylight time, -5 otherwise (US rule since 2007)."""+ y = utc.year+ start = datetime.datetime.combine(_nth_sunday(y, 3, 2), datetime.time(7, 0)) # 2:00 EST+ end = datetime.datetime.combine(_nth_sunday(y, 11, 1), datetime.time(6, 0)) # 2:00 EDT+ naive = utc.replace(tzinfo=None)+ return -4 if start <= naive < end else -5+++def to_eastern(utc):+ return utc.replace(tzinfo=None) + datetime.timedelta(hours=eastern_offset(utc))+++def eastern_to_utc(local):+ for off in (-4, -5):+ utc = local - datetime.timedelta(hours=off)+ if eastern_offset(utc) == off:+ return utc+ return local + datetime.timedelta(hours=5)+++def utc_now():+ return datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0, tzinfo=None)+++def utc_of(ts):+ return EPOCH + datetime.timedelta(seconds=int(ts))+++def parse_now(text):+ """--now -> naive UTC. A time without an offset is New York time."""+ if not text:+ return utc_now()+ t = text.strip()+ if t.upper().endswith(" ET"):+ t = t[:-3].strip()+ if re.match(r"^\d{1,2}:\d{2}$", t):+ t = "%s %s" % (to_eastern(utc_now()).date().isoformat(), t.zfill(5))+ t = t.replace("Z", "+00:00")+ try:+ dt = datetime.datetime.fromisoformat(t)+ except ValueError:+ raise PlanError('--now wants a New York time like "2026-10-19 10:15" (or ...Z for UTC)')+ if dt.tzinfo is None:+ return eastern_to_utc(dt)+ return (dt - dt.utcoffset()).replace(tzinfo=None)+++def parse_hhmm(text, what):+ m = re.match(r"^\s*(\d{1,2}):(\d{2})\s*$", str(text))+ if not m or int(m.group(1)) > 23 or int(m.group(2)) > 59:+ raise PlanError("%s wants a New York time like 15:55, not %r" % (what, text))+ return datetime.time(int(m.group(1)), int(m.group(2)))+++def parse_clock(text, what):+ """10:15 AM, 10:15, 3:05 PM -> time."""+ m = re.match(r"^\s*(\d{1,2}):(\d{2})\s*([AaPp][Mm])?\s*$", str(text))+ if not m:+ raise PlanError("%s wants a time like 10:15 AM, not %r" % (what, text))+ h, mi = int(m.group(1)), int(m.group(2))+ if m.group(3):+ if not 1 <= h <= 12:+ raise PlanError("%s wants a time like 10:15 AM, not %r" % (what, text))+ h = h % 12 + (12 if m.group(3).upper() == "PM" else 0)+ if h > 23 or mi > 59:+ raise PlanError("%s wants a time like 10:15 AM, not %r" % (what, text))+ return datetime.time(h, mi)+++def hm(t):+ return "%02d:%02d" % (t.hour, t.minute)+++def ampm(t):+ h = t.hour % 12 or 12+ return "%d:%02d %s" % (h, t.minute, "AM" if t.hour < 12 else "PM")+++def session(d):+ """(open_time, close_time) in New York time, or None if closed all day."""+ if d.weekday() >= 5 or d.isoformat() in NYSE_HOLIDAYS:+ return None+ return OPEN, (EARLY if d.isoformat() in NYSE_EARLY_CLOSE else CLOSE)+++# ---------------------------------------------------------------- money math (Decimal, to the cent)++def D(x, what="a number"):+ try:+ if isinstance(x, float):+ return Decimal(repr(x))+ return Decimal(str(x).strip().lstrip("$").replace(",", ""))+ except (InvalidOperation, ValueError):+ raise PlanError("%s is not a number: %r" % (what, x))+++def cents(x):+ """Round half up to the cent."""+ return D(x).quantize(CENT, rounding=ROUND_HALF_UP)+++def floor_cents(x):+ """A long's stop: round down, away from the entry."""+ return D(x).quantize(CENT, rounding=ROUND_FLOOR)+++def money(x):+ return "$%s" % format(D(x).quantize(CENT), ",f")+++def num(x):+ """1, 1.5, 2.25: a Decimal without trailing zeros."""+ s = format(D(x).normalize(), "f")+ return s+++def ratio(x):+ """reward:risk for people: 1.0, 1.5, 1.37."""+ s = "%.2f" % float(x)+ return s[:-1] if s.endswith("0") else s+++WORDS = {1: "one", 2: "two", 3: "three", 4: "four", 5: "five"}+++def parse_stop(text):+ t = str(text).strip().lower()+ if t in ("or-mid", "or_mid", "mid", "or-midpoint"):+ return "or_mid", None+ if t in ("or-low", "or_low", "low"):+ return "or_low", None+ m = re.match(r"^(price|pct|atr):\s*\$?([0-9][0-9,]*\.?[0-9]*)$", t)+ if not m:+ raise PlanError("--stop is or-mid, or-low, price:X, pct:X or atr:K (got %r)" % text)+ kind, val = m.group(1), D(m.group(2), "--stop")+ if val <= 0:+ raise PlanError("--stop %s needs a number above 0" % kind)+ if kind == "pct" and val >= 100:+ raise PlanError("--stop pct:X needs X under 100")+ return kind, val+++def parse_target(text):+ t = str(text).strip()+ m = re.match(r"^([0-9]*\.?[0-9]+)\s*[Rr]$", t)+ if m:+ r = D(m.group(1), "--target")+ if r <= 0:+ raise PlanError("--target needs an R multiple above 0, like 1R or 2R")+ return "r", r+ m = re.match(r"^price:\s*\$?([0-9][0-9,]*\.?[0-9]*)$", t.lower())+ if m:+ return "price", D(m.group(1), "--target")+ raise PlanError("--target is 2R, 1R, 1.5R ... or price:X (got %r)" % text)+++def r_label(r):+ n = int(r) if r == r.to_integral_value() else None+ return "%sR (%s times the risk)" % (num(r), WORDS.get(n, num(r)))+++def compute(entry, stop_rule, stop_param, target_rule, target_param, or_high=None, or_low=None,+ atr=None, atr_bars=None):+ """The stop, the target and the risk, in exact cents. Raises PlanError with the reason."""+ e = cents(entry)+ if e <= 0:+ raise PlanError("the entry price must be above $0")+ detail = ""+ if stop_rule in ("or_mid", "or_low"):+ if or_high is None or or_low is None:+ raise PlanError("an %s stop needs the opening range (--or-high and --or-low)" % stop_rule.replace("_", "-"))+ oh, ol = cents(or_high), cents(or_low)+ if oh <= ol:+ raise PlanError("the opening-range high %s must be above its low %s" % (money(oh), money(ol)))+ if stop_rule == "or_mid":+ raw = (oh + ol) / 2+ label = "opening-range midpoint"+ detail = "(%s + %s) / 2 = $%s" % (money(oh), money(ol), num(raw))+ else:+ raw, label = ol, "opening-range low"+ elif stop_rule == "price":+ raw, label = stop_param, "your price"+ elif stop_rule == "pct":+ raw = e * (1 - stop_param / 100)+ label = "%s%% under the entry" % num(stop_param)+ detail = "%s x (1 - %s%%) = $%s" % (money(e), num(stop_param), num(raw))+ elif stop_rule == "atr":+ if atr is None:+ raise PlanError("an atr stop needs the session's bars")+ a = D(round(atr, 6))+ raw = e - stop_param * a+ label = "%s x ATR(%d) under the entry" % (num(stop_param), atr_bars)+ detail = "ATR $%s over the %d bars to the entry%s" % (+ num(a.quantize(Decimal("0.0001"))), atr_bars, " (fewer than 14 so far)" if atr_bars < ATR_BARS else "")+ else:+ raise PlanError("unknown stop rule %r" % stop_rule)+ stop = floor_cents(raw)+ if stop != D(raw):+ detail = (detail + ", rounded down" if detail else "$%s rounded down" % num(raw))+ if stop >= e:+ raise PlanError("the stop %s (%s) is at or above the entry %s: a long's stop goes under the entry"+ % (money(stop), label, money(e)))+ if stop <= 0:+ raise PlanError("the stop works out to %s: pick a stop above $0" % money(stop))+ risk = e - stop+ floor_risk = e * MIN_RISK_PCT / 100+ if risk < floor_risk:+ raise PlanError("the stop is %s under the entry, less than 0.05%% of the price (%s on %s): too tight to "+ "survive the spread, normal wiggle would stop you out. Widen it."+ % (money(risk), money(floor_risk.quantize(CENT, rounding=ROUND_HALF_UP)), money(e)))+ if target_rule == "r":+ target = cents(e + target_param * risk)+ t_label = r_label(target_param)+ else:+ target = cents(target_param)+ t_label = None+ if target <= e:+ raise PlanError("the target %s is at or below the entry %s: a long's target goes above it"+ % (money(target), money(e)))+ rr = ((target - e) / risk).quantize(CENT, rounding=ROUND_HALF_UP)+ if t_label is None:+ t_label = "your price (%sR)" % ratio(rr)+ return {"entry": e, "stop": stop, "stop_label": label, "stop_detail": detail, "target": target,+ "target_r": target_param if target_rule == "r" else rr, "target_label": t_label,+ "risk": risk, "reward_risk": rr}+++# ---------------------------------------------------------------- bars for ATR (same reader as trader-entry)++def _open_url(url, timeout=20):+ req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "application/json"})+ with urllib.request.urlopen(req, timeout=timeout) as r:+ return r.read().decode("utf-8", "replace")+++def _sleep(seconds):+ time.sleep(seconds)+++def yahoo_get(path):+ """query2 first, query1 on 429 or 5xx; one retry after a pause on 429."""+ last = "no answer"+ for host in HOSTS:+ url = "https://%s.finance.yahoo.com%s" % (host, path)+ for attempt in (0, 1):+ try:+ return _open_url(url)+ except urllib.error.HTTPError as e:+ code, body = e.code, None+ try:+ if code == 404: # Yahoo says why in the body: an unknown ticker+ body = e.read().decode("utf-8", "replace")+ except Exception:+ body = None+ finally:+ e.close()+ if code == 404:+ if body:+ return body+ raise PlanError("Yahoo has no chart at %s (HTTP 404)" % url.split("?")[0])+ last = "HTTP %d" % code+ if code == 429 and attempt == 0:+ _sleep(BACKOFF)+ continue+ if code == 429 or code >= 500:+ break+ raise PlanError("Yahoo answered HTTP %d for %s" % (code, url.split("?")[0]))+ except urllib.error.URLError as e:+ last = "could not connect: %s" % (e.reason,)+ break+ except OSError as e:+ last = "network error: %s" % (e,)+ break+ raise PlanError("Yahoo did not answer (%s on query2 and query1): wait a minute and try again" % last)+++def read_text(path):+ if path.endswith(".gz"):+ with gzip.open(path, "rt", encoding="utf-8") as fh:+ return fh.read()+ with open(path, encoding="utf-8") as fh:+ return fh.read()+++def load_chart(sym, interval, day, offline=None):+ ysym = sym.upper().replace(".", "-")+ if offline:+ path = offline+ if os.path.isdir(offline):+ path = os.path.join(offline, ysym + ".json")+ if not os.path.exists(path):+ path += ".gz"+ if not os.path.exists(path):+ raise PlanError("no offline file %s" % path)+ try:+ text = read_text(path)+ except (OSError, ValueError) as e:+ raise PlanError("could not read %s: %s" % (path, e))+ else:+ back = (to_eastern(utc_now()).date() - day).days+ rng = "1d" if back <= 0 else "5d" if back <= 6 else "1mo" if back <= 28 else "60d"+ if interval == "1m" and back > 6:+ raise PlanError("Yahoo keeps 1-minute bars for about a week")+ text = yahoo_get("/v8/finance/chart/%s?range=%s&interval=%s" % (ysym, rng, interval))+ try:+ data = json.loads(text)+ res = data["chart"]["result"]+ except (ValueError, KeyError, TypeError):+ raise PlanError("Yahoo returned something unexpected for %s" % sym)+ if not res:+ err = (data.get("chart") or {}).get("error") or {}+ raise PlanError("Yahoo has no data for %s: %s" % (sym, err.get("description") or "unknown ticker"))+ r = res[0] or {}+ meta = r.get("meta") or {}+ if str(meta.get("symbol") or ysym).upper() != ysym:+ raise PlanError("the chart file holds %s, not %s" % (meta.get("symbol"), sym))+ q = ((r.get("indicators") or {}).get("quote") or [{}])[0] or {}++ def at(key, i):+ arr = q.get(key) or []+ return arr[i] if i < len(arr) else None++ bars = []+ for i, t in enumerate(r.get("timestamp") or []):+ c = at("close", i)+ if t is None or c is None:+ continue+ h, lo = at("high", i), at("low", i)+ bars.append({"t": int(t), "h": float(c if h is None else h), "l": float(c if lo is None else lo),+ "c": float(c)})+ return {"bars": bars, "data_time": meta.get("regularMarketTime")}+++def session_bars(chart, day, interval, upto_slot=None, now_utc=None):+ """Closed, on-grid bars of one New York session, oldest first (the live tick is dropped)."""+ step = INTERVALS[interval]+ s = session(day)+ if not s:+ return []+ open_dt = datetime.datetime.combine(day, s[0])+ close_dt = datetime.datetime.combine(day, s[1])+ if now_utc is None and chart.get("data_time"):+ now_utc = utc_of(chart["data_time"])+ local = to_eastern(now_utc) if now_utc else None+ out = {}+ for b in chart["bars"]:+ if b["t"] % step:+ continue+ et = to_eastern(utc_of(b["t"]))+ if et.date() != day or not (open_dt <= et < close_dt):+ continue+ if local and et + datetime.timedelta(seconds=step) > local:+ continue+ slot = int((et - open_dt).total_seconds()) // step+ if upto_slot is not None and slot > upto_slot:+ continue+ out[slot] = b+ return [out[k] for k in sorted(out)]+++def atr_of(bars, n=ATR_BARS):+ """Average true range of the last n bars (all of them if fewer). The first+ bar of the session uses its own high - low (no overnight gap)."""+ trs, prev = [], None+ for b in bars:+ tr = b["h"] - b["l"]+ if prev is not None:+ tr = max(tr, abs(b["h"] - prev), abs(b["l"] - prev))+ trs.append(tr)+ prev = b["c"]+ use = trs[-n:]+ return sum(use) / len(use), len(use)+++# ---------------------------------------------------------------- plan++def read_json(path, what):+ if not path or not os.path.exists(path):+ raise PlanError("no %s at %s" % (what, path))+ try:+ with open(path, encoding="utf-8") as fh:+ return json.load(fh)+ except ValueError as e:+ raise PlanError("%s is not valid JSON: %s" % (path, e))+++def read_config(path):+ cfg = dict(DEFAULTS)+ if path and os.path.exists(path):+ doc = read_json(path, "config")+ for k in DEFAULTS:+ if doc.get(k) is not None:+ cfg[k] = doc[k]+ return cfg+++def resolve_flat_by(day, explicit, cfg, entry_time):+ """(HH:MM, note). The config's flat-by moves up with a 1:00 p.m. early close."""+ t = parse_hhmm(explicit or cfg.get("flat_by") or DEFAULTS["flat_by"], "--flat-by" if explicit else "flat_by")+ note = ""+ s = session(day) if day else None+ if s:+ close_dt = datetime.datetime.combine(day, s[1])+ at = datetime.datetime.combine(day, t)+ if at >= close_dt:+ if explicit:+ raise PlanError("--flat-by %s is at or after the %s close on %s" % (hm(t), ampm(s[1]), day))+ moved = at - (datetime.datetime.combine(day, CLOSE) - close_dt)+ if moved.time() <= OPEN:+ raise PlanError("flat_by %s in the config is at or after the close" % hm(t))+ t = moved.time()+ note = "moved up for the 1:00 p.m. early close (%s)" % NYSE_EARLY_CLOSE.get(day.isoformat(), "")+ if entry_time and entry_time >= t:+ raise PlanError("the entry at %s is at or after your flat-by %s: there is no time left to hold it"+ % (ampm(entry_time), hm(t)))+ return hm(t), note+++def gather(a):+ """The entry facts, from trader/entry.json or the flags."""+ if a.symbol and a.from_path:+ raise PlanError("use --from or --symbol, not both")+ if a.side in ("sell", "short"):+ raise PlanError("v2 plans longs only: no stops above a short entry. Plan a buy instead.")+ if a.symbol:+ if a.entry is None:+ raise PlanError("--symbol needs --entry PRICE")+ if (a.or_high is None) != (a.or_low is None):+ raise PlanError("give both --or-high and --or-low, or neither")+ info = {"symbol": a.symbol.upper(), "entry": a.entry, "setup": a.setup or ("orb" if a.or_high is not None else "level"),+ "date": a.date, "entry_time": a.time, "entry_bar": a.entry_bar, "interval": a.interval or "5m",+ "or_high": a.or_high, "or_low": a.or_low, "or_minutes": a.or_minutes, "source": "flags"}+ else:+ path = a.from_path or "trader/entry.json"+ doc = read_json(path, "entry (run /trader-entry first, or give --symbol and --entry)")+ if str(doc.get("side") or "buy").lower() not in ("buy", "long"):+ raise PlanError("%s is a %s: v2 plans longs only" % (path, doc.get("side")))+ if doc.get("status") != "triggered" and a.entry is None:+ raise PlanError("%s says %s is %s, not triggered: plan once it triggers, or give --entry PRICE to plan ahead"+ % (path, doc.get("symbol"), doc.get("status") or "unknown"))+ orr = doc.get("opening_range") or {}+ info = {"symbol": str(doc.get("symbol") or "").upper(), "entry": a.entry if a.entry is not None else doc.get("price"),+ "setup": a.setup or doc.get("setup") or "orb", "date": a.date or doc.get("date"),+ "entry_time": a.time or (doc.get("time") if a.entry is None else None),+ "entry_bar": a.entry_bar if a.entry_bar is not None else (doc.get("bar_index") if a.entry is None else None),+ "interval": a.interval or doc.get("interval") or "5m",+ "or_high": a.or_high if a.or_high is not None else orr.get("high"),+ "or_low": a.or_low if a.or_low is not None else orr.get("low"),+ "or_minutes": orr.get("minutes") or a.or_minutes, "source": path}+ if not info["symbol"] or info["entry"] is None:+ raise PlanError("%s has no symbol or price" % path)+ if info["interval"] not in INTERVALS:+ raise PlanError("interval is 5m or 1m")+ return info+++def build_plan(a, now_utc):+ info = gather(a)+ cfg = read_config(a.config)+ stop_text = a.stop+ if not stop_text:+ if info["setup"] != "orb":+ raise PlanError("a %s setup has no opening-range stop to default to: give --stop price:X, pct:X or atr:K"+ % info["setup"])+ stop_text = "or-mid"+ stop_rule, stop_param = parse_stop(stop_text)+ target_rule, target_param = parse_target(a.target or "2R")+ day = None+ if info["date"]:+ try:+ day = datetime.date.fromisoformat(str(info["date"]))+ except ValueError:+ raise PlanError("date wants YYYY-MM-DD, not %r" % info["date"])+ else:+ day = to_eastern(now_utc).date()+ entry_time = parse_clock(info["entry_time"], "the entry time") if info["entry_time"] else None+ atr = atr_n = None+ if stop_rule == "atr":+ chart = load_chart(info["symbol"], info["interval"], day, a.offline)+ bars = session_bars(chart, day, info["interval"], info["entry_bar"], parse_now(a.now) if a.now else None)+ if len(bars) < 3:+ raise PlanError("an atr stop needs at least 3 closed %s bars of %s on %s by the entry; found %d"+ % (info["interval"], info["symbol"], day, len(bars)))+ atr, atr_n = atr_of(bars)+ c = compute(info["entry"], stop_rule, stop_param, target_rule, target_param, info["or_high"], info["or_low"],+ atr, atr_n)+ flat_by, flat_note = resolve_flat_by(day, a.flat_by, cfg, entry_time)+ orr = None+ if info["or_high"] is not None and info["or_low"] is not None:+ orr = {"high": float(cents(info["or_high"])), "low": float(cents(info["or_low"])),+ "minutes": int(info["or_minutes"] or 15)}+ plan = {"created_by": "trader-exit", "symbol": info["symbol"], "side": "buy", "date": day.isoformat(),+ "setup": info["setup"], "entry": float(c["entry"]),+ "entry_time": ampm(entry_time) if entry_time else None,+ "entry_bar": info["entry_bar"], "interval": info["interval"], "opening_range": orr,+ "stop": float(c["stop"]), "stop_rule": stop_rule, "stop_label": c["stop_label"],+ "target": float(c["target"]), "target_r": float(c["target_r"]), "target_label": c["target_label"],+ "risk_per_share": float(c["risk"]), "reward_risk": float(c["reward_risk"]), "flat_by": flat_by,+ "stop_detail": c["stop_detail"], "created_at": now_utc.strftime("%Y-%m-%dT%H:%M:%SZ"), "note": NOTE}+ if atr is not None:+ plan["atr"] = round(atr, 4)+ plan["atr_bars"] = atr_n+ warnings = []+ if flat_note:+ warnings.append("Flat-by %s: %s." % (flat_by, flat_note))+ mrr = cfg.get("min_reward_risk")+ try:+ if mrr is not None and c["reward_risk"] < D(mrr):+ warnings.append("Reward:risk %s is under your min_reward_risk %s in the config: trader-risk checks that."+ % (ratio(c["reward_risk"]), num(D(mrr))))+ except PlanError:+ pass+ today = to_eastern(now_utc).date()+ if day != today:+ warnings.append("This plan is for %s, not today (%s)." % (day.isoformat(), today.isoformat()))+ return plan, warnings+++def describe(plan):+ day = datetime.date.fromisoformat(plan["date"])+ setup = {"orb": "opening-range breakout", "level": "close above a level"}.get(plan["setup"], plan["setup"])+ e = D(plan["entry"])+ risk = D(plan["risk_per_share"])+ pct = (risk / e * 100).quantize(CENT, rounding=ROUND_HALF_UP)+ when = ""+ if plan.get("entry_time"):+ when = " at %s" % plan["entry_time"]+ if plan.get("entry_bar") is not None:+ when += " (bar %d)" % plan["entry_bar"]+ out = ["Exit plan: %s long, %s, %s on %s bars" % (+ plan["symbol"], day.strftime("%a %Y-%m-%d"), setup, "5-minute" if plan["interval"] == "5m" else "1-minute")]+ out.append(" Entry %s%s" % (money(plan["entry"]), when))+ out.append(" Stop %s %s%s" % (money(plan["stop"]), plan["stop_label"],+ (": " + plan["stop_detail"]) if plan.get("stop_detail") else ""))+ out.append(" Target %s %s" % (money(plan["target"]), plan["target_label"]))+ out.append(" Risk a share %s (%s%% of the entry)" % (money(plan["risk_per_share"]), pct))+ out.append(" Reward:risk %s" % ratio(plan["reward_risk"]))+ out.append(" Flat by %s ET, win or lose: no overnight hold" % plan["flat_by"])+ out.append("Set before the entry. If price hits the stop, you are out; never move it further away.")+ out.append(NOTE)+ return out+++def cmd_plan(a):+ now = parse_now(a.now)+ plan, warnings = build_plan(a, now)+ if a.write:+ d = os.path.dirname(a.write)+ if d:+ os.makedirs(d, exist_ok=True)+ with open(a.write, "w", encoding="utf-8") as fh:+ json.dump(plan, fh, indent=2)+ fh.write("\n")+ if a.json:+ print(json.dumps(dict(plan, warnings=warnings), indent=2))+ return 0+ for line in describe(plan):+ print(line)+ for w in warnings:+ print("Note: " + w)+ if a.write:+ print("Wrote %s." % a.write)+ print("Next: /trader-timemachine replays it, then /trader-budget sizes it to your max loss. Nothing was placed.")+ return 0+++def cmd_show(a):+ if not os.path.exists(a.plan):+ print("No plan at %s yet. Make one: exit.py plan --write" % a.plan)+ return 1+ plan = read_json(a.plan, "plan")+ for k in ("symbol", "date", "entry", "stop", "target", "risk_per_share", "reward_risk", "flat_by"):+ if plan.get(k) is None:+ raise PlanError("%s is missing %r: make a new plan with exit.py plan --write" % (a.plan, k))+ if a.json:+ print(json.dumps(plan, indent=2))+ return 0+ for line in describe(dict({"setup": "orb", "interval": "5m", "stop_label": "", "target_label": ""}, **plan)):+ print(line)+ today = to_eastern(parse_now(a.now)).date().isoformat()+ if plan["date"] != today:+ print("Note: this plan is for %s, not today (%s)." % (plan["date"], today))+ return 0+++def main(argv=None):+ ap = argparse.ArgumentParser(description="Exit Planner (trader-exit): the stop and target before the entry.")+ sub = ap.add_subparsers(dest="cmd")+ p = sub.add_parser("plan", help="set the stop and target")+ p.add_argument("--from", dest="from_path", metavar="PATH", help="entry.json to plan from (default trader/entry.json)")+ p.add_argument("--symbol")+ p.add_argument("--entry", type=float, help="entry price (or a plan-ahead price with --from)")+ p.add_argument("--or-high", type=float)+ p.add_argument("--or-low", type=float)+ p.add_argument("--or-minutes", type=int, default=15)+ p.add_argument("--setup", choices=["orb", "level"])+ p.add_argument("--date", help="session date YYYY-MM-DD (default: the entry's, or today)")+ p.add_argument("--time", help="entry time, e.g. 10:15 AM")+ p.add_argument("--entry-bar", type=int)+ p.add_argument("--interval", choices=["5m", "1m"])+ p.add_argument("--side", default="buy", choices=["buy", "long", "sell", "short"], help="v2: buy only")+ p.add_argument("--stop", help="or-mid (orb default), or-low, price:X, pct:X, atr:K")+ p.add_argument("--target", help="2R (default), 1R, 1.5R, price:X")+ p.add_argument("--flat-by", help="HH:MM New York (default: config flat_by, 15:55)")+ p.add_argument("--config", default="trader/config.json")+ p.add_argument("--offline", metavar="PATH", help="saved Yahoo chart JSON for an atr stop")+ p.add_argument("--now", help='pretend it is this New York time, e.g. "2026-10-19 10:15"')+ p.add_argument("--write", nargs="?", const="trader/plan.json", metavar="PATH",+ help="save the plan (default trader/plan.json)")+ p.add_argument("--json", action="store_true")+ p = sub.add_parser("show", help="print the current plan")+ p.add_argument("--plan", default="trader/plan.json")+ p.add_argument("--now")+ p.add_argument("--json", action="store_true")+ a = ap.parse_args(argv)+ if not a.cmd:+ ap.print_help()+ return 1+ try:+ return {"plan": cmd_plan, "show": cmd_show}[a.cmd](a)+ except PlanError as e:+ print("exit.py: %s" % e, file=sys.stderr)+ return 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/trader-news/SKILL.md b/trader-news/SKILL.mdnew file mode 100644index 0000000..45c4d61--- /dev/null+++ b/trader-news/SKILL.md@@ -0,0 +1,104 @@+---+name: trader-news+description: >-+ News Monitor. Tracks breaking news on every stock you watch and flags what+ moves it: Yahoo Finance headlines per ticker, each company's 8-K filings on+ SEC EDGAR (earnings, CEO changes, deals, restatements, bankruptcy) and how+ far each stock is from yesterday's close. Shows only what is new since the+ last check, newest first, in New York time, tags each item (earnings,+ analyst, deal, halt, regulatory, macro...) and never repeats one. Use when+ the user says "any news on TSLA", "why is this moving", "what's the news on+ my watchlist", "morning briefing", "pre-market news", "monitor the news",+ "did anything break", "check the 8-Ks", or after /trader-scanner finds setups.+argument-hint: "[tickers]"+---++# trader-news++A chart can look perfect and still be about to gap on an earnings date, a+halt or a lawsuit. Before a setup becomes a trade, this skill reads the two+feeds that carry those first, for every stock on the watchlist, and tells you+only what is new. It also prints how far each stock has moved today, so a+headline and a move sit side by side.++Tool in this folder (standard library Python, no keys):++```bash+python3 "${CLAUDE_SKILL_DIR}/news.py" # watchlist + plan + portfolio+python3 "${CLAUDE_SKILL_DIR}/news.py" --tickers TSLA NVDA --hours 12+python3 "${CLAUDE_SKILL_DIR}/news.py" --no-sec --json+```++## What it reads and writes++| file / feed | what |+| --- | --- |+| `--tickers`, else `trader/watchlist.json` | the scanner's hits (trader-scanner) |+| `trader/plan.json` | the trade you are planning (trader-exit) |+| `trader/portfolio.json` | what you hold (trader-broker records fills there) |+| Yahoo Finance headline RSS | `https://feeds.finance.yahoo.com/rss/2.0/headline?s=TSLA®ion=US&lang=en-US` |+| Yahoo Finance chart endpoint | the last price against yesterday's close (unofficial, can lag) |+| SEC EDGAR company Atom feed | 8-K by default (`--forms 8-K,10-Q` for more); needs `sec_user_agent` in `trader/config.json` or `SEC_USER_AGENT`, else filings are skipped with a note |+| `trader/state/news.json` | what has been shown (kept 30 days) and each ticker's CIK |++## The rules++- **Headlines are leads, not facts.** Before telling the user something+ happened, open the story or the filing and read it. Quote the source and+ link it. Never summarise a paywalled story you could not read: say so.+- **Filings beat headlines.** If an 8-K and a headline disagree, the 8-K is+ what the company told the SEC.+- **Say what it touches.** Every item lists the tickers it touches and its+ tags: earnings, analyst, legal, deal, capital, people, risk, halt,+ regulatory, macro. Filings marked `!` carry an important 8-K item: earnings+ results (2.02), an officer change (5.02), an impairment (2.06), a delisting+ notice (3.01), past financials no longer reliable (4.02), bankruptcy (1.03)+ or a cyber incident (1.05).+- **MOVING** marks a stock 3 % or more from yesterday's close (`--move-pct`).+ A move with no headline is worth saying out loud too.+- **No predictions.** Report what was published and how far the price is from+ yesterday's close. Never say what the stock will do next.++## Steps++1. Run the check: `python3 "${CLAUDE_SKILL_DIR}/news.py"`. Exit code 1 means+ nothing new. `--all` shows items already seen, `--json` gives everything+ machine readable, `--dry-run` leaves the state alone.+2. Read the items that matter: every `!` filing, anything tagged earnings,+ halt, legal, regulatory or risk, and every MOVING ticker first.+3. Write a short brief, per ticker: what happened, the source and link, the+ move, and one line on why it matters to the setup (for example "earnings+ are this week: an overnight gap can jump past any stop").+4. If a story changes the picture, say so before `/trader-entry` and+ `/trader-exit`: an earnings date inside the trade, a halt, an offering.+ Never act on a headline alone.++During the session: `/loop 15m /trader-news`, or a scheduled task each+morning before the open.++## Example: the reel++Monday 2026-10-19, TSLA broke its opening range at 10:15 AM ET. The check at+10:15 (Yahoo Finance's TSLA feed, 16 headlines since 8:00) leads with the+morning's real stories: "Meta and Musk earnings and September pending home+sales: What to Watch" (8:00, earnings), "Tesla-SpaceX Merger Mania Strikes+Wall Street Ahead of Earnings" (8:04, earnings, deal), "Tech Stock Rebound+Nudges US Equity Futures Mostly Higher Pre-Bell" (8:02, macro). The brief:+"Tesla reports this week, so the stock can gap overnight; today's trade is+in and out before the close. No new 8-K." At 10:52 the price line reads+`TSLA 366.48 +3.31% vs yesterday's close 354.72 at 10:52 ET MOVING`. When a+ticker has no news, say so rather than padding the brief.++## What it never does++- Never invents or embellishes a story, a quote or a number.+- Never trades on news, and never tells the user to buy or sell because of a+ headline.+- Never hammers a server: one request per feed per ticker, a pause between+ calls, and SEC's 10 requests a second limit stays far away.++## Safety++Education and tooling, not financial advice. This skill only reads and+reports. Nothing places an order except `/trader-broker`, after+`/trader-risk` passes and the user types an explicit yes for that order.diff --git a/trader-news/news.py b/trader-news/news.pynew file mode 100644index 0000000..a9fdfe9--- /dev/null+++ b/trader-news/news.py@@ -0,0 +1,546 @@+#!/usr/bin/env python3+"""News monitor for trader-news. Standard library only.++Watches headlines and SEC filings for the stocks you watch or hold and+prints only what is new since the last check, newest first, with how far each+stock has moved today and a flag on anything that touches your tickers.++ python3 news.py # watchlist + plan + portfolio tickers+ python3 news.py --tickers TSLA NVDA AMD+ python3 news.py --tickers TSLA --all --hours 72 # everything in the last 3 days, seen or not+ python3 news.py --no-sec # headlines only+ python3 news.py --no-moves # skip the price line per ticker++Your tickers, when --tickers is not given: every hit in trader/watchlist.json+(trader-scanner), the symbol in trader/plan.json (trader-exit) and the+positions in trader/portfolio.json.++Sources, one request each per ticker:+ - Yahoo Finance headline RSS:+ https://feeds.finance.yahoo.com/rss/2.0/headline?s=<TICKER>®ion=US&lang=en-US+ - SEC EDGAR filings Atom feed for the company (8-K by default: earnings,+ executive changes, deals, restatements):+ https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=<CIK>&type=8-K&count=10&output=atom+ SEC needs a User-Agent with your name and email (sec_user_agent in+ trader/config.json or SEC_USER_AGENT). Without one the SEC part is skipped+ and the tool says so; headlines still run.++ - The move: Yahoo Finance's chart endpoint (unofficial, can lag), the last+ price against yesterday's close:+ https://query2.finance.yahoo.com/v8/finance/chart/<TICKER>?range=1d&interval=5m++Times print in New York time (ET). State: trader/state/news.json remembers+what you have seen (30 days), so an item shows once. Offline: --offline DIR+reads yahoo-<TICKER>.xml, chart-<TICKER>.json, sec-<FORM>-<CIK>.xml and+company_tickers.json from DIR. The tests use it.++Headlines are leads, not facts: open the story before acting, and treat+nothing here as advice.+"""++import argparse+import datetime as _dt+import email.utils+import gzip+import hashlib+import json+import os+import re+import sys+import time+import urllib.error+import urllib.request+import xml.etree.ElementTree as ET++YAHOO = "https://feeds.finance.yahoo.com/rss/2.0/headline?s=%s®ion=US&lang=en-US"+CHART = "https://%s.finance.yahoo.com/v8/finance/chart/%s?range=1d&interval=5m"+SEC_FEED = ("https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=%s&type=%s"+ "&dateb=&owner=include&count=%d&output=atom")+TICKERS_URL = "https://www.sec.gov/files/company_tickers.json"+PLACEHOLDER = "[email protected]"+BROWSER_UA = "Mozilla/5.0 (compatible; day-trader-skill/2.0; +https://github.com/Jakeschincariol/day-trader-skill)"+KEEP_DAYS = 30+MOVE_PCT = 3.0 # a stock this far from yesterday's close is flagged as moving++ITEMS_8K = {+ "1.01": "material agreement", "1.02": "agreement ended", "1.03": "bankruptcy",+ "1.05": "cybersecurity incident", "2.01": "acquisition or sale of assets",+ "2.02": "earnings results", "2.03": "new debt", "2.04": "debt acceleration",+ "2.05": "restructuring costs", "2.06": "impairment", "3.01": "delisting notice",+ "3.02": "unregistered share sale", "3.03": "shareholder rights change",+ "4.01": "auditor change", "4.02": "past financials no longer reliable",+ "5.01": "change in control", "5.02": "director or officer change",+ "5.03": "bylaws or fiscal year change", "5.07": "shareholder vote results",+ "7.01": "Regulation FD disclosure", "8.01": "other events", "9.01": "exhibits",+}+IMPORTANT_ITEMS = {"1.03", "1.05", "2.02", "2.04", "2.06", "3.01", "4.02", "5.01", "5.02"}+KEYWORDS = [+ ("earnings", r"\bearnings\b|\bresults\b|\bEPS\b|\bguidance\b|\bforecast\b"),+ ("analyst", r"\bupgrade[sd]?\b|\bdowngrade[sd]?\b|price target|\boutperform\b|\bunderperform\b"),+ ("legal", r"\blawsuit\b|\bsued\b|\bprobe\b|\binvestigation\b|\bSEC charges\b|\bantitrust\b|\bjudge\b|\bcourt\b"),+ ("deal", r"\bacqui(?:re|res|red|sition)\b|\bmerger\b|\bbuyout\b|\btakeover\b|\bdeal\b"),+ ("capital", r"\bdividend\b|\bbuyback\b|\brepurchase\b|\bstock split\b|\boffering\b"),+ ("people", r"\bCEO\b|\bCFO\b|\bresign|\bsteps down\b|\bappoint"),+ ("risk", r"\brecall\b|\bbankrupt|\bdefault\b|\bdelist|\bhack|\bbreach\b|\boutage\b"),+ ("halt", r"\bhalt(?:s|ed)?\b|\btrading (?:pause|suspen)"),+ ("regulatory", r"\bFDA\b|\bapproval\b|\bapproves\b|\bclinical\b|\bFTC\b|\bDOJ\b"),+ ("macro", r"\bFed\b|\bFOMC\b|\bCPI\b|\binflation\b|\bjobs report\b|\bpayrolls\b|\btariffs?\b|\bfutures\b"),+]+++class NewsError(Exception):+ pass+++# ---------------------------------------------------------------- time++def _nth_sunday(year, month, n):+ d = _dt.date(year, month, 1)+ d += _dt.timedelta(days=(6 - d.weekday()) % 7)+ return d + _dt.timedelta(weeks=n - 1)+++def eastern_offset(utc):+ """Hours from UTC for New York: -4 in daylight time, -5 otherwise (US rule since 2007)."""+ y = utc.year+ start = _dt.datetime.combine(_nth_sunday(y, 3, 2), _dt.time(7, 0)) # 2:00 EST+ end = _dt.datetime.combine(_nth_sunday(y, 11, 1), _dt.time(6, 0)) # 2:00 EDT+ naive = utc.replace(tzinfo=None)+ return -4 if start <= naive < end else -5+++def to_eastern(utc):+ """Aware or naive UTC -> naive New York wall-clock time."""+ if utc.tzinfo is not None:+ utc = utc.astimezone(_dt.timezone.utc)+ return utc.replace(tzinfo=None) + _dt.timedelta(hours=eastern_offset(utc))+++# ---------------------------------------------------------------- inputs++def load_json(path):+ if path and os.path.isfile(path):+ with open(path, encoding="utf-8") as fh:+ return json.load(fh)+ return None+++def watch_from_files(portfolio="trader/portfolio.json", watchlist="trader/watchlist.json",+ plan="trader/plan.json"):+ """{ticker: name or None}: the scanner's hits, the planned trade and your holdings."""+ out = {}+ wl = load_json(watchlist) or {}+ for h in wl.get("hits", []):+ sym = h.get("symbol") or h.get("ticker")+ if sym:+ out[sym.upper()] = h.get("name")+ pl = load_json(plan) or {}+ if pl.get("symbol"):+ out.setdefault(pl["symbol"].upper(), pl.get("name"))+ pf = load_json(portfolio) or {}+ for p in pf.get("positions", []):+ sym = p.get("ticker") or p.get("symbol")+ if sym:+ out[sym.upper()] = p.get("name") or out.get(sym.upper())+ return out+++def sec_user_agent(cli=None, config="trader/config.json"):+ ua = (cli or os.environ.get("SEC_USER_AGENT") or "").strip()+ if not ua:+ cfg = load_json(config) or {}+ ua = str(cfg.get("sec_user_agent") or "").strip()+ if not ua or "@" not in ua or PLACEHOLDER in ua:+ return None+ return ua+++# ---------------------------------------------------------------- fetching++class Fetcher(object):+ def __init__(self, sec_ua=None, offline=None, pause=0.15):+ self.sec_ua = sec_ua+ self.offline = offline+ self.pause = pause+ self._last = 0.0++ def get(self, url, name, sec=False):+ if self.offline:+ path = os.path.join(self.offline, name)+ if not os.path.isfile(path):+ raise NewsError("offline: no file %s" % path)+ with open(path, "rb") as fh:+ return fh.read()+ if sec and not self.sec_ua:+ raise NewsError("no SEC User-Agent set")+ gap = time.time() - self._last+ if gap < self.pause:+ time.sleep(self.pause - gap)+ self._last = time.time()+ headers = {"User-Agent": self.sec_ua if sec else BROWSER_UA, "Accept-Encoding": "gzip"}+ req = urllib.request.Request(url, headers=headers)+ try:+ with urllib.request.urlopen(req, timeout=30) as resp:+ data = resp.read()+ if resp.headers.get("Content-Encoding") == "gzip":+ data = gzip.decompress(data)+ return data+ except urllib.error.HTTPError as exc:+ raise NewsError("HTTP %s for %s" % (exc.code, url))+ except urllib.error.URLError as exc:+ raise NewsError("could not reach %s: %s" % (url, exc.reason))+++def yahoo_symbol(ticker):+ return ticker.upper().replace(".", "-")+++def cik_map(fetcher, state):+ """ticker -> 10-digit CIK, from SEC's company_tickers.json (cached in state)."""+ cached = state.setdefault("ciks", {})+ if cached:+ return cached+ data = json.loads(fetcher.get(TICKERS_URL, "company_tickers.json", sec=True).decode("utf-8"))+ for v in data.values():+ cached.setdefault(v["ticker"].upper().replace("-", "."), str(v["cik_str"]).zfill(10))+ return cached+++# ---------------------------------------------------------------- parsing++def _local(tag):+ return tag.rsplit("}", 1)[-1]+++def _text(el, name):+ for c in el.iter():+ if _local(c.tag) == name:+ return (c.text or "").strip()+ return ""+++def parse_time(value):+ """RFC 822 (RSS) or ISO 8601 (Atom) -> aware UTC datetime, or None."""+ value = (value or "").strip()+ if not value:+ return None+ try:+ d = email.utils.parsedate_to_datetime(value)+ except (TypeError, ValueError, IndexError):+ d = None+ if d is None:+ try:+ d = _dt.datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+ if d.tzinfo is None:+ d = d.replace(tzinfo=_dt.timezone.utc)+ return d.astimezone(_dt.timezone.utc)+++def parse_rss(data, ticker):+ """Yahoo headline RSS -> items."""+ try:+ root = ET.fromstring(data)+ except ET.ParseError as exc:+ raise NewsError("RSS for %s is not valid XML: %s" % (ticker, exc))+ out = []+ for it in root.iter("item"):+ title = _text(it, "title")+ link = _text(it, "link")+ guid = _text(it, "guid") or link+ out.append({"id": "rss:" + guid, "source": "Yahoo Finance", "kind": "headline",+ "ticker": ticker, "title": title, "summary": _text(it, "description"),+ "link": link, "time": parse_time(_text(it, "pubDate"))})+ return out+++def parse_sec_atom(data, ticker):+ """EDGAR company filings Atom -> items."""+ try:+ root = ET.fromstring(data)+ except ET.ParseError as exc:+ raise NewsError("SEC feed for %s is not valid XML: %s" % (ticker, exc))+ company = ""+ for el in root.iter():+ if _local(el.tag) == "conformed-name":+ company = (el.text or "").strip()+ break+ out = []+ for entry in root.iter():+ if _local(entry.tag) != "entry":+ continue+ form = _text(entry, "filing-type")+ acc = _text(entry, "accession-number")+ items = re.findall(r"\d+\.\d+", _text(entry, "items-desc"))+ labels = [ITEMS_8K.get(i, "item " + i) for i in items if i != "9.01"]+ link = ""+ for c in entry.iter():+ if _local(c.tag) == "link":+ link = c.get("href", "")+ title = "%s filed a %s" % (company or ticker, form)+ if labels:+ title += ": " + ", ".join(labels)+ out.append({"id": "sec:" + acc, "source": "SEC EDGAR", "kind": "filing", "form": form,+ "ticker": ticker, "title": title, "summary": _text(entry, "form-name"),+ "items": items, "important": bool(set(items) & IMPORTANT_ITEMS),+ "link": link, "time": parse_time(_text(entry, "updated"))})+ return out+++def parse_chart(data, ticker):+ """Yahoo chart JSON -> {"ticker", "price", "prev_close", "pct", "time"} or raise."""+ try:+ doc = json.loads(data.decode("utf-8") if isinstance(data, bytes) else data)+ meta = doc["chart"]["result"][0]["meta"]+ except (ValueError, KeyError, IndexError, TypeError):+ raise NewsError("chart for %s is not usable" % ticker)+ price = meta.get("regularMarketPrice")+ prev = meta.get("chartPreviousClose") or meta.get("previousClose")+ if not price or not prev:+ raise NewsError("chart for %s has no price" % ticker)+ when = meta.get("regularMarketTime")+ return {"ticker": ticker, "price": round(float(price), 2), "prev_close": round(float(prev), 2),+ "pct": round((float(price) / float(prev) - 1) * 100, 2),+ "time": _dt.datetime.fromtimestamp(when, _dt.timezone.utc) if when else None}+++def collect_moves(fetcher, watch, errors=None):+ errors = [] if errors is None else errors+ out = []+ for t in sorted(watch):+ name = "chart-%s.json" % t+ try:+ try:+ data = fetcher.get(CHART % ("query2", yahoo_symbol(t)), name)+ except NewsError as exc:+ if fetcher.offline or not re.search(r"HTTP (429|5\d\d)", str(exc)):+ raise+ data = fetcher.get(CHART % ("query1", yahoo_symbol(t)), name)+ out.append(parse_chart(data, t))+ except NewsError as exc:+ if not (fetcher.offline and "no file" in str(exc)):+ errors.append("price for %s: %s" % (t, exc))+ return out+++def mention_patterns(watch):+ pats = {}+ for t, name in watch.items():+ alts = [r"\(%s\)" % re.escape(t), r"\$%s\b" % re.escape(t),+ r"\b(?:NYSE|NASDAQ|Nasdaq)\s*:\s*%s\b" % re.escape(t)]+ if name and len(name) >= 4:+ alts.append(r"\b%s\b" % re.escape(name).replace(r"\ ", r"[\s-]"))+ pats[t] = re.compile("|".join(alts))+ return pats+++def tag(items, watch):+ """Which of your tickers each item touches, and why it matters."""+ pats = mention_patterns(watch)+ for it in items:+ hay = "%s %s" % (it["title"], it.get("summary") or "")+ touches = {it["ticker"]} if it["ticker"] in watch else set()+ for t, rx in pats.items():+ if rx.search(hay):+ touches.add(t)+ it["touches"] = sorted(touches)+ it["tags"] = [label for label, rx in KEYWORDS if re.search(rx, hay, re.I)]+ if it["kind"] == "filing" and "2.02" in it.get("items", []) and "earnings" not in it["tags"]:+ it["tags"].insert(0, "earnings")+ return items+++def dedupe(items):+ """One item per story: same id, or same link, or same title the same day."""+ seen, out = {}, []+ for it in items:+ keys = [it["id"], it["link"],+ "%s|%s" % (re.sub(r"\W+", " ", it["title"].lower()).strip(),+ it["time"].date() if it["time"] else "")]+ hit = next((seen[k] for k in keys if k and k in seen), None)+ if hit is not None:+ for t in it.get("touches", []):+ if t not in hit["touches"]:+ hit["touches"].append(t)+ hit["touches"].sort()+ continue+ for k in keys:+ if k:+ seen[k] = it+ out.append(it)+ return out+++def fingerprint(it):+ return hashlib.sha1(it["id"].encode("utf-8")).hexdigest()[:16]+++# ---------------------------------------------------------------- the check++def collect(fetcher, watch, state, sec=True, forms=("8-K",), count=10, errors=None):+ errors = [] if errors is None else errors+ items = []+ for t in sorted(watch):+ try:+ items += parse_rss(fetcher.get(YAHOO % yahoo_symbol(t), "yahoo-%s.xml" % t), t)+ except NewsError as exc:+ errors.append("headlines for %s: %s" % (t, exc))+ if sec:+ try:+ ciks = cik_map(fetcher, state)+ except NewsError as exc:+ errors.append("SEC ticker list: %s" % exc)+ ciks = {}+ for t in sorted(watch):+ cik = ciks.get(t)+ if not cik:+ if ciks:+ errors.append("no SEC CIK for %s" % t)+ continue+ for form in forms:+ try:+ data = fetcher.get(SEC_FEED % (cik, form, count),+ "sec-%s-%s.xml" % (form, cik), sec=True)+ items += parse_sec_atom(data, t)+ except NewsError as exc:+ errors.append("SEC %s for %s: %s" % (form, t, exc))+ return items+++def select(items, state, now, hours=48, show_all=False):+ """Items within the window; only unseen ones unless show_all."""+ seen = state.setdefault("seen", {})+ cutoff = now - _dt.timedelta(hours=hours)+ ahead = now + _dt.timedelta(minutes=10) # a pinned --now: nothing from after it+ out = []+ for it in items:+ if it["time"] is not None and (it["time"] < cutoff or it["time"] > ahead):+ continue+ fp = fingerprint(it)+ it["new"] = fp not in seen+ if it["new"] or show_all:+ out.append(it)+ out.sort(key=lambda i: (i["time"] or now), reverse=True)+ return out+++def remember(items, state, now):+ seen = state.setdefault("seen", {})+ stamp = now.isoformat()+ for it in items:+ seen.setdefault(fingerprint(it), stamp)+ cutoff = (now - _dt.timedelta(days=KEEP_DAYS)).isoformat()+ state["seen"] = {k: v for k, v in seen.items() if v >= cutoff}+ state["last_check"] = stamp+++def render_moves(moves, move_pct=MOVE_PCT):+ out = []+ for m in moves:+ flag = "MOVING" if abs(m["pct"]) >= move_pct else ""+ when = (" at %s ET" % to_eastern(m["time"]).strftime("%H:%M")) if m.get("time") else ""+ out.append("%-6s %s %+.2f%% vs yesterday's close %s%s %s" % (+ m["ticker"], "{:,.2f}".format(m["price"]), m["pct"], "{:,.2f}".format(m["prev_close"]),+ when, flag))+ return out+++def render(items, errors, now, moves=None, move_pct=MOVE_PCT):+ out = render_moves(moves or [], move_pct)+ if out:+ out.append("")+ if not items:+ out.append("Nothing new.")+ for it in items:+ when = to_eastern(it["time"]).strftime("%Y-%m-%d %H:%M ET") if it["time"] else "time unknown"+ mark = "!" if it.get("important") else " "+ who = ",".join(it["touches"]) or it["ticker"]+ out.append("%s %s %-11s %-13s %s" % (mark, when, who, it["source"], it["title"]))+ extra = []+ if it["tags"]:+ extra.append("tags: " + ", ".join(it["tags"]))+ extra.append(it["link"])+ out.append(" " + " ".join(extra))+ for e in errors:+ out.append("note: %s" % e)+ out.append("Checked %s. Headlines are leads, not facts; open the story before acting. "+ "Not financial advice." % to_eastern(now).strftime("%Y-%m-%d %H:%M ET"))+ return "\n".join(out) + "\n"+++def _json_ready(items):+ out = []+ for it in items:+ d = dict(it)+ d["time"] = it["time"].isoformat() if it["time"] else None+ out.append(d)+ return out+++def main(argv=None):+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])+ ap.add_argument("--tickers", nargs="*", help="default: watchlist + plan + portfolio")+ ap.add_argument("--portfolio", default="trader/portfolio.json")+ ap.add_argument("--watchlist", default="trader/watchlist.json")+ ap.add_argument("--plan", default="trader/plan.json")+ ap.add_argument("--state", default="trader/state/news.json")+ ap.add_argument("--hours", type=float, default=48, help="ignore items older than this")+ ap.add_argument("--all", action="store_true", help="show seen items too")+ ap.add_argument("--forms", default="8-K", help="SEC forms to watch, comma separated")+ ap.add_argument("--no-sec", action="store_true", help="headlines only")+ ap.add_argument("--no-moves", action="store_true", help="skip the price line per ticker")+ ap.add_argument("--move-pct", type=float, default=MOVE_PCT, help="flag a move this big (percent)")+ ap.add_argument("--user-agent", help="SEC User-Agent: \"Your Name [email protected]\"")+ ap.add_argument("--config", default="trader/config.json")+ ap.add_argument("--offline", metavar="DIR")+ ap.add_argument("--now", help="ISO time, for reproducible runs")+ ap.add_argument("--dry-run", action="store_true", help="do not update the state file")+ ap.add_argument("--json", action="store_true")+ args = ap.parse_args(argv)++ if args.tickers:+ watch = {t.upper(): None for t in args.tickers}+ known = watch_from_files(args.portfolio, args.watchlist, args.plan)+ watch.update({t: known[t] for t in watch if known.get(t)})+ else:+ watch = watch_from_files(args.portfolio, args.watchlist, args.plan)+ if not watch:+ print("news: no tickers. Pass --tickers, or run /trader-scanner first (it writes "+ "trader/watchlist.json).", file=sys.stderr)+ return 2+ now = parse_time(args.now) if args.now else _dt.datetime.now(_dt.timezone.utc)+ state = load_json(args.state) or {}+ errors = []+ ua = sec_user_agent(args.user_agent, args.config)+ sec = not args.no_sec+ if sec and not ua and not args.offline:+ errors.append("SEC filings skipped: set sec_user_agent in trader/config.json or "+ "SEC_USER_AGENT (\"Your Name [email protected]\") to include them")+ sec = False+ fetcher = Fetcher(ua, offline=args.offline)+ forms = [f.strip().upper() for f in args.forms.split(",") if f.strip()]+ items = collect(fetcher, watch, state, sec=sec, forms=forms, errors=errors)+ items = dedupe(tag(items, watch))+ shown = select(items, state, now, hours=args.hours, show_all=args.all)+ moves = [] if args.no_moves else collect_moves(fetcher, watch, errors)+ if args.json:+ mv = [dict(m, time=m["time"].isoformat() if m.get("time") else None,+ moving=abs(m["pct"]) >= args.move_pct) for m in moves]+ print(json.dumps({"checked": now.isoformat(), "moves": mv, "items": _json_ready(shown),+ "notes": errors}, indent=2))+ else:+ sys.stdout.write(render(shown, errors, now, moves, args.move_pct))+ if not args.dry_run:+ remember(items, state, now)+ folder = os.path.dirname(args.state)+ if folder:+ os.makedirs(folder, exist_ok=True)+ with open(args.state, "w", encoding="utf-8") as fh:+ json.dump(state, fh, indent=2)+ fh.write("\n")+ return 0 if any(i["new"] for i in shown) else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/trader-pelosi/SKILL.md b/trader-pelosi/SKILL.mdnew file mode 100644index 0000000..f09348d--- /dev/null+++ b/trader-pelosi/SKILL.md@@ -0,0 +1,158 @@+---+name: trader-pelosi+description: >-+ The Pelosi Tracker. Watches the stock trades members of Congress must+ disclose under the STOCK Act: reads the House Clerk's public Periodic+ Transaction Reports (PTRs) as soon as they are posted, alerts once per new+ filing, and turns each PDF into clean rows (who, owner, stock, ticker,+ buy or sell, options strike and expiry, trade date, amount range, how many+ days it took to disclose). Flags trades in stocks you hold. Senate reports+ are covered by a documented manual route. Use when the user says "what is+ Pelosi buying", "track Nancy Pelosi", "Congress trades", "politician stock+ trades", "did any congressman buy X", "alert me when Pelosi files", or+ "run the Pelosi skill".+argument-hint: "[member name] [--read]"+---++# trader-pelosi++Members of Congress have to report their trades, their spouse's and their+dependent children's. The House Clerk posts every report as a PDF and lists+them all in one index file per year. This skill reads that index, notices the+moment a new report appears, and reads the report for you.++It is fast. It is not early. A PTR is due within 30 days of the member+learning of the trade and never more than 45 days after it, so by the time+anyone can read it the trade is days or weeks old. There is no inside+information here: only public filings, read quickly. Say that every time.++Tool in this folder (standard library Python; `pdftotext` from poppler is+optional, to read the PDFs locally):++```bash+python3 "${CLAUDE_SKILL_DIR}/ptr.py" --help+```++## What it reads and writes++- Reads `https://disclosures-clerk.house.gov/public_disc/financial-pdfs/<YEAR>FD.zip`+ (one `<Member>` per filing: name, district, FilingType, FilingDate, DocID)+ and each PTR at `.../public_disc/ptr-pdfs/<YEAR>/<DocID>.pdf`.+- Writes `trader/state/pelosi.json` (the DocIDs already shown, so each PTR+ alerts once) and keeps downloaded PDFs in `trader/state/ptr-pdfs/`.+- Reads `trader/portfolio.json` (if it exists) to flag trades in what you hold.++## The rules++- **Quote the filing, not a tracker.** Every row comes from the PTR PDF on the+ Clerk's site, with its DocID and link. Third-party trackers are fine for+ browsing but can be off (Capitol Trades showed Pelosi's trade dates one day+ earlier than her PTRs). The PTR wins.+- **Amounts are ranges.** "$1,000,001 - $5,000,000", never "$3 million".+- **Owner matters.** SP is the spouse, JT joint, DC a dependent child, blank+ the member. Pelosi's 2026 trades are all SP: Paul Pelosi.+- **Say the delay.** Each row shows how many days passed between the trade+ and the filing; over 45 is flagged as late.+- **Options are options.** A call bought with a strike and an expiry is not+ a share purchase. The tool reads contracts, strike and expiry from the+ description and marks exercises.++## Step 1: what has been filed++```bash+python3 "${CLAUDE_SKILL_DIR}/ptr.py" index --member pelosi+python3 "${CLAUDE_SKILL_DIR}/ptr.py" index --since 2026-10-01 # every member+python3 "${CLAUDE_SKILL_DIR}/ptr.py" index --member "Josh Gottheimer" --year 2025+```++`--member` takes a last name, "First Last" or "Last, First", and repeats.+`--type ''` lists every filing type (annual reports are type O).++## Step 2: watch for new ones++```bash+python3 "${CLAUDE_SKILL_DIR}/ptr.py" new --member pelosi --read+```++Shows only PTRs not seen at the last check (the first run shows the last 45+days), downloads and reads them with `--read`, and records them in the state+file. Exit code 1 means nothing new. In January it also checks last year's+index. The Clerk rebuilds the index file about once a day (the copy read on+2026-10-13 was stamped 09:00 that morning), so checking every hour on weekdays+is plenty: run it with `/loop 1h` or a scheduled task.++## Step 3: read a report++```bash+python3 "${CLAUDE_SKILL_DIR}/ptr.py" fetch 20035143+python3 "${CLAUDE_SKILL_DIR}/ptr.py" parse ptr.txt --filed 2026-08-21 --json+```++`fetch` saves the PDF and, if `pdftotext` is installed, prints the rows. If it+is not installed, open the saved PDF and read it directly: you can read PDFs.+`parse` turns `pdftotext -layout` text into rows. Check the row count against+the PDF when a report runs over several pages.++## Example: a real alert++```+NEW Periodic Transaction Report: Hon. Nancy Pelosi (CA11) filed 2026-08-21, doc 20035143+ - spouse purchase, Bloom Energy Corporation Class A Common Stock (BE): 100 call+ options, $100 strike, expires 2027-06-17, $1,000,001 - $5,000,000, traded+ 2026-07-24, disclosed 28 days later+```++The same PTR also shows 10,000 and 5,000 BE shares, a second block of 100 BE+calls on 07/28, Intel shares and 50 Intel calls ($50 strike, 6/17/27), and a+private real estate LLC with no ticker. Her other 2026 PTRs: 20033725+(01/23), 20034836 (06/23, Intel and Uber calls) and 20035553 (10/02, a real+estate LLC). Then: "This is a public disclosure filed 28 days after the trade.+It says what Paul Pelosi bought in July, not what anyone will buy next."++If the user wants to act on it, it goes the long way: a disclosure is weeks+old, so it is a reason to look at a chart, not a setup. `/trader-scanner`+and `/trader-entry` decide if there is a trade today; then shares only (the+config has `allow_options: false`), sized by `/trader-budget`, checked by+`/trader-risk`, placed by `/trader-broker` only after their yes.++## The Senate: the manual route++Senate reports live at `https://efdsearch.senate.gov`. Before searching, the+site asks you to tick a box agreeing to the legal limits on how the reports+may be used. That is an agreement for the person to accept, so this skill+does not click it or automate it. The route:++1. The user opens `https://efdsearch.senate.gov/search/` in their browser and+ accepts the agreement themselves.+2. They pick the report type "Periodic Transactions", type the senator's last+ name, set the date range and search.+3. They open the report: electronic filings show a table of transactions,+ paper filings are scanned images.+4. They paste the table (or a screenshot, or the saved page) into the chat,+ and you write it up in the same shape as the House rows, with the report+ link, and the same 45-day caveat.++## What it never does++- Never says or implies a member has inside information, or that copying a+ politician beats the market. No return claims.+- Never presents a range as an exact dollar figure or a tracker's date as the+ trade date.+- Never places an order, and never copies options trades.+- Never automates the Senate agreement or any login.++## Safety++- Education and tooling, not financial advice. Nothing in this pack is a+ recommendation to buy or sell anything.+- Paper trading by default (`"paper": true` in `trader/config.json`).+- Nothing places an order except `/trader-broker`, and only after+ `/trader-risk` passes AND the user types an explicit yes for that order in+ the chat, AND the brokerage tool is set to "Needs approval" in Claude+ (Customize > Connectors > tool permissions) so Claude's own "Allow once /+ Deny" card appears too. Never "Always allow" an order tool.+- No options, margin, shorting or leverage unless the config allows it and+ the user confirms.+- Congressional trades are PUBLIC disclosures filed up to 45 days after the+ trade (STOCK Act). This skill reads them fast; it has no inside+ information, and it says so.diff --git a/trader-pelosi/ptr.py b/trader-pelosi/ptr.pynew file mode 100644index 0000000..54a445e--- /dev/null+++ b/trader-pelosi/ptr.py@@ -0,0 +1,566 @@+#!/usr/bin/env python3+"""Congress trade tracker for trader-pelosi. Standard library only.++Reads the House Clerk's public financial disclosure index and the Periodic+Transaction Reports (PTRs) members of the House file when they, their spouse+or a dependent child buy or sell a stock.++ python3 ptr.py index --member pelosi # this year's PTRs by a member+ python3 ptr.py index --year 2026 --since 2026-10-01 # every PTR filed since a date+ python3 ptr.py new --member pelosi # only what is new since last check+ python3 ptr.py fetch 20035143 # download one PTR and read it+ python3 ptr.py parse ptr.txt --filed 2026-08-21 # rows from `pdftotext -layout` text++Where the data comes from:+ - The index: https://disclosures-clerk.house.gov/public_disc/financial-pdfs/<YEAR>FD.zip+ (a ZIP with <YEAR>FD.xml: one <Member> per filing, FilingType P = PTR).+ - Each PTR: https://disclosures-clerk.house.gov/public_disc/ptr-pdfs/<YEAR>/<DocID>.pdf+ - Reading a PDF needs `pdftotext` (poppler) if you want rows from this tool.+ Without it, the tool prints the PDF path and Claude reads the PDF itself.++What a PTR is, and is not:+ - It is a PUBLIC disclosure under the STOCK Act, due within 30 days of the+ member learning of the trade and never later than 45 days after it. So it+ arrives days or weeks after the trade, and amounts are ranges, not prices.+ - Reading them fast is not inside information. There is none here.+ - This covers the House. Senate PTRs are on efdsearch.senate.gov behind an+ agreement you must accept yourself; see SKILL.md for the manual route.++State: `new` remembers which DocIDs it has shown in trader/state/pelosi.json,+so each PTR alerts once. Offline: --offline FILE reads a saved <YEAR>FD.zip+(or the .xml inside it) instead of the network. The tests use it.+"""++import argparse+import datetime as _dt+import io+import json+import os+import re+import shutil+import subprocess+import sys+import urllib.error+import urllib.request+import xml.etree.ElementTree as ET+import zipfile++INDEX_URL = "https://disclosures-clerk.house.gov/public_disc/financial-pdfs/%d%s.zip"+PTR_URL = "https://disclosures-clerk.house.gov/public_disc/ptr-pdfs/%d/%s.pdf"+FD_URL = "https://disclosures-clerk.house.gov/public_disc/financial-pdfs/%d/%s.pdf"+UA = "day-trader-skill/2.0 (+https://github.com/Jakeschincariol/day-trader-skill)"+FILING_TYPES = {+ "P": "Periodic Transaction Report", "O": "Annual report", "A": "Amendment",+ "C": "Candidate report", "X": "Extension", "T": "Termination report",+ "W": "Waiver", "D": "Disclosure (new member or candidate)", "H": "New filer report",+}+TXN_TYPES = {"P": "purchase", "S": "sale", "S (partial)": "partial sale", "E": "exchange"}+OWNERS = {"SP": "spouse", "JT": "joint", "DC": "dependent child", "": "self"}+LATE_DAYS = 45+++class PtrError(Exception):+ pass+++# ---------------------------------------------------------------- the index++def iso(mdy):+ """'8/21/2026' or '08/21/2026' -> '2026-08-21' (two-digit years -> 20xx)."""+ m = re.match(r"^\s*(\d{1,2})/(\d{1,2})/(\d{2,4})\s*$", mdy or "")+ if not m:+ return None+ month, day, year = int(m.group(1)), int(m.group(2)), int(m.group(3))+ if year < 100:+ year += 2000+ try:+ return _dt.date(year, month, day).isoformat()+ except ValueError:+ return None+++def download(url, timeout=60):+ req = urllib.request.Request(url, headers={"User-Agent": UA})+ try:+ with urllib.request.urlopen(req, timeout=timeout) as resp:+ return resp.read()+ except urllib.error.HTTPError as exc:+ raise PtrError("HTTP %s for %s" % (exc.code, url))+ except urllib.error.URLError as exc:+ raise PtrError("could not reach %s: %s" % (url, exc.reason))+++def read_index_bytes(data):+ """Index XML bytes from the ZIP (or the XML itself)."""+ if data[:2] == b"PK":+ with zipfile.ZipFile(io.BytesIO(data)) as z:+ names = [n for n in z.namelist() if n.lower().endswith(".xml")]+ if not names:+ raise PtrError("no XML inside the ZIP (files: %s)" % ", ".join(z.namelist()))+ return z.read(names[0])+ return data+++def parse_index(xml_bytes, year):+ """Every filing in a <YEAR>FD.xml as a dict, newest first."""+ try:+ root = ET.fromstring(xml_bytes)+ except ET.ParseError as exc:+ raise PtrError("index is not valid XML: %s" % exc)+ out = []+ for m in root.iter("Member"):+ f = {c.tag: (c.text or "").strip() for c in m}+ doc = f.get("DocID", "")+ kind = f.get("FilingType", "")+ y = int(f.get("Year") or year)+ url = (PTR_URL if kind == "P" else FD_URL) % (y, doc)+ name = " ".join(x for x in (f.get("Prefix"), f.get("First"), f.get("Last"),+ f.get("Suffix")) if x)+ out.append({"doc_id": doc, "type": kind, "type_name": FILING_TYPES.get(kind, kind),+ "last": f.get("Last", ""), "first": f.get("First", ""), "name": name,+ "district": f.get("StateDst", ""), "year": y,+ "filed": iso(f.get("FilingDate", "")), "url": url})+ out.sort(key=lambda r: (r["filed"] or "", r["doc_id"]), reverse=True)+ return out+++def load_index(year, offline=None):+ if offline:+ with open(offline, "rb") as fh:+ data = fh.read()+ else:+ data = download(INDEX_URL % (year, "FD"))+ return parse_index(read_index_bytes(data), year)+++def member_match(row, member):+ """'pelosi', 'Nancy Pelosi' or 'Pelosi, Nancy' against an index row."""+ member = (member or "").strip().lower()+ if not member:+ return True+ if "," in member:+ last, first = [x.strip() for x in member.split(",", 1)]+ else:+ parts = member.split()+ last, first = parts[-1], " ".join(parts[:-1])+ if row["last"].lower() != last:+ return False+ return not first or row["first"].lower().startswith(first)+++def select(rows, members=None, kind="P", since=None):+ out = []+ for r in rows:+ if kind and r["type"] != kind:+ continue+ if members and not any(member_match(r, m) for m in members):+ continue+ if since and (r["filed"] or "") < since:+ continue+ out.append(r)+ return out+++# ---------------------------------------------------------------- state++def load_state(path):+ if path and os.path.isfile(path):+ with open(path, encoding="utf-8") as fh:+ return json.load(fh)+ return {"seen": [], "last_check": None}+++def save_state(path, state):+ folder = os.path.dirname(path)+ if folder:+ os.makedirs(folder, exist_ok=True)+ with open(path, "w", encoding="utf-8") as fh:+ json.dump(state, fh, indent=2)+ fh.write("\n")+++def new_since(rows, state, today, first_days=LATE_DAYS):+ """Rows not seen before. On the first run: only those filed in the last+ first_days days, so you are not flooded with the whole year."""+ seen = set(state.get("seen", []))+ if state.get("last_check") is None:+ cutoff = (today - _dt.timedelta(days=first_days)).isoformat()+ return [r for r in rows if (r["filed"] or "") >= cutoff]+ return [r for r in rows if r["doc_id"] not in seen]+++# ---------------------------------------------------------------- parsing a PTR++TXN = re.compile(+ r"^\s*(?:(?P<owner>SP|JT|DC)\s+)?(?P<asset>.*?)\s+(?P<type>S \(partial\)|P|S|E)\s+"+ r"(?P<date>\d{2}/\d{2}/\d{4})\s+(?P<notified>\d{2}/\d{2}/\d{4})\s+(?P<amount>\S.*?)\s*$")+LABELS = [+ ("status", re.compile(r"^\s*F(?:ILING)?\s+S(?:TATUS)?\s*:\s*(.*)$", re.I)),+ ("description", re.compile(r"^\s*D(?:ESCRIPTION)?\s*:\s*(.*)$", re.I)),+ ("account", re.compile(r"^\s*S(?:UBHOLDING)?\s+O(?:F)?\s*:\s*(.*)$", re.I)),+ ("location", re.compile(r"^\s*L(?:OCATION)?\s*:\s*(.*)$", re.I)),+]+# Column headers repeat at the top of every page, sometimes in the middle of a+# row that continues on the next page: skip them without ending the row.+PAGE_HEADER = re.compile(r"^\s*(ID\s+Owner\s+Asset|Type\s+Date\b|Type$|Date$|Gains >$|\$200\?$)",+ re.I)+END = re.compile(r"^\s*(\* For the complete|I CERTIFY|Digitally Signed|Filing ID #)", re.I)+AMOUNT = re.compile(r"\$([\d,]+)")+OPTION = re.compile(r"([\d,]+)\s+(call|put)\s+options?\b.*?strike price of \$([\d,.]+)"+ r".*?expiration date of (\d{1,2}/\d{1,2}/\d{2,4})", re.I | re.S)+SHARES = re.compile(r"(?:purchased|sold|bought)\s+([\d,]+)\s+shares", re.I)+++def _amount(text):+ nums = [int(x.replace(",", "")) for x in AMOUNT.findall(text or "")]+ low = nums[0] if nums else None+ high = nums[1] if len(nums) > 1 else None+ return low, high+++def _finish(row, filed):+ asset = " ".join(row.pop("_asset").split())+ tick = re.findall(r"\(([A-Z][A-Z0-9.\-/]{0,9})\)", asset)+ code = re.findall(r"\[([A-Z]{2})\]", asset)+ row["ticker"] = tick[-1] if tick else None+ row["asset_type"] = code[-1] if code else None+ name = re.sub(r"\s*\[[A-Z]{2}\]", "", asset)+ if tick:+ name = re.sub(r"\s*\(%s\)" % re.escape(tick[-1]), "", name)+ row["asset"] = name.strip(" -")+ row["amount"] = " ".join(row["amount"].split())+ row["amount_low"], row["amount_high"] = _amount(row["amount"])+ row["description"] = " ".join(row.get("description", "").split()) or None+ opt = OPTION.search(row["description"] or "")+ if opt:+ row["option"] = {"contracts": int(opt.group(1).replace(",", "")),+ "kind": opt.group(2).lower(),+ "strike": float(opt.group(3).replace(",", "")),+ "expires": iso(opt.group(4)),+ "exercised": bool(re.match(r"\s*exercised\b", row["description"], re.I))}+ sh = SHARES.search(row["description"] or "")+ if sh:+ row["shares"] = int(sh.group(1).replace(",", ""))+ if filed and row["date"]:+ days = (_dt.date.fromisoformat(filed) - _dt.date.fromisoformat(row["date"])).days+ row["days_to_disclose"] = days+ row["late"] = days > LATE_DAYS+ return row+++def parse_ptr_text(text, filed=None):+ """Rows from `pdftotext -layout` output of a House PTR.++ Returns {"name", "status", "district", "doc_id", "filed", "rows": [...]}.+ Each row: owner, owner_name, asset, ticker, asset_type, type, type_name,+ date, notified, amount, amount_low, amount_high, status, description,+ account, option {contracts, kind, strike, expires}, shares,+ days_to_disclose, late."""+ head = {"name": None, "status": None, "district": None, "doc_id": None, "filed": filed}+ rows, cur, mode = [], None, None+ amount_open = False+ for raw in text.splitlines():+ line = raw.rstrip()+ s = line.strip()+ m = re.match(r"^Name:\s+(.*)$", s)+ if m and not head["name"]:+ head["name"] = m.group(1).strip()+ continue+ m = re.match(r"^Status:\s+(.*)$", s)+ if m and not head["status"]:+ head["status"] = m.group(1).strip()+ continue+ m = re.match(r"^State/District:\s*(\S+)", s)+ if m:+ head["district"] = m.group(1)+ continue+ m = re.search(r"Filing ID #(\d+)", s)+ if m:+ head["doc_id"] = m.group(1)+ continue+ m = re.match(r"^Digitally Signed:.*?,\s*(\d{2}/\d{2}/\d{4})", s)+ if m:+ head["filed"] = head["filed"] or iso(m.group(1))+ continue+ t = TXN.match(line)+ if t and iso(t.group("date")):+ if cur:+ rows.append(cur)+ owner = t.group("owner") or ""+ cur = {"owner": owner, "owner_name": OWNERS.get(owner, owner),+ "_asset": t.group("asset"), "type": t.group("type"),+ "type_name": TXN_TYPES.get(t.group("type"), t.group("type")),+ "date": iso(t.group("date")), "notified": iso(t.group("notified")),+ "amount": t.group("amount"), "status": None, "account": None}+ amount_open = cur["amount"].endswith("-")+ mode = "asset"+ continue+ if cur is None:+ continue+ if not s:+ if mode in ("description", "asset"):+ mode = "labels" if mode == "description" or "[" in cur["_asset"] else mode+ continue+ if PAGE_HEADER.match(s):+ continue+ if END.match(s):+ mode = "labels"+ continue+ label = next(((k, rx.match(line)) for k, rx in LABELS if rx.match(line)), None)+ if label:+ key, lm = label+ value = lm.group(1).strip()+ if key == "description":+ cur["description"] = value+ mode = "description"+ elif key in ("status", "account"):+ cur[key] = value+ mode = "labels"+ else:+ mode = "labels"+ continue+ if mode == "asset":+ parts = re.split(r"\s{2,}", s)+ if amount_open and re.fullmatch(r"\$[\d,]+", parts[-1]):+ cur["amount"] += " " + parts.pop()+ amount_open = False+ if parts and parts[0]:+ cur["_asset"] += " " + " ".join(parts)+ elif mode == "description":+ cur["description"] = cur.get("description", "") + " " + s+ if cur:+ rows.append(cur)+ head["rows"] = [_finish(r, head["filed"]) for r in rows]+ return head+++def pdf_to_text(pdf_path):+ exe = shutil.which("pdftotext")+ if not exe:+ return None+ try:+ out = subprocess.run([exe, "-layout", pdf_path, "-"], capture_output=True, timeout=60)+ except (OSError, subprocess.SubprocessError):+ return None+ return out.stdout.decode("utf-8", "replace") if out.returncode == 0 else None+++# ---------------------------------------------------------------- output++def watchlist(args):+ tickers = {t.upper() for t in (args.tickers or [])}+ path = getattr(args, "portfolio", None)+ if path and os.path.isfile(path):+ with open(path, encoding="utf-8") as fh:+ for p in json.load(fh).get("positions", []):+ if p.get("ticker"):+ tickers.add(p["ticker"].upper())+ return tickers+++def describe(row):+ bits = ["%s %s" % (row["owner_name"], row["type_name"])]+ what = row["asset"]+ if row.get("ticker"):+ what += " (%s)" % row["ticker"]+ if row.get("option"):+ o = row["option"]+ what += ": %s%d %s options, $%g strike, expires %s" % (+ "exercised " if o.get("exercised") else "", o["contracts"], o["kind"],+ o["strike"], o["expires"])+ elif row.get("shares"):+ what += ": %s shares" % "{:,}".format(row["shares"])+ bits.append(what)+ bits.append(row["amount"])+ when = "traded %s" % row["date"]+ if row.get("days_to_disclose") is not None:+ when += ", disclosed %d days later%s" % (row["days_to_disclose"],+ " (LATE: over 45)" if row.get("late") else "")+ bits.append(when)+ if row.get("account"):+ bits.append("account: %s" % row["account"])+ return ", ".join(bits)+++def render_report(report, watch=()):+ out = ["%s (%s), %s. PTR %s, filed %s." % (+ report.get("name") or "?", report.get("district") or "?", report.get("status") or "?",+ report.get("doc_id") or "?", report.get("filed") or "?")]+ for r in report["rows"]:+ flag = " <- %s is on your list" % r["ticker"] if r.get("ticker") in watch else ""+ out.append(" - %s%s" % (describe(r), flag))+ if r.get("description") and not r.get("option") and not r.get("shares"):+ out.append(" %s" % r["description"])+ if not report["rows"]:+ out.append(" no transaction rows found: read the PDF directly")+ out.append("Public disclosure under the STOCK Act, filed up to 45 days after the trade. "+ "Amounts are ranges. Not inside information.")+ return "\n".join(out) + "\n"+++def render_index(rows):+ out = []+ for r in rows:+ out.append("%s %-28s %-5s %-4s doc %-9s %s" % (+ r["filed"], r["name"][:28], r["district"], r["type"], r["doc_id"], r["url"]))+ return "\n".join(out) + ("\n" if out else "")+++# ---------------------------------------------------------------- CLI++def _parser():+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])+ sub = ap.add_subparsers(dest="cmd")+ year = _dt.date.today().year++ def common(p):+ p.add_argument("--year", type=int, default=year)+ p.add_argument("--member", action="append",+ help="last name or 'First Last'; repeat for more members")+ p.add_argument("--type", default="P", help="FilingType (default P = PTR; '' for all)")+ p.add_argument("--since", help="only filings on or after YYYY-MM-DD")+ p.add_argument("--offline", metavar="FILE", help="a saved <YEAR>FD.zip or .xml")+ p.add_argument("--json", action="store_true")++ p = sub.add_parser("index", help="list filings from the yearly index")+ common(p)+ p.add_argument("--limit", type=int, default=50)++ p = sub.add_parser("new", help="filings not seen at the last check")+ common(p)+ p.add_argument("--state", default="trader/state/pelosi.json")+ p.add_argument("--today", help="YYYY-MM-DD, for reproducible runs")+ p.add_argument("--dry-run", action="store_true", help="do not update the state file")+ p.add_argument("--read", action="store_true",+ help="also download and read each new PTR (needs pdftotext)")+ p.add_argument("--pdf-dir", default="trader/state/ptr-pdfs")+ p.add_argument("--tickers", nargs="*", help="flag trades in these tickers")+ p.add_argument("--portfolio", default="trader/portfolio.json")++ p = sub.add_parser("fetch", help="download one PTR PDF and read it")+ p.add_argument("doc_id")+ p.add_argument("--year", type=int, default=year)+ p.add_argument("--filed", help="filing date YYYY-MM-DD if known")+ p.add_argument("--pdf-dir", default="trader/state/ptr-pdfs")+ p.add_argument("--tickers", nargs="*")+ p.add_argument("--portfolio", default="trader/portfolio.json")+ p.add_argument("--json", action="store_true")++ p = sub.add_parser("parse", help="rows from pdftotext -layout text of a PTR")+ p.add_argument("text_file")+ p.add_argument("--filed", help="filing date YYYY-MM-DD (else read from the signature)")+ p.add_argument("--tickers", nargs="*")+ p.add_argument("--portfolio", default="trader/portfolio.json")+ p.add_argument("--json", action="store_true")+ return ap+++def _fetch_and_read(doc_id, year, pdf_dir, filed=None):+ os.makedirs(pdf_dir, exist_ok=True)+ path = os.path.join(pdf_dir, "%s.pdf" % doc_id)+ if not os.path.isfile(path):+ data = download(PTR_URL % (year, doc_id))+ if not data.startswith(b"%PDF"):+ raise PtrError("doc %s did not come back as a PDF" % doc_id)+ with open(path, "wb") as fh:+ fh.write(data)+ text = pdf_to_text(path)+ if text is None:+ return path, None+ report = parse_ptr_text(text, filed=filed)+ report["pdf"] = path+ report["url"] = PTR_URL % (year, doc_id)+ return path, report+++def main(argv=None):+ args = _parser().parse_args(argv)+ if not args.cmd:+ _parser().print_help()+ return 2+ try:+ return _run(args)+ except (PtrError, OSError) as exc:+ print("ptr: %s" % exc, file=sys.stderr)+ return 2+++def _run(args):+ if args.cmd == "parse":+ with open(args.text_file, encoding="utf-8", errors="replace") as fh:+ report = parse_ptr_text(fh.read(), filed=args.filed)+ if args.json:+ print(json.dumps(report, indent=2))+ else:+ sys.stdout.write(render_report(report, watchlist(args)))+ return 0 if report["rows"] else 1++ if args.cmd == "fetch":+ path, report = _fetch_and_read(args.doc_id, args.year, args.pdf_dir, args.filed)+ if report is None:+ print("Saved %s. pdftotext is not installed, so read the PDF directly "+ "(Claude can open it), or install poppler (brew install poppler)." % path)+ return 0+ if args.json:+ print(json.dumps(report, indent=2))+ else:+ sys.stdout.write(render_report(report, watchlist(args)))+ return 0 if report["rows"] else 1++ rows = load_index(args.year, args.offline)+ if args.cmd == "new" and not args.offline:+ today = _dt.date.fromisoformat(args.today) if args.today else _dt.date.today()+ if today.month == 1 and args.year == today.year:+ try:+ rows += load_index(args.year - 1)+ except PtrError:+ pass+ picked = select(rows, args.member, args.type or None, args.since)++ if args.cmd == "index":+ picked = picked[:args.limit]+ if args.json:+ print(json.dumps(picked, indent=2))+ else:+ sys.stdout.write(render_index(picked))+ if not picked:+ print("No matching filings in the %d index." % args.year)+ return 0 if picked else 1++ # new+ today = _dt.date.fromisoformat(args.today) if args.today else _dt.date.today()+ state = load_state(args.state)+ fresh = new_since(picked, state, today)+ watch = watchlist(args)+ reports = []+ if args.read:+ for r in fresh:+ if r["type"] != "P":+ continue+ path, report = _fetch_and_read(r["doc_id"], r["year"], args.pdf_dir, r["filed"])+ reports.append({"filing": r, "pdf": path, "report": report})+ if args.json:+ print(json.dumps({"new": fresh, "reports": reports}, indent=2))+ else:+ if not fresh:+ print("Nothing new since %s." % (state.get("last_check") or "the last check"))+ for r in fresh:+ print("NEW %s: %s (%s) filed %s, doc %s" % (+ r["type_name"], r["name"], r["district"], r["filed"], r["doc_id"]))+ print(" %s" % r["url"])+ for rep in reports:+ if rep["report"] is None:+ print(" read %s (pdftotext not installed)" % rep["pdf"])+ else:+ sys.stdout.write(render_report(rep["report"], watch))+ if not args.dry_run:+ seen = set(state.get("seen", []))+ seen.update(r["doc_id"] for r in picked)+ state["seen"] = sorted(seen)+ state["last_check"] = _dt.datetime.now().replace(microsecond=0).isoformat()+ save_state(args.state, state)+ return 0 if fresh else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/trader-risk/SKILL.md b/trader-risk/SKILL.mdnew file mode 100644index 0000000..8628b2f--- /dev/null+++ b/trader-risk/SKILL.md@@ -0,0 +1,172 @@+---+name: trader-risk+description: >-+ Risk Manager. Checks every trade against your limits and stops anything+ over them, before it can reach the broker. For a day trade: a stop is+ required, the loss at the stop must fit your max loss per trade (measured+ from the higher of the plan's entry and a fresh price), reward:risk must+ meet your minimum, the day's total risk must fit your daily loss limit, no+ more than your trades per day, and no new entries outside your entry+ window or when the market is closed. It also keeps the basics: blocked+ tickers, order size, position cap, cash buffer, margin, short sales,+ options and crypto, malformed or bad bracket orders, duplicates and a daily+ order limit. Getting out is never blocked by a day limit. Prints PASS or+ BLOCK with the reason and records the verdicts so trader-broker only shows+ an order that passed. Use when the user says "check my order", "is this+ safe", "risk check", "does this break my rules", "can I take this trade",+ "how much have I risked today", or before /trader-broker, always.+argument-hint: "[path to orders.json]"+---++# trader-risk++The Risk Manager is the gate between a proposal and the broker. Every order+written by trader-budget or trader-broker's flatten passes through it. A+BLOCK is final for that order: it does not go to the user for a yes, and it+does not go to the broker. Most people who day trade lose money. These limits+keep each loss and each day's losses small. They do not make a trade win.++`${CLAUDE_SKILL_DIR}` below is this skill's folder (where this SKILL.md lives).++```bash+python3 "${CLAUDE_SKILL_DIR}/check.py" # trader/ files; writes trader/state/risk.json+python3 "${CLAUDE_SKILL_DIR}/check.py" --json+python3 "${CLAUDE_SKILL_DIR}/check.py" --no-write # look without recording+python3 "${CLAUDE_SKILL_DIR}/check.py" --now "2026-10-19 10:15" # pin the clock (New York time)+```++## What it reads and writes++| file | what |+| --- | --- |+| `trader/orders.json` | the proposed orders (trader-budget, or trader-broker's flatten) |+| `trader/config.json` | the limits (trader-budget ships `config.example.json`) |+| `trader/portfolio.json` | cash and holdings; if missing, a fresh account funded with the budget |+| `trader/prices.json` | a fresh price raises the entry it measures risk from; also values holdings |+| `trader/state/broker.json` | what was placed today: duplicates, trades per day, daily loss, day trades |+| `trader/state/risk.json` | the verdicts it writes, with a fingerprint of each exact order |++## Entries and exits++An **entry** opens or adds to a position: a buy, or a sell that would go+short. An **exit** only reduces what you already hold. Getting out must+always be possible, so an exit is checked for format, asset and short sales+only. Every other rule (day limits, entry window, loss, reward:risk, blocked+list, size, duplicates) turns into a warning for an exit, never a BLOCK.++## The checks++Orders are checked in file order, as if each passed order had filled, so a+batch that is fine order by order but breaks a limit together is caught.++| check | blocks when |+| --- | --- |+| format | no symbol, side not buy or sell, both or neither of qty and notional, a notional order that is not market + day (Alpaca's rule), a limit order with no limit price; a bracket that is not whole shares, not `day` or `gtc`, or misses its stop-loss or take-profit |+| asset | an option symbol while `allow_options` is false; crypto or anything that is not a US stock or ETF ticker |+| short | a sell of more than you hold (`allow_short` false) |+| blocked | (entries) the ticker is on the `blocked` list |+| size | (entries) under `min_order_usd` or over `max_order_usd` |+| position | (entries) the stock would be over `max_position_pct` of the account |+| cash | (entries) the buy would leave less than the cash buffer, or need margin |+| stop | (entries) no stop while `require_stop` is true (a bracket `stop_loss_stop_price`, or the order's plan stop); a stop on the wrong side of the entry |+| loss | (entries) qty x (entry minus stop) over `max_loss_per_trade_usd` |+| reward:risk | (entries) (target minus entry) / (entry minus stop) under `min_reward_risk` |+| daily loss | (entries) the max losses at the stops of today's entries, plus this one, over `max_daily_loss_usd` |+| trades | (entries) `max_trades_per_day` entries already placed today |+| window | (entries) before `no_entries_before` or after `no_entries_after`, or the market is closed |+| pdt | (entries, only with `pdt_guard` true) 3 day trades already in the last 5 business days |+| duplicate | (entries) the same symbol and side twice in one batch, or already placed today |+| daily limit | (entries) `max_orders_per_day` orders already placed today |++How the numbers work:++- **The entry it measures from**: the limit price for a limit order. For a+ market order, the HIGHER of the plan's entry and a fresh price from+ `trader/prices.json` (under 15 minutes old). A plan written at 10:15 cannot+ understate the risk at 10:55 after the price ran up. An older price is not+ used, and it says so.+- **Daily loss** counts the full max loss of every entry placed today, win or+ lose, as trader-broker logged it. Three full-size trades use up a $150 day.+- **The window** is New York time, worked out in the tool (daylight saving+ included), never from the computer's clock zone. Weekends and NYSE holidays+ are closed. On a 1:00 p.m. early close the window ends 3 hours earlier too.+ Set both `no_entries_*` to null to switch the window off.+- **pdt_guard** (off by default) counts a day trade as a symbol bought and+ sold on the same day in the log, plus any entry placed today (it is meant+ to be flat by the close). FINRA removed the $25,000 pattern-day-trader+ minimum (Regulatory Notice 26-10, effective June 4, 2026; firms may phase+ in until October 20, 2027), so some brokers still apply the old rule: turn+ `pdt_guard` on if yours does.++Warnings do not block, but say them to the user: a LIVE account, a number+sent as a number instead of a string, a stop that lives only in the plan and+not at the broker, a price too old to use, an early close today.++## Steps++1. If the price may have moved since the plan, refresh it first+ (trader-alerts: `alerts.py quote TSLA --write`).+2. Run `check.py`. Exit code 0 means every order passed, 1 means at least one+ was blocked.+3. Tell the user the result in plain words, order by order: the max loss at+ the stop, reward:risk, and how much of today's limits it uses. For a+ BLOCK, give the reason and the fix (fewer shares, a closer stop from+ trader-exit, wait for the window, or skip the trade). Never change a+ limit yourself.+4. If the order changes in any way, run the check again. trader-broker matches+ each order to its verdict by fingerprint, so an edited order is not ready+ until it passes again, and a verdict from yesterday does not count today.++## Example: the reel++The TSLA bracket from trader-budget at 10:15 AM on Monday 2026-10-19, on a+fresh $5,000 paper account with the example config:++```+PASS #1 buy TSLA 8 shares, entry+ entry 364.18 (the plan's entry), stop 358.32, target 370.04: risk 5.86 a share+ max loss $46.88 (limit $50), reward:risk 1.00 (min 1)+ today before this: 0 of 3 trades, $0 of $150 daily loss++1 passed, 0 blocked at 2026-10-19 10:15 New York. Cash after the passed orders: $2,086.56 (paper account).+```++One more share and it is blocked:++```+BLOCK #1 buy TSLA 9 shares, entry+ entry 364.18 (the plan's entry), stop 358.32, target 370.04: risk 5.86 a share+ max loss $52.74 (limit $50), reward:risk 1.00 (min 1)+ today before this: 0 of 3 trades, $0 of $150 daily loss+ - loss: 9 shares x 5.86 risk a share = $52.74 at the stop, over your $50 max loss per trade+```++The same 8 shares checked at 10:55 with the real 10:52 quote (366.48) in+`trader/prices.json` are blocked twice: 8 x 8.16 = $65.28 at the stop, and+reward:risk 0.44. At 9:40 they are blocked by the window (no new entries+before 9:45). The 3:55 PM sell that closes the position passes, even though+it is after the 3:30 entry cutoff: it is an exit.++## Rules++- A PASS only means the order is allowed to be shown to the user. It is not a yes.+- Every number comes from the config, the order, the portfolio, the prices or the broker log.+- Free Yahoo prices are unofficial and can lag; the broker's price is the one that fills, and a+ stop can fill worse than its price in a fast market.++## What it never does++It never places an order, never edits an order to make it pass, never+loosens a limit, never blocks a sell that only gets the user out, and never+treats a PASS as the user's yes.++## Safety++- Education and tooling, not financial advice. A PASS is a rules check, not a recommendation.+- Paper trading by default (`"paper": true`). Going live is the user's own decision, in their own config.+- Nothing in this pack places an order except trader-broker, and only when all three hold: trader-risk+ passed that exact order today, the user typed an explicit yes for that one order in the chat, and the+ user clicked Allow once on Claude's own card because the order tool is set to "Needs approval"+ (Customize > Connectors > tool permissions). Never set an order tool to "Always allow".+- No options, margin, short selling or leverage unless the config allows it and the user confirms.+- Broker keys live in environment variables or the Claude Desktop config, never in the chat.diff --git a/trader-risk/check.py b/trader-risk/check.pynew file mode 100644index 0000000..2e51047--- /dev/null+++ b/trader-risk/check.py@@ -0,0 +1,819 @@+#!/usr/bin/env python3+"""Pre-trade risk check for trader-risk. Standard library only, no network.++Reads the proposed orders (trader/orders.json) and checks every one against+your rules (trader/config.json), your account (trader/portfolio.json),+prices (trader/prices.json) and what was placed today (trader/state/broker.json).+Each order gets PASS or BLOCK with the reasons. Orders are checked in file+order as if each PASS had filled, so buys that are fine one by one but break+a limit together are caught.++ python3 check.py # the trader/ files, writes trader/state/risk.json+ python3 check.py --now "2026-10-19 10:15" # pin the clock (New York time)+ python3 check.py --orders trader/orders.json --json+ python3 check.py --no-write # check without recording the verdicts++Entries and exits. An ENTRY opens or adds to a position (a buy, or a sell+that would go short). An EXIT only reduces what you hold. Getting out must+always be possible: an exit is checked for format, asset and short sales+only; every other rule turns into a warning for it.++What blocks an order (every order):++ format missing symbol or side, both or neither of qty / notional,+ notional on anything but a market day order (Alpaca's rule),+ a limit order without a limit price, unknown type; a bracket+ that is not whole shares, not day / gtc, or misses a leg+ asset options (OCC symbols) unless "allow_options": true; crypto+ and anything that is not a stock or ETF+ short selling more than you hold, unless "allow_short": true++What blocks an entry (on top):++ blocked a ticker on your "blocked" list+ size under min_order_usd, over max_order_usd+ position the stock would be over max_position_pct of the account+ cash the buy would dip into your cash buffer, or need margin+ duplicate the same symbol and side twice in this batch, or already+ placed today (trader/state/broker.json)+ daily limit max_orders_per_day orders placed today+ stop no stop while "require_stop": true (a bracket stop_loss_stop_price+ or the order's plan stop); a stop on the wrong side of the entry+ loss qty x (entry - stop) over max_loss_per_trade_usd. The entry is+ the limit price for a limit order, else the HIGHER of the plan's+ entry and a fresh price (under 15 minutes old), so a stale plan+ cannot understate the risk+ reward:risk (target - entry) / (entry - stop) under min_reward_risk+ daily loss the max losses at the stops of today's entries plus this one+ over max_daily_loss_usd (win or lose, each counts in full)+ trades max_trades_per_day entries already placed today+ window before no_entries_before or after no_entries_after (New York+ time), or the market is closed (weekend, NYSE holiday, outside+ 9:30 to the close; on a 1:00 p.m. early close the window ends+ 3 hours earlier too)+ pdt only with "pdt_guard": true: 3 day trades already in the last+ 5 business days (a 4th would trip the old pattern-day-trader rule)++Exit code 0 when every order passes, 1 when any order is blocked.+The verdicts go to trader/state/risk.json with a fingerprint of each order,+so trader-broker only shows an order as ready if THIS exact order passed today.+"""++import argparse+import datetime+import hashlib+import json+import os+import re+import sys++DEFAULTS = {+ "budget": None, "cash_buffer_pct": 10, "max_position_pct": 75, "max_order_usd": 4000,+ "min_order_usd": 5, "max_loss_per_trade_usd": 50, "max_daily_loss_usd": 150, "max_trades_per_day": 3,+ "max_orders_per_day": 10, "min_reward_risk": 1.0, "require_stop": True,+ "no_entries_before": "09:45", "no_entries_after": "15:30", "flat_by": "15:55",+ "paper": True, "blocked": [], "allow_options": False, "allow_margin": False, "allow_short": False,+ "pdt_guard": False,+}+ALPACA_FIELDS = ("symbol", "side", "qty", "notional", "type", "time_in_force", "limit_price",+ "stop_price", "trail_price", "trail_percent", "extended_hours", "client_order_id",+ "order_class", "take_profit_limit_price", "stop_loss_stop_price",+ "stop_loss_limit_price", "advanced_instructions")+PRICE_FIELDS = ("qty", "notional", "limit_price", "stop_price", "take_profit_limit_price",+ "stop_loss_stop_price", "stop_loss_limit_price")+TYPES = {"market", "limit", "stop", "stop_limit", "trailing_stop"}+TIFS = {"day", "gtc", "opg", "cls", "ioc", "fok"}+OCC = re.compile(r"^[A-Z]{1,6}\d{6}[CP]\d{8}$")+TICKER = re.compile(r"^[A-Z]{1,5}([.\-][A-Z]{1,2})?$")+HHMM = re.compile(r"^([01]?\d|2[0-3]):([0-5]\d)$")+CENT = 0.005+FRESH_MINUTES = 15+REF_WORDS = {"plan": "the plan's entry", "price": "the latest price", "limit": "the limit price",+ "stop price": "the stop price", "stale price": "an old price"}++NYSE_HOLIDAYS = {+ "2026-01-01": "New Year's Day",+ "2026-01-19": "Martin Luther King, Jr. Day",+ "2026-02-16": "Washington's Birthday",+ "2026-04-03": "Good Friday",+ "2026-05-25": "Memorial Day",+ "2026-06-19": "Juneteenth National Independence Day",+ "2026-07-03": "Independence Day (observed)",+ "2026-09-07": "Labor Day",+ "2026-11-26": "Thanksgiving Day",+ "2026-12-25": "Christmas Day",+ "2027-01-01": "New Year's Day",+ "2027-01-18": "Martin Luther King, Jr. Day",+ "2027-02-15": "Washington's Birthday",+ "2027-03-26": "Good Friday",+ "2027-05-31": "Memorial Day",+ "2027-06-18": "Juneteenth National Independence Day (observed)",+ "2027-07-05": "Independence Day (observed)",+ "2027-09-06": "Labor Day",+ "2027-11-25": "Thanksgiving Day",+ "2027-12-24": "Christmas Day (observed)",+}+NYSE_EARLY_CLOSE = { # 1:00 p.m. ET+ "2026-11-27": "day after Thanksgiving",+ "2026-12-24": "Christmas Eve",+ "2027-11-26": "day after Thanksgiving",+}+CALENDAR_YEARS = (2026, 2027)+OPEN = datetime.time(9, 30)+CLOSE = datetime.time(16, 0)+EARLY = datetime.time(13, 0)+++class RiskError(Exception):+ pass+++# ---------------------------------------------------------------- time (New York, no tz files)++def _nth_sunday(year, month, n):+ d = datetime.date(year, month, 1)+ d += datetime.timedelta(days=(6 - d.weekday()) % 7)+ return d + datetime.timedelta(weeks=n - 1)+++def eastern_offset(utc):+ """Hours from UTC for New York: -4 in daylight time, -5 otherwise.+ DST runs from 2:00 a.m. on the second Sunday of March to 2:00 a.m. on the+ first Sunday of November (US rule since 2007)."""+ y = utc.year+ start = datetime.datetime.combine(_nth_sunday(y, 3, 2), datetime.time(7, 0)) # 2:00 EST+ end = datetime.datetime.combine(_nth_sunday(y, 11, 1), datetime.time(6, 0)) # 2:00 EDT+ naive = utc.replace(tzinfo=None)+ return -4 if start <= naive < end else -5+++def to_eastern(utc):+ return utc.replace(tzinfo=None) + datetime.timedelta(hours=eastern_offset(utc))+++def eastern_to_utc(local):+ for off in (-4, -5):+ utc = local - datetime.timedelta(hours=off)+ if eastern_offset(utc) == off:+ return utc+ return local + datetime.timedelta(hours=5)+++def parse_now(text):+ """ISO time -> naive UTC. A time without an offset is taken as New York time."""+ if not text:+ return datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0, tzinfo=None)+ t = text.strip().replace("Z", "+00:00")+ try:+ dt = datetime.datetime.fromisoformat(t)+ except ValueError:+ raise RiskError("--now wants a time like \"2026-10-19 10:15\" (New York) or ...Z (UTC)")+ if dt.tzinfo is None:+ return eastern_to_utc(dt)+ return (dt - dt.utcoffset()).replace(tzinfo=None)+++def parse_utc(text):+ if not text:+ return None+ try:+ dt = datetime.datetime.fromisoformat(str(text).strip().replace("Z", "+00:00"))+ except ValueError:+ return None+ if dt.tzinfo is not None:+ dt = (dt - dt.utcoffset()).replace(tzinfo=None)+ return dt+++def trading_day(d):+ """(is_trading_day, reason). Weekends and the NYSE holiday list."""+ if d.weekday() >= 5:+ return False, "weekend"+ name = NYSE_HOLIDAYS.get(d.isoformat())+ if name:+ return False, "NYSE holiday: " + name+ return True, ""+++def hhmm(value, key):+ """"09:45" -> time(9, 45); None or "" -> None (that bound is off)."""+ if value in (None, "", False):+ return None+ m = HHMM.match(str(value).strip())+ if not m:+ raise RiskError("%s must be a New York time like \"09:45\", got %r" % (key, value))+ return datetime.time(int(m.group(1)), int(m.group(2)))+++def _shift(t, hours):+ dt = datetime.datetime.combine(datetime.date(2000, 1, 1), t) - datetime.timedelta(hours=hours)+ return dt.time()+++def window_check(now_et, c):+ """Reasons an entry cannot be placed now (New York time). Empty when the window is off."""+ before = hhmm(c.get("no_entries_before"), "no_entries_before")+ after = hhmm(c.get("no_entries_after"), "no_entries_after")+ if before is None and after is None:+ return [], []+ warns = []+ d, t = now_et.date(), now_et.time().replace(second=0, microsecond=0)+ if d.year not in CALENDAR_YEARS:+ warns.append("the holiday list covers %s only: check nyse.com for %s"+ % (" and ".join(map(str, CALENDAR_YEARS)), d.isoformat()))+ ok, why = trading_day(d)+ stamp = now_et.strftime("%a %Y-%m-%d %H:%M")+ if not ok:+ return ["window: the market is closed today (%s, %s New York)" % (why, stamp)], warns+ close = EARLY if d.isoformat() in NYSE_EARLY_CLOSE else CLOSE+ if t < OPEN or now_et.time() >= close:+ return ["window: the market is closed (%s New York; the session is %s to %s)"+ % (stamp, OPEN.strftime("%H:%M"), close.strftime("%H:%M"))], warns+ if close == EARLY and after is not None:+ after = _shift(after, 3)+ warns.append("early close at 1:00 p.m. today (%s): no new entries after %s"+ % (NYSE_EARLY_CLOSE[d.isoformat()], after.strftime("%H:%M")))+ if before is not None and t < before:+ return ["window: no new entries before %s New York (it is %s)" % (before.strftime("%H:%M"),+ t.strftime("%H:%M"))], warns+ if after is not None and t > after:+ return ["window: no new entries after %s New York (it is %s)" % (after.strftime("%H:%M"),+ t.strftime("%H:%M"))], warns+ return [], warns+++def business_days(today, n=5):+ """The last n NYSE trading days up to and including today, newest first."""+ out, d = [], today+ for _ in range(40):+ if trading_day(d)[0]:+ out.append(d.isoformat())+ if len(out) == n:+ break+ d -= datetime.timedelta(days=1)+ return out+++# ---------------------------------------------------------------- files and helpers++def read_json(path, what, required=True):+ if not path or not os.path.exists(path):+ if required:+ raise RiskError("no %s at %s" % (what, path))+ return None+ try:+ with open(path, encoding="utf-8") as fh:+ return json.load(fh)+ except json.JSONDecodeError as e:+ raise RiskError("%s is not valid JSON: %s" % (path, e))+++def fingerprint(order):+ """Same function in trader-broker/ticket.py: the exact order that was checked."""+ core = {k: order[k] for k in ALPACA_FIELDS if k in order and order[k] is not None}+ blob = json.dumps(core, sort_keys=True, separators=(",", ":"))+ return hashlib.sha256(blob.encode("utf-8")).hexdigest()[:16]+++def _f(x):+ try:+ return float(x)+ except (TypeError, ValueError):+ return None+++def money(x):+ return "$" + "{:,.2f}".format(float(x)).replace(".00", "")+++def _cent(x):+ """A price to the cent, half up (366.475 -> 366.48)."""+ return int(float(x) * 100 + 0.5 + 1e-9) / 100.0+++def _p(x):+ return "%.2f" % float(x)+++def account(cfg, portfolio, prices):+ """Starting account: cash and position values. No portfolio = a fresh+ account funded with the budget."""+ warnings = []+ if portfolio is None:+ budget = _f(cfg.get("budget"))+ if not budget:+ raise RiskError("no trader/portfolio.json and no budget in the config: "+ "nothing to check the orders against")+ return {"cash": budget, "shares": {}, "values": {}}, warnings+ cash = _f(portfolio.get("cash"))+ if cash is None:+ raise RiskError("portfolio.json needs a \"cash\" number")+ shares, values = {}, {}+ for p in portfolio.get("positions", []):+ t = str(p.get("ticker") or p.get("symbol") or "").upper()+ if not t:+ continue+ n = _f(p.get("shares", p.get("qty")))+ if n is None:+ n = sum(_f(l.get("shares")) or 0 for l in p.get("lots", []))+ shares[t] = shares.get(t, 0) + n+ if prices.get(t):+ values[t] = shares[t] * prices[t]+ else:+ basis = sum(_f(l.get("cost")) or 0 for l in p.get("lots", []))+ values[t] = basis+ warnings.append("no price for %s: valued at its cost basis %s" % (t, money(basis)))+ return {"cash": cash, "shares": shares, "values": values}, warnings+++def rec_day(rec):+ return str(rec.get("date") or str(rec.get("at", ""))[:10])+++def rec_is_entry(rec):+ """trader-broker logs the kind trader-risk gave; older records: a buy is an entry."""+ k = rec.get("kind")+ if k:+ return k == "entry"+ return str(rec.get("side", "")).lower() == "buy"+++def placed_today(state, today):+ """Orders recorded as placed today by trader-broker."""+ out = []+ for rec in (state or {}).get("orders", []):+ if rec.get("status") == "placed" and rec_day(rec) == today:+ out.append(rec)+ return out+++def day_trades(state, today):+ """Day trades in the last 5 business days: a (day, symbol) with both a buy+ and a sell placed or filled that day. An entry placed today counts too: it+ is meant to be flat by the close. Returns (count, sorted list of "day SYM")."""+ days = set(business_days(datetime.date.fromisoformat(today)))+ sides = {}+ for rec in (state or {}).get("orders", []):+ if rec.get("status") not in ("placed", "filled"):+ continue+ d = rec_day(rec)+ if d not in days:+ continue+ key = (d, str(rec.get("symbol", "")).upper())+ sides.setdefault(key, set()).add(str(rec.get("side", "")).lower())+ if d == today and rec.get("status") == "placed" and rec_is_entry(rec):+ sides[key].add("pending")+ hits = sorted("%s %s" % k for k, s in sides.items()+ if ("buy" in s and "sell" in s) or (k[0] == today and "pending" in s))+ return len(hits), hits+++# ---------------------------------------------------------------- the check++def check(orders, cfg, portfolio=None, prices=None, state=None, today=None, now=None, price_times=None):+ """Pure function. Returns {"results": [...], "pass": n, "block": n, "warnings": [...]}.++ now naive UTC (default: the real clock); its New York date is "today"+ price_times {SYM: naive UTC time of that price}; None = every price counts as fresh"""+ c = dict(DEFAULTS)+ c.update(cfg or {})+ prices = {str(k).upper(): float(v) for k, v in (prices or {}).items() if _f(v)}+ now_utc = now or parse_now(None)+ now_et = to_eastern(now_utc)+ today = today or now_et.date().isoformat()+ acct, top_warn = account(c, portfolio, prices)+ blocked = {str(b).upper() for b in c.get("blocked") or []}+ done_today = placed_today(state, today)+ count_today = len(done_today)+ entries_today = [r for r in done_today if rec_is_entry(r)]+ loss_today = 0.0+ for r in entries_today:+ ml = _f(r.get("max_loss"))+ if ml is None:+ top_warn.append("an entry placed today (%s %s) has no max loss in the log; not counted in "+ "the daily loss" % (r.get("side"), r.get("symbol")))+ else:+ loss_today += ml+ placed_keys = {(str(r.get("symbol", "")).upper(), r.get("side")) for r in done_today}+ win_reasons, win_warns = window_check(now_et, c)+ pdt_n, pdt_list = day_trades(state, today) if c.get("pdt_guard") else (0, [])+ seen = set()+ results = []+ batch_entries, batch_loss = 0, 0.0+ if not c.get("paper", True):+ top_warn.append("LIVE account (\"paper\": false): these orders use real money")+ top_warn.extend(win_warns)++ def fresh(sym):+ if sym not in prices:+ return None+ if price_times is None:+ return prices[sym]+ t = price_times.get(sym)+ if t is None:+ return None+ age = (now_utc - t).total_seconds()+ return prices[sym] if -60 <= age <= FRESH_MINUTES * 60 else None++ for i, o in enumerate(orders, 1):+ reasons, warns, info = [], [], []+ later = [] # entry-only reasons, turned into warnings for an exit+ sym = str(o.get("symbol", "")).strip().upper()+ side = str(o.get("side", "")).strip().lower()+ typ = str(o.get("type", "market")).strip().lower()+ tif = str(o.get("time_in_force", "day")).strip().lower()+ qty, notional = o.get("qty"), o.get("notional")+ plan = o.get("plan") if isinstance(o.get("plan"), dict) else {}+ oc = str(o.get("order_class") or "").strip().lower()+ legs = o.get("take_profit_limit_price") is not None or o.get("stop_loss_stop_price") is not None+ bracket = oc == "bracket" or (not oc and legs)+ value = None++ # format+ if not sym:+ reasons.append("format: no symbol")+ if side not in ("buy", "sell"):+ reasons.append("format: side must be buy or sell, got %r" % o.get("side"))+ if (qty is None) == (notional is None):+ reasons.append("format: give exactly one of qty or notional")+ for k in PRICE_FIELDS:+ if o.get(k) is not None:+ v = _f(o.get(k))+ if v is None or v <= 0:+ reasons.append("format: %s must be a positive number, got %r" % (k, o.get(k)))+ elif not isinstance(o.get(k), str):+ warns.append("send %s as a string (\"%s\"), the way place_stock_order types it"+ % (k, o.get(k)))+ if typ not in TYPES:+ reasons.append("format: unknown order type %r" % typ)+ if tif not in TIFS:+ reasons.append("format: unknown time_in_force %r" % tif)+ if notional is not None and (typ != "market" or tif != "day"):+ reasons.append("format: a notional (dollar) order must be a market order with time_in_force day")+ if typ in ("limit", "stop_limit") and o.get("limit_price") is None:+ reasons.append("format: a %s order needs a limit_price" % typ)+ if typ in ("stop", "stop_limit") and o.get("stop_price") is None:+ reasons.append("format: a %s order needs a stop_price" % typ)+ if o.get("extended_hours") and not (typ == "limit" and tif in ("day", "gtc")):+ reasons.append("format: extended hours needs a limit order with time_in_force day or gtc")+ if o.get("stop_loss_limit_price") is not None and o.get("stop_loss_stop_price") is None:+ reasons.append("format: stop_loss_limit_price needs a stop_loss_stop_price")+ if bracket:+ if notional is not None:+ reasons.append("format: a bracket order needs a whole-share qty, not a notional amount")+ elif _f(qty) is not None and abs(_f(qty) - round(_f(qty))) > 1e-9:+ reasons.append("format: a bracket order takes whole shares only, got qty %r" % qty)+ if tif not in ("day", "gtc"):+ reasons.append("format: a bracket order needs time_in_force day or gtc, got %r" % tif)+ if o.get("take_profit_limit_price") is None or o.get("stop_loss_stop_price") is None:+ reasons.append("format: a bracket order needs both take_profit_limit_price and "+ "stop_loss_stop_price")+ elif oc or o.get("advanced_instructions"):+ warns.append("advanced order (%s): check every leg before you say yes"+ % (oc or "advanced_instructions"))++ # asset+ if sym and OCC.match(sym.replace(" ", "")):+ if not c.get("allow_options"):+ reasons.append("asset: %s is an option contract; options are off "+ "(\"allow_options\": false)" % sym)+ else:+ warns.append("option order: options can lose 100%% of what you pay")+ elif sym and ("/" in sym or not TICKER.match(sym)):+ reasons.append("asset: %s does not look like a US stock or ETF ticker; "+ "this pack trades stocks and ETFs only" % sym)++ # the reference price: what one share costs to get in+ plan_entry = _f(plan.get("entry"))+ live = fresh(sym)+ ref, ref_from = None, None+ if typ in ("limit", "stop_limit"):+ ref, ref_from = _f(o.get("limit_price")), "limit"+ elif typ == "stop":+ ref, ref_from = _f(o.get("stop_price")), "stop price"+ if ref is None:+ cands = [(p, w) for p, w in ((plan_entry, "plan"), (live, "price")) if p]+ if cands:+ ref, ref_from = max(cands, key=lambda x: x[0])+ ref = _cent(ref)+ if live and ref_from == "price" and plan_entry and live > plan_entry + CENT:+ info.append("%s last %s is above the plan's entry %s: the risk is measured from %s"+ % (sym, _p(ref), _p(plan_entry), _p(ref)))+ elif sym in prices:+ ref, ref_from = prices[sym], "stale price"+ if plan_entry and live is None and sym in prices and price_times is not None and typ == "market":+ warns.append("the %s price in trader/prices.json is older than %d minutes: not used"+ % (sym, FRESH_MINUTES))+ q = _f(qty)+ if notional is not None and _f(notional):+ value = _f(notional)+ elif q:+ if ref:+ value = q * ref++ # entry or exit+ held = acct["shares"].get(sym, 0.0)+ held_value = acct["values"].get(sym, 0.0)+ exiting = False+ if side == "sell" and held > 1e-9:+ if q is not None:+ exiting = q <= held + 1e-9+ elif value is not None:+ exiting = value <= held_value + CENT+ elif side == "buy" and held < -1e-9 and q is not None:+ exiting = q <= -held + 1e-9+ kind = "exit" if exiting else "entry"+ if kind == "entry" and value is None and q:+ later.append("price: no price for %s to size a %s-share order; add it to "+ "trader/prices.json (trader-alerts: alerts.py quote %s --write)" % (sym, qty, sym))++ # blocked list and size+ if sym in blocked:+ later.append("blocked: %s is on your blocked list" % sym)+ if value is not None:+ if value < float(c.get("min_order_usd") or 0) - CENT:+ later.append("size: %s is under your %s minimum order"+ % (money(value), money(c["min_order_usd"])))+ if c.get("max_order_usd") and value > float(c["max_order_usd"]) + CENT:+ later.append("size: %s is over your %s max order"+ % (money(value), money(c["max_order_usd"])))++ # account effects, simulated in order+ cash = acct["cash"]+ total = cash + sum(acct["values"].values())+ buffer_usd = total * float(c.get("cash_buffer_pct") or 0) / 100.0+ if value is not None and side == "buy" and kind == "entry":+ after_cash = cash - value+ if after_cash < -CENT and not c.get("allow_margin"):+ later.append("cash: needs %s but only %s cash; that would be margin (borrowed money)"+ % (money(value), money(cash)))+ elif after_cash < buffer_usd - CENT:+ later.append("cash: leaves %s cash, under your %s%% buffer of %s"+ % (money(max(after_cash, 0)), _pct(c["cash_buffer_pct"]), money(buffer_usd)))+ pos_after = held_value + value+ limit = total * float(c.get("max_position_pct") or 100) / 100.0+ if total > 0 and pos_after > limit + CENT:+ later.append("position: %s would be %s, %.1f%% of the %s account, over your %s%% cap"+ % (sym, money(pos_after), 100.0 * pos_after / total, money(total),+ _pct(c["max_position_pct"])))+ if side == "sell" and sym and kind == "entry":+ if q is not None:+ over = q > held + 1e-9+ elif value is not None:+ over = value > held_value + CENT+ else:+ over = held <= 0+ if over and not c.get("allow_short"):+ reasons.append("short: selling more %s than you hold (%s shares); short selling is off. "+ "If you bought it, record the fill first (ticket.py fill)" % (sym, _num(held)))++ # day-trade checks: stop, loss, reward:risk, daily loss, trades, window, pdt+ max_loss = risk_ps = rr = stop = target = None+ if kind == "entry" and side in ("buy", "sell"):+ long = side == "buy"+ leg_stop, plan_stop = _f(o.get("stop_loss_stop_price")), _f(plan.get("stop"))+ stop = leg_stop if leg_stop else plan_stop+ target = _f(o.get("take_profit_limit_price")) or _f(plan.get("target"))+ if leg_stop and plan_stop and abs(leg_stop - plan_stop) > CENT:+ warns.append("the bracket stop %s differs from the plan's stop %s: the bracket's is the one "+ "the broker uses" % (_p(leg_stop), _p(plan_stop)))+ if stop and not leg_stop:+ warns.append("the stop %s is in the plan only, not at the broker: set a stop alert "+ "(trader-alerts: alerts.py add --from-plan)" % _p(stop))+ if not stop:+ if c.get("require_stop", True):+ later.append("stop: no stop. Every entry needs one (\"require_stop\": true): a bracket "+ "stop_loss_stop_price, from trader-exit and trader-budget")+ else:+ warns.append("no stop: the max loss is not capped, so it is not counted in the daily loss")+ elif ref:+ if (long and stop >= ref - CENT) or (not long and stop <= ref + CENT):+ later.append("stop: the stop %s must be %s the entry %s for a %s"+ % (_p(stop), "below" if long else "above", _p(ref), side))+ else:+ risk_c = int(round(abs(ref - stop) * 100))+ risk_ps = risk_c / 100.0+ shares = q if q is not None else ((value or 0) / ref)+ max_loss = round(shares * risk_ps, 2)+ cap = _f(c.get("max_loss_per_trade_usd"))+ if cap and max_loss > cap + CENT:+ later.append("loss: %s shares x %s risk a share = %s at the stop, over your %s max loss "+ "per trade" % (_num(shares), _p(risk_ps), money(max_loss), money(cap)))+ min_rr = _f(c.get("min_reward_risk"))+ if target:+ if (long and target <= ref + CENT) or (not long and target >= ref - CENT):+ later.append("target: the target %s must be %s the entry %s"+ % (_p(target), "above" if long else "below", _p(ref)))+ else:+ rr = round(int(round(abs(target - ref) * 100)) / float(risk_c), 2)+ if min_rr and rr < min_rr - 1e-9:+ later.append("reward:risk: %.2f (target %s, entry %s, stop %s) is under your "+ "minimum %s" % (rr, _p(target), _p(ref), _p(stop), _num(min_rr)))+ elif min_rr:+ later.append("reward:risk: no target to measure it against (min_reward_risk %s)"+ % _num(min_rr))+ daily = _f(c.get("max_daily_loss_usd"))+ if daily and max_loss is not None:+ used = loss_today + batch_loss+ if used + max_loss > daily + CENT:+ later.append("daily loss: %s already at risk today plus %s for this one = %s, over your %s "+ "daily loss limit" % (money(used), money(max_loss), money(used + max_loss),+ money(daily)))+ cap_t = int(c.get("max_trades_per_day") or 0)+ if cap_t and len(entries_today) + batch_entries >= cap_t:+ later.append("trades: %d entries placed today plus %d passed earlier in this batch, your limit "+ "is %d a day" % (len(entries_today), batch_entries, cap_t))+ later.extend(win_reasons)+ if c.get("pdt_guard") and pdt_n >= 3:+ later.append("pdt: %d day trades in the last 5 business days (%s); a 4th trips the "+ "pattern-day-trader rule your broker applies (\"pdt_guard\": true)"+ % (pdt_n, ", ".join(pdt_list)))+ if stop and ref and risk_ps:+ info.append("entry %s (%s), stop %s, target %s: risk %s a share"+ % (_p(ref), REF_WORDS.get(ref_from, ref_from), _p(stop),+ _p(target) if target else "none", _p(risk_ps)))+ info.append("max loss %s%s, reward:risk %s%s"+ % (money(max_loss), (" (limit %s)" % money(c["max_loss_per_trade_usd"]))+ if _f(c.get("max_loss_per_trade_usd")) else "",+ ("%.2f" % rr) if rr is not None else "n/a",+ (" (min %s)" % _num(c["min_reward_risk"])) if _f(c.get("min_reward_risk")) else ""))+ if daily or cap_t:+ info.append("today before this: %d of %s trades, %s of %s daily loss"+ % (len(entries_today) + batch_entries, cap_t or "unlimited",+ money(loss_today + batch_loss), money(daily) if daily else "no limit on"))++ # duplicates and the daily order limit+ key = (sym, side)+ if key in seen:+ later.append("duplicate: a second %s %s in this batch" % (side, sym))+ if key in placed_keys:+ later.append("duplicate: a %s %s was already placed today" % (side, sym))+ passed_so_far = sum(1 for r in results if r["verdict"] == "PASS")+ cap_n = int(c.get("max_orders_per_day") or 0)+ if cap_n and count_today + passed_so_far >= cap_n:+ later.append("daily limit: %d placed today plus %d passed earlier in this batch, "+ "your limit is %d a day" % (count_today, passed_so_far, cap_n))+ seen.add(key)++ if kind == "entry":+ reasons.extend(later)+ else:+ warns.extend("exit, not blocked: " + x for x in later)++ verdict = "BLOCK" if reasons else "PASS"+ if verdict == "PASS":+ if kind == "entry" and side in ("buy", "sell"):+ batch_entries += 1+ batch_loss += max_loss or 0.0+ if side == "buy":+ if value is not None:+ acct["cash"] -= value+ acct["values"][sym] = acct["values"].get(sym, 0.0) + value+ if q is not None:+ acct["shares"][sym] = held + q+ elif ref and value is not None:+ acct["shares"][sym] = held + value / ref+ elif side == "sell":+ if value is not None:+ acct["cash"] += value+ acct["values"][sym] = max(acct["values"].get(sym, 0.0) - value, 0.0)+ if q is not None:+ acct["shares"][sym] = held - q+ elif ref and value is not None:+ acct["shares"][sym] = held - value / ref+ results.append({+ "index": i, "symbol": sym, "side": side, "kind": kind,+ "amount": money(_f(notional) or 0) if notional is not None else ("%s shares" % qty),+ "value_usd": round(value, 2) if value is not None else None,+ "entry_ref": round(ref, 2) if ref else None, "entry_ref_from": ref_from,+ "stop": stop, "target": target, "risk_per_share": risk_ps, "max_loss": max_loss,+ "reward_risk": rr, "fingerprint": fingerprint(o), "verdict": verdict,+ "reasons": reasons, "warnings": warns, "info": info,+ })++ return {+ "date": today,+ "now_new_york": now_et.strftime("%Y-%m-%d %H:%M"),+ "paper": bool(c.get("paper", True)),+ "results": results,+ "pass": sum(1 for r in results if r["verdict"] == "PASS"),+ "block": sum(1 for r in results if r["verdict"] == "BLOCK"),+ "warnings": top_warn,+ "cash_after": round(acct["cash"], 2),+ "today": {"orders_placed": count_today, "entries_placed": len(entries_today),+ "loss_at_risk": round(loss_today, 2), "day_trades_5d": pdt_n if c.get("pdt_guard") else None},+ }+++def _pct(x):+ x = float(x)+ return str(int(x)) if x == int(x) else ("%.2f" % x)+++def _num(x):+ x = float(x)+ return str(int(x)) if x == int(x) else ("%.4f" % x).rstrip("0")+++def report(res):+ lines = []+ for w in res["warnings"]:+ lines.append("WARNING: " + w)+ if res["warnings"]:+ lines.append("")+ for r in res["results"]:+ lines.append("%-5s #%d %s %s %s, %s" % (r["verdict"], r["index"], r["side"], r["symbol"], r["amount"],+ r["kind"]))+ for x in r.get("info", []):+ lines.append(" " + x)+ for x in r["reasons"]:+ lines.append(" - " + x)+ for x in r["warnings"]:+ lines.append(" ~ " + x)+ lines.append("")+ lines.append("%d passed, %d blocked at %s New York. Cash after the passed orders: %s (%s account)."+ % (res["pass"], res["block"], res["now_new_york"], money(res["cash_after"]),+ "paper" if res["paper"] else "LIVE"))+ if res["block"]:+ lines.append("Blocked orders do not go to the broker. Fix the order or your rules, then check again.")+ else:+ lines.append("Every order passed. trader-broker still asks you yes or no for each one.")+ lines.append("Education and tooling, not financial advice.")+ return "\n".join(lines)+++def load_prices(pdoc):+ """prices.json -> ({SYM: price}, {SYM: price time as naive UTC or None}).++ The price time is the quote's own time (detail.time), else when it was fetched+ (detail.fetched), else the file's as_of."""+ if not isinstance(pdoc, dict):+ return {}, {}+ prices = pdoc.get("prices", pdoc)+ if not isinstance(prices, dict):+ return {}, {}+ out, times = {}, {}+ as_of = parse_utc(pdoc.get("as_of"))+ detail = pdoc.get("detail") or {}+ for s, p in prices.items():+ if _f(p) is None:+ continue+ s = str(s).upper()+ out[s] = float(p)+ d = detail.get(s) or {}+ times[s] = parse_utc(d.get("time")) or parse_utc(d.get("fetched")) or as_of+ return out, times+++def main(argv=None):+ ap = argparse.ArgumentParser(description="Check proposed orders against your limits (trader-risk).")+ ap.add_argument("--orders", default="trader/orders.json")+ ap.add_argument("--config", default="trader/config.json")+ ap.add_argument("--portfolio", default="trader/portfolio.json",+ help="your account; if missing, a fresh account funded with the budget")+ ap.add_argument("--prices", default="trader/prices.json")+ ap.add_argument("--state", default="trader/state/broker.json", help="what trader-broker placed today")+ ap.add_argument("--now", help="pretend it is this New York time, e.g. \"2026-10-19 10:15\"")+ ap.add_argument("--today", help="YYYY-MM-DD (default: today in New York)")+ ap.add_argument("--out", default="trader/state/risk.json", help="where the verdicts are recorded")+ ap.add_argument("--no-write", action="store_true", help="do not record the verdicts")+ ap.add_argument("--json", action="store_true")+ a = ap.parse_args(argv)+ try:+ now = parse_now(a.now)+ if a.today and not re.match(r"^\d{4}-\d{2}-\d{2}$", a.today):+ raise RiskError("--today wants a date like 2026-10-19")+ doc = read_json(a.orders, "orders file (run trader-budget first)")+ orders = doc.get("orders", doc) if isinstance(doc, dict) else doc+ if not isinstance(orders, list) or not orders:+ raise RiskError("no orders in %s" % a.orders)+ cfg = read_json(a.config, "config", required=False) or {}+ portfolio = read_json(a.portfolio, "portfolio", required=False)+ pdoc = read_json(a.prices, "prices", required=False) or {}+ prices, times = load_prices(pdoc)+ state = read_json(a.state, "broker state", required=False)+ res = check(orders, cfg, portfolio, prices, state, a.today, now, times)+ if pdoc.get("as_of"):+ res["prices_as_of"] = pdoc["as_of"]+ if not a.no_write:+ d = os.path.dirname(a.out)+ if d:+ os.makedirs(d, exist_ok=True)+ rec = dict(res)+ rec["checked_at"] = datetime.datetime.now(datetime.timezone.utc).replace(+ microsecond=0, tzinfo=None).strftime("%Y-%m-%dT%H:%M:%SZ")+ rec["orders_file"] = a.orders+ tmp = a.out + ".tmp"+ with open(tmp, "w", encoding="utf-8") as fh:+ json.dump(rec, fh, indent=2)+ fh.write("\n")+ os.replace(tmp, a.out)+ except RiskError as e:+ print("check.py: %s" % e, file=sys.stderr)+ return 1+ print(json.dumps(res, indent=2) if a.json else report(res))+ return 1 if res["block"] else 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/trader-scanner/SKILL.md b/trader-scanner/SKILL.mdnew file mode 100644index 0000000..96bc6a8--- /dev/null+++ b/trader-scanner/SKILL.md@@ -0,0 +1,203 @@+---+name: trader-scanner+description: >-+ Chart Scanner. Scans thousands of charts for setups: opening-range+ breakouts, flags, oversold bounces. Builds the list of US-listed common+ stocks, ordinary shares and ADRs from Nasdaq Trader's symbol directories,+ runs a pre-market scan of daily closes (20-day closing-high breakout, bull+ flag, reclaimed the 20-day average, oversold, oversold bounce) and an+ intraday opening-range breakout scan on 5-minute bars, then writes+ trader/watchlist.json for trader-news and trader-entry. Free Yahoo data,+ bar by bar. Use when the user says "scan the market", "find me setups",+ "what is breaking out", "opening range breakouts", "scan for bull flags",+ "oversold stocks", "pre-market scan", "build my watchlist", "what should I+ look at today", or at the start of a trading day before /trader-news.+argument-hint: "[universe | daily | orb] [--at HH:MM]"+---++# trader-scanner++The Chart Scanner is the first step of a day trade. It reads thousands of+free charts and lists the ones that match a rule. That is all it does. A scan+is a list of charts that match a rule, not a list of stocks to buy, and a+setup on a chart is not a prediction. Most people who day trade lose money;+the scanner does not change that. It only saves you from flipping through+5,000 charts by hand.++`${CLAUDE_SKILL_DIR}` below is this skill's folder (where this SKILL.md lives).++```bash+python3 "${CLAUDE_SKILL_DIR}/scan.py" universe # -> trader/universe.txt+python3 "${CLAUDE_SKILL_DIR}/scan.py" daily # before the open -> trader/watchlist.json+python3 "${CLAUDE_SKILL_DIR}/scan.py" daily --symbols TSLA,NVDA,AMD # or --watchlist FILE, --limit 200+python3 "${CLAUDE_SKILL_DIR}/scan.py" orb # after 9:50 AM ET -> trader/watchlist.json+python3 "${CLAUDE_SKILL_DIR}/scan.py" orb --at 10:15 # cut the clock at 10:15 AM ET+python3 "${CLAUDE_SKILL_DIR}/scan.py" orb --watchlist trader/watchlist.json --json+```++Flags: `--min-price 5` and `--min-volume` (daily 1,000,000, orb 0),+`--or-minutes 15`, `--max-confirm 200` (orb stage 2),+`--now "2026-10-19 10:15"` (New York time) to pin the clock, `--offline PATH`+to read saved Yahoo files, `--no-write`, `--show N`, `--json`. Exit code 0+when the scan found something, 1 when it found nothing or could not run (the+reason is one plain line).++## What it reads and writes++| file | what |+| --- | --- |+| `trader/universe.txt` | written by `universe`: one `SYMBOL\|Name` a line, read by `daily` and `orb` |+| `trader/watchlist.json` | written by `daily` and `orb`: `mode`, `as_of`, `universe`, `scanned`, `failed`, `hits[]`. trader-news and trader-entry read `hits[].symbol` |+| `trader/config.json` | read by `orb`: `no_entries_after` (default 15:30) |++## The universe++`universe` downloads `nasdaqlisted.txt` and `otherlisted.txt` from+nasdaqtrader.com/dynamic/SymDir and keeps a row when, in this order:++1. It is not a test issue, not an ETF, not NextShares.+2. It is a plain ticker: 1 to 5 letters, or 1 to 4 letters plus one class+ letter after a dot (BRK.B). A `$` preferred (ABR$D) is out, and so is a+ `.U`, `.W` or `.R` suffix (units, warrants, rights).+3. Out, whatever else the name says: warrants; SPAC units and rights ("Units,+ each consisting of", "Rights to receive"); notes, ETNs, debentures; a %+ coupon; "Depositary Shares" that are not American or Global (those carry a+ preferred).+4. In: the name calls it common stock, common shares or units, ordinary+ shares, shares of beneficial interest, ADS / ADR / American or Global+ depositary shares, or partnership or trust units.+5. Out: the name still says unit, right, bond, preferred or preference.+6. In: everything else (plain names like "AMETEK, Inc.").++On the Oct 19 2026 files this keeps 5,943. The reel said 5,259: that count+came from an ad hoc filter (names that say common or ordinary, no ADRs). All+5,259 of those are in this list; the 684 extra are mostly ADRs, closed-end+funds and partnership units. The Oct 20 files gave 5,942.++## The daily scan (before the open)++Yahoo's spark endpoint returns closes for 20 symbols a request, so 5,942+symbols take 298 requests. On Oct 20 2026 that took 145 seconds with the+polite pause (0.3 s). Liquidity comes from the spark meta: last price at+least `--min-price` and last session's volume at least `--min-volume`. Run it+before the open or after the close: during the session the volume is the+day's so far, and today's daily bar is left out until 4:00 PM.++The setups are computed from daily closes only (spark has no highs or lows),+so they are close cousins of the reel's `refs/scan.py`, which used highs and+lows:++| setup | the rule on closes |+| --- | --- |+| `breakout_20d` | the last close is above every close of the 20 sessions before it |+| `bull_flag` | up more than 10 % over the 10 sessions before the last 5, then the last 5 closes inside a 5 % range |+| `reclaim_ma20` | the close before was under its 20-day average, the last close is above it |+| `oversold` | RSI 14 (Wilder) under 30 |+| `oversold_bounce` | RSI 14 was under 30 yesterday and today closed up |++A closing-high breakout fires more often than an intraday-high one (KO on+Oct 16 broke its 20-day closing high, not its 20-day intraday high). Hits are+listed most traded first (price times volume).++## The opening-range breakout scan (during the session)++The opening range is the first `--or-minutes` (15) of the session: the 9:30,+9:35 and 9:40 five-minute bars. A hit is the first completed 5-minute bar+to CLOSE above the range high, at that bar's close time.++1. Stage 1, every symbol: spark closes of today's 5-minute bars, 20 a+ request. A chart goes on only if a completed bar after the range closed at+ or above the highest close of the range. That is a necessary condition+ (the range high is at least every range close), so no breakout is lost.+2. Stage 2, each candidate: the v8 chart with real highs and lows, one+ request each. Range high = the highest high of the range bars, range low =+ the lowest low. On a strong morning most charts are candidates, so stage 2+ checks at most `--max-confirm` (200) of them, the most traded first (price+ times volume so far), and prints PARTIAL with the count it skipped.+ `--max-confirm 0` checks them all.++Timing, live on Tue Oct 20 2026 (a strong morning): 100 liquid names at+10:01 AM took 35 seconds (5 spark requests, 70 v8 charts, 51 of 91 usable+charts broke out). The whole universe at 10:03 AM took about 4 minutes (298+spark requests, then 200 v8 charts): 2,448 usable charts, 1,782 candidates,+the 200 most traded checked, 119 of those broke out. For a fast answer, scan+the daily watchlist or a list of names you trade (`--watchlist`, `--symbols`).++A chart is usable only when every 5-minute bar from 9:30 to the cutoff is+there; a missing bar means a halt or a thin stock. Null closes are dropped,+a bar off the 5-minute grid (the live tick, like 10:58:07) is dropped, and a+bar counts only once it is complete (start + 5 minutes). Before 9:50 AM, on a+weekend or holiday, after the close, or after `no_entries_after` (an expired+setup) it prints one plain line and writes nothing. The 1:00 PM early closes+are in the calendar.++## Data and limits++- Yahoo's chart and spark endpoints are free, unofficial and can lag. Bars are+ 5-minute bars, bar by bar, never tick by tick. query2 first, query1 on a 429+ or 5xx, one retry after a 5-second wait on a 429.+- Partial results are said as partial: "Fetched 4,980 of 5,259 charts (279+ failed or had no data)". Never round a partial scan up to "the whole market".+- NYSE holidays and early closes for 2026 and 2027 (nyse.com, read 2026-10-13).++## Steps++1. Once a week or so: `scan.py universe`.+2. Before the open: `scan.py daily`. Tell the user the counts (fetched,+ liquid, scanned, hits) and the top few by setup.+3. After 9:50 AM ET (10:15 is the classic): `scan.py orb`. Tell the user how+ many usable charts broke their range and when, and that a later hit is+ closer to the price now.+4. The user picks one chart. Hand it on: `/trader-news TICKER` (what is moving+ it), then `/trader-entry TICKER` (the entry bar by bar). Never pick for them.++## Example: the reel++Monday Oct 19 2026, scan at 10:15 AM over the reel's 234-ticker wall+(`tests/fixtures/trader-scanner/wall5m-2026-10-19.json.gz`, real Yahoo charts):++```+python3 scan.py orb --offline wall5m-2026-10-19.json.gz --now "2026-10-19 10:15" --min-price 0+Fetched 233 of 234 charts (1 failed or had no data); 231 usable; 95 candidates, 95 confirmed with real highs and lows.+42 of 231 charts closed above their opening-range high by 10:15 AM:+ 9:50 AM AMC $2.97 range 2.90 to 2.96 +0.50% over+ ...+ 10:15 AM TSLA $364.18 range 354.47 to 362.18 +0.55% over+```++The reel's wall had no price floor (AMC at $2.97 is one of the 42), hence+`--min-price 0`; with the default $5 floor it is 41. TSLA's range is the 9:30+to 9:40 bars, high 362.18, low 354.47; the 10:10 bar closed at 364.18, 0.55 %+over the high, at 10:15 AM. The user picks TSLA and Claude hands it to+`/trader-news TSLA`, then `/trader-entry TSLA`. In the reel the universe was+5,259 US stocks; this tool's rule gives 5,943 on the same files.++The pre-market scan that morning (closes through Fri Oct 16, the reel's daily+charts) tags BLK, CI, XOM and HD a 20-day breakout, CCL a bull flag, F, JPM+and GE a reclaim of the 20-day average, and BAC, MS, RIVN and PLUG oversold,+as the reel did. On closes it also tags KO (breakout), RCL (flag) and PNC (an+oversold bounce).++## Rules++- Say what was scanned: how many symbols, how many charts came back, how many+ were usable, and the time of the data.+- Say "matched a rule", never "a buy", "a winner" or "a good trade".+- Never print a P&L, a return or a profit figure.+- A hit is stale once the price has moved on. Re-run before acting on it.++## What it never does++It never places, sizes or checks an order, never says which stock to buy,+never calls data real time, and never promises that a setup works.++## Safety++- Education and tooling, not financial advice. A PASS is a rules check, not a recommendation.+- Paper trading by default (`"paper": true`). Going live is the user's own decision, in their own config.+- Nothing in this pack places an order except trader-broker, and only when all three hold: trader-risk+ passed that exact order today, the user typed an explicit yes for that one order in the chat, and the+ user clicked Allow once on Claude's own card because the order tool is set to "Needs approval"+ (Customize > Connectors > tool permissions). Never set an order tool to "Always allow".+- No options, margin, short selling or leverage unless the config allows it and the user confirms.+- Broker keys live in environment variables or the Claude Desktop config, never in the chat.diff --git a/trader-scanner/scan.py b/trader-scanner/scan.pynew file mode 100644index 0000000..3dfc541--- /dev/null+++ b/trader-scanner/scan.py@@ -0,0 +1,1083 @@+#!/usr/bin/env python3+"""Chart Scanner for trader-scanner: scan thousands of charts for setups. Standard library only.++ python3 scan.py universe # Nasdaq Trader lists -> trader/universe.txt+ python3 scan.py daily # before the open: daily setups -> trader/watchlist.json+ python3 scan.py daily --symbols TSLA,NVDA,AMD # or --watchlist FILE, or --limit 200+ python3 scan.py orb # after 9:50 AM ET: opening-range breakouts so far+ python3 scan.py orb --at 10:15 --or-minutes 15 # cut the clock at 10:15 AM ET+ python3 scan.py orb --offline wall5m.json.gz --now "2026-10-19 10:15" --min-price 0++universe Downloads Nasdaq Trader's symbol directories (nasdaqlisted.txt and+ otherlisted.txt) and keeps US-listed common stocks, ordinary shares+ and ADRs. The rule, in order:+ 1. not a test issue, not an ETF, not NextShares+ 2. a plain ticker: 1 to 5 letters, or 1 to 4 letters plus one+ class letter after a dot (BRK.B); a .U / .W / .R suffix+ (units, warrants, rights) is out, and so is a $ preferred+ 3. out, whatever else the name says: warrants; SPAC units and+ rights ("Units, each consisting of", "Rights to receive");+ notes, ETNs, debentures; a % coupon; "Depositary Shares" that+ are not American or Global (those carry a preferred)+ 4. in: the name calls it common stock / shares / units, ordinary+ shares, shares of beneficial interest, ADS / ADR / American or+ Global depositary shares, or partnership / trust units+ 5. out: the name still says unit, right, bond, preferred or preference+ 6. in: everything else (plain names like "AMETEK, Inc.")++daily Pre-market scan of daily CLOSES (Yahoo spark: 20 symbols a request,+ 3 months of 1-day bars, closes only). Liquidity from the spark meta:+ regularMarketPrice >= --min-price (5) and regularMarketVolume >=+ --min-volume (1,000,000). Setups, from closes only:+ breakout_20d the last close is above every close of the 20 before it+ bull_flag up more than 10 % over the 10 sessions before the+ last 5, then the last 5 closes inside a 5 % range+ reclaim_ma20 closed under the 20-day average, then closed above it+ oversold RSI 14 (Wilder) under 30+ oversold_bounce RSI 14 was under 30 yesterday and today closed up+ Today's daily bar is dropped until the session's close.++orb Opening-range breakouts, 5-minute bars. The range is the first+ --or-minutes (15) of the session. Stage 1: spark closes for every+ symbol (1 day of 5-minute bars, 20 a request); a chart goes on only+ if a completed bar after the range closed at or above the highest+ close of the range (a necessary condition). Stage 2: each candidate's+ v8 chart (real highs and lows): range high = the highest high of the+ range bars, a hit = the first completed bar to CLOSE above it, at that+ bar's close time. Stage 2 fetches at most --max-confirm (200) charts,+ the most traded candidates first (price x volume so far), and says+ so when it stops short. A chart is usable only when every 5-minute+ bar from 9:30 to the cutoff is there (a missing bar is a halt or no+ trades). Floors: --min-price 5 (last close), --min-volume 0.++Bars: null closes are dropped, a bar off the 5-minute grid (the live tick,+like 10:49:45) is dropped, and a bar counts only once it is complete+(start + 5 minutes <= the clock). Times are New York (ET). --now pins the+clock ("2026-10-19 10:15", New York time; ...Z for UTC).++Yahoo's endpoints are free, unofficial and can lag. query2 first, query1 on+a 429 or 5xx, one retry after a pause on a 429. A polite pause between+requests (--pause). Partial results are reported as partial.++--offline PATH reads files instead of the network: universe wants a folder+with nasdaqlisted.txt and otherlisted.txt; daily and orb take a folder of+<T>.json v8 chart files or spark responses, or one file that is a spark+response, a v8 chart, or a bundle {"TSLA": <v8 json>, ...}. .json.gz is fine.++A scan is a list of charts that match a rule, not a list of stocks to buy.+Exit code 0 when the scan found something, 1 when it did not or could not run.+"""++import argparse+import datetime+import gzip+import json+import os+import re+import sys+import time+import urllib.error+import urllib.request++UA = "Mozilla/5.0 (compatible; day-trader-skill/2.0; +https://github.com/Jakeschincariol/day-trader-skill)"+YAHOO_HOSTS = ("https://query2.finance.yahoo.com", "https://query1.finance.yahoo.com")+NASDAQ_FILES = ("nasdaqlisted.txt", "otherlisted.txt")+NASDAQ_URL = "https://www.nasdaqtrader.com/dynamic/SymDir/"+SPARK_MAX = 20 # Yahoo's spark answers 400 above 20 symbols+PAUSE = 0.3 # seconds between requests: be polite to free endpoints+BACKOFF = 5.0 # seconds to wait before the one retry after a 429+SLEEP = time.sleep # tests swap this out+BAR_MIN = 5+MAX_CONFIRM = 200 # stage-2 v8 charts per orb scan, most traded first+MIN_DAILY_BARS = 30+DEFAULT_UNIVERSE = "trader/universe.txt"+NOTE = "A scan is a list of charts that match a rule, not a list of stocks to buy."++NYSE_HOLIDAYS = {+ "2026-01-01": "New Year's Day",+ "2026-01-19": "Martin Luther King, Jr. Day",+ "2026-02-16": "Washington's Birthday",+ "2026-04-03": "Good Friday",+ "2026-05-25": "Memorial Day",+ "2026-06-19": "Juneteenth National Independence Day",+ "2026-07-03": "Independence Day (observed)",+ "2026-09-07": "Labor Day",+ "2026-11-26": "Thanksgiving Day",+ "2026-12-25": "Christmas Day",+ "2027-01-01": "New Year's Day",+ "2027-01-18": "Martin Luther King, Jr. Day",+ "2027-02-15": "Washington's Birthday",+ "2027-03-26": "Good Friday",+ "2027-05-31": "Memorial Day",+ "2027-06-18": "Juneteenth National Independence Day (observed)",+ "2027-07-05": "Independence Day (observed)",+ "2027-09-06": "Labor Day",+ "2027-11-25": "Thanksgiving Day",+ "2027-12-24": "Christmas Day (observed)",+}+NYSE_EARLY_CLOSE = { # 1:00 p.m. ET+ "2026-11-27": "day after Thanksgiving",+ "2026-12-24": "Christmas Eve",+ "2027-11-26": "day after Thanksgiving",+}+CALENDAR_YEARS = (2026, 2027)+OPEN = datetime.time(9, 30)+CLOSE = datetime.time(16, 0)+EARLY = datetime.time(13, 0)++SETUPS = [+ ("breakout_20d", "20-day closing-high breakout"),+ ("bull_flag", "bull flag"),+ ("reclaim_ma20", "reclaimed the 20-day average"),+ ("oversold", "oversold (RSI under 30)"),+ ("oversold_bounce", "oversold bounce"),+]+LABEL = dict(SETUPS)+++class ScanError(Exception):+ pass+++# ---------------------------------------------------------------- time++def _nth_sunday(year, month, n):+ d = datetime.date(year, month, 1)+ d += datetime.timedelta(days=(6 - d.weekday()) % 7)+ return d + datetime.timedelta(weeks=n - 1)+++def eastern_offset(utc):+ """Hours from UTC for New York: -4 in daylight time, -5 otherwise.+ DST runs from 2:00 a.m. on the second Sunday of March to 2:00 a.m. on the+ first Sunday of November (US rule since 2007)."""+ y = utc.year+ start = datetime.datetime.combine(_nth_sunday(y, 3, 2), datetime.time(7, 0)) # 2:00 EST+ end = datetime.datetime.combine(_nth_sunday(y, 11, 1), datetime.time(6, 0)) # 2:00 EDT+ naive = utc.replace(tzinfo=None)+ return -4 if start <= naive < end else -5+++def to_eastern(utc):+ return utc.replace(tzinfo=None) + datetime.timedelta(hours=eastern_offset(utc))+++def eastern_to_utc(local):+ for off in (-4, -5):+ utc = local - datetime.timedelta(hours=off)+ if eastern_offset(utc) == off:+ return utc+ return local + datetime.timedelta(hours=5)+++def ts_to_eastern(ts):+ """Unix seconds -> naive New York time. Never uses the machine's time zone."""+ return to_eastern(datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=int(ts)))+++def parse_now(text):+ """ISO time -> naive UTC. A time without an offset is taken as New York time."""+ if not text:+ return datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0, tzinfo=None)+ t = text.strip().replace("Z", "+00:00")+ try:+ dt = datetime.datetime.fromisoformat(t)+ except ValueError:+ raise ScanError('--now wants a time like "2026-10-19 10:15" (New York) or ...Z (UTC)')+ if dt.tzinfo is None:+ return eastern_to_utc(dt)+ return (dt - dt.utcoffset()).replace(tzinfo=None)+++def parse_hhmm(text, flag="--at"):+ m = re.match(r"^\s*(\d{1,2}):(\d{2})\s*$", text or "")+ if not m or int(m.group(1)) > 23 or int(m.group(2)) > 59:+ raise ScanError("%s wants a New York time like 10:15" % flag)+ return datetime.time(int(m.group(1)), int(m.group(2)))+++def trading_day(d):+ """(is_trading_day, reason). Weekends and the NYSE holiday list."""+ if d.weekday() >= 5:+ return False, "weekend"+ name = NYSE_HOLIDAYS.get(d.isoformat())+ if name:+ return False, "NYSE holiday: " + name+ return True, ""+++def session(d):+ """(open_time, close_time) in New York time, or None if closed all day."""+ ok, _ = trading_day(d)+ if not ok:+ return None+ return OPEN, (EARLY if d.isoformat() in NYSE_EARLY_CLOSE else CLOSE)+++def clock_label(t):+ """datetime or time -> '10:15 AM'."""+ h = t.hour % 12 or 12+ return "%d:%02d %s" % (h, t.minute, "AM" if t.hour < 12 else "PM")+++def day_label(d):+ return "%s %s" % (d.strftime("%a"), d.isoformat())+++# ---------------------------------------------------------------- network++def http_get(url, timeout=20):+ req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "*/*"})+ with urllib.request.urlopen(req, timeout=timeout) as r:+ return r.read().decode("utf-8", "replace")+++def yahoo_get(path):+ """GET a Yahoo Finance path. query2 first, query1 on a 429 or 5xx, and one+ more round after BACKOFF seconds if a 429 was seen. 4xx other than 429 is final."""+ last = "no answer"+ for attempt in (0, 1):+ saw_429 = False+ for host in YAHOO_HOSTS:+ try:+ return http_get(host + path)+ except urllib.error.HTTPError as e:+ last = "HTTP %d" % e.code+ try:+ body = e.read().decode("utf-8", "replace") if 400 <= e.code < 500 and e.code != 429 else ""+ except Exception:+ body = ""+ finally:+ e.close()+ if e.code == 429:+ saw_429 = True+ continue+ if e.code >= 500:+ continue+ if body.strip().startswith("{"):+ return body # Yahoo's JSON error ("No data found"), parsed by the caller+ raise ScanError("Yahoo answered %s for %s" % (last, path.split("?")[0]))+ except (urllib.error.URLError, OSError) as e:+ last = str(getattr(e, "reason", e))+ continue+ if attempt == 0 and saw_429:+ SLEEP(BACKOFF)+ continue+ break+ raise ScanError("Yahoo answered %s for %s" % (last, path.split("?")[0]))+++def to_yahoo(sym):+ return sym.upper().replace(".", "-")+++def spark_path(symbols, rng, interval):+ return "/v7/finance/spark?symbols=%s&range=%s&interval=%s" % (+ ",".join(to_yahoo(s) for s in symbols), rng, interval)+++def chart_path(sym, rng, interval):+ return "/v8/finance/chart/%s?range=%s&interval=%s" % (to_yahoo(sym), rng, interval)+++# ---------------------------------------------------------------- parsing++def series_from_result(res):+ """A Yahoo chart result (v8 or one spark response) -> plain lists."""+ q = ((res.get("indicators") or {}).get("quote") or [{}])[0] or {}+ t = res.get("timestamp") or []+ n = len(t)++ def col(k):+ v = q.get(k)+ return list(v) + [None] * (n - len(v)) if isinstance(v, list) else None+ return {"t": list(t), "c": col("close") or [None] * n, "o": col("open"), "h": col("high"),+ "l": col("low"), "v": col("volume"), "meta": res.get("meta") or {}}+++def parse_spark(text_or_doc, wanted=None):+ """Spark JSON -> {SYM: series}. Symbols Yahoo does not know are simply missing+ from the answer. `wanted` maps Yahoo symbols back to ours (BRK-B -> BRK.B)."""+ doc = json.loads(text_or_doc) if isinstance(text_or_doc, str) else text_or_doc+ sp = (doc or {}).get("spark") if isinstance(doc, dict) else None+ if not isinstance(sp, dict):+ raise ScanError("Yahoo's spark answer is not the shape this tool knows")+ err = sp.get("error")+ out = {}+ for item in sp.get("result") or []:+ resp = item.get("response") or []+ if not resp:+ continue+ ysym = item.get("symbol") or (resp[0].get("meta") or {}).get("symbol") or ""+ sym = (wanted or {}).get(ysym.upper(), ysym.upper().replace("-", "."))+ out[sym] = series_from_result(resp[0])+ if err and not out:+ raise ScanError("Yahoo spark: %s" % (err.get("description") or err.get("code") or err))+ return out+++def parse_chart(text_or_doc, sym=""):+ """v8 chart JSON -> series. Raises ScanError for Yahoo's 'no data' answers."""+ try:+ doc = json.loads(text_or_doc) if isinstance(text_or_doc, str) else text_or_doc+ chart = doc["chart"]+ except (ValueError, KeyError, TypeError):+ raise ScanError("Yahoo returned something unexpected for %s" % sym)+ res = chart.get("result")+ if not res:+ err = chart.get("error") or {}+ raise ScanError("no data for %s: %s" % (sym, err.get("description", "unknown ticker")))+ return series_from_result(res[0])+++def _read_maybe_gz(path):+ if path.endswith(".gz"):+ with gzip.open(path, "rt", encoding="utf-8") as fh:+ return fh.read()+ with open(path, encoding="utf-8") as fh:+ return fh.read()+++def _stem(name):+ for ext in (".json.gz", ".json"):+ if name.endswith(ext):+ return name[:-len(ext)]+ return name+++def _absorb(doc, name_hint, data, errors):+ """One parsed offline JSON doc -> data / errors."""+ if isinstance(doc, dict) and "spark" in doc:+ data.update(parse_spark(doc))+ elif isinstance(doc, dict) and "chart" in doc:+ sym = name_hint+ if not sym:+ try:+ sym = (doc["chart"].get("result") or [{}])[0]["meta"]["symbol"]+ except (AttributeError, KeyError, TypeError, IndexError):+ raise ScanError("an offline v8 chart without a symbol: name the file <TICKER>.json")+ sym = sym.upper().replace("-", ".")+ try:+ data[sym] = parse_chart(doc, sym)+ except ScanError as e:+ errors[sym] = str(e)+ elif isinstance(doc, dict):+ for k, v in doc.items():+ _absorb(v, k, data, errors)+ else:+ raise ScanError("offline file %s is not a spark answer, a v8 chart or a bundle" % name_hint)+++def load_offline(path):+ """A folder of <T>.json(.gz) files or one file -> ({SYM: series}, {SYM: error})."""+ data, errors = {}, {}+ if os.path.isdir(path):+ names = sorted(f for f in os.listdir(path) if f.endswith((".json", ".json.gz")))+ if not names:+ raise ScanError("no .json files in %s" % path)+ for f in names:+ try:+ doc = json.loads(_read_maybe_gz(os.path.join(path, f)))+ except ValueError as e:+ raise ScanError("%s is not valid JSON: %s" % (f, e))+ if isinstance(doc, dict) and ("chart" in doc or "spark" in doc):+ _absorb(doc, "" if "spark" in doc else _stem(f), data, errors)+ else:+ _absorb(doc, "", data, errors)+ elif os.path.isfile(path):+ try:+ doc = json.loads(_read_maybe_gz(path))+ except ValueError as e:+ raise ScanError("%s is not valid JSON: %s" % (path, e))+ _absorb(doc, "", data, errors)+ else:+ raise ScanError("no offline file or folder at %s" % path)+ return data, errors+++# ---------------------------------------------------------------- universe++TICKER = re.compile(r"^[A-Z]{1,5}$|^[A-Z]{1,4}\.[A-Z]$")+ALWAYS_OUT = [+ ("warrant", re.compile(r"\bwarrants?\b")),+ ("unit or right", re.compile(r"\b(units?|rights?),? (each|that|entitling)\b|(?<!the )\brights? to\b")),+ ("note", re.compile(r"\b(notes?|etns?|debentures?)\b")),+ ("coupon", re.compile(r"%")),+ ("depositary", re.compile(r"(?<!american )(?<!global )\bdepositary shares?\b")),+]+COMMON = re.compile(+ r"\bcommon (stock|shares?|units?)\b|\bord(inary)? shares?\b|\bshares? of beneficial interest\b"+ r"|\b(american|global) deposit[ao]ry\b|\bads[s]?\b|\badrs?\b"+ r"|\b(limited partnership|partnership|trust) units?\b|\bl\.?p\.? units?\b"+ r"|\bunits? (of|representing)\b.*\b(limited partner|partnership|beneficial interest|limited liability)")+SOFT_OUT = [+ ("unit", re.compile(r"\bunits?\b")),+ ("right", re.compile(r"\brights?\b")),+ ("bond", re.compile(r"\bbonds?\b")),+ ("preferred", re.compile(r"\bpreferred\b|\bpreference\b")),+]+++def classify(row):+ """One symbol-directory row -> 'keep' or the rule that drops it."""+ sym = (row.get("Symbol") or row.get("ACT Symbol") or "").strip()+ if (row.get("Test Issue") or "").strip() != "N":+ return "test issue"+ if (row.get("ETF") or "").strip() != "N":+ return "ETF"+ if (row.get("NextShares") or "N").strip() != "N":+ return "NextShares"+ if not TICKER.match(sym):+ return "not a plain ticker"+ if re.search(r"\.[UWR]$", sym):+ return "unit / warrant / right suffix"+ name = " ".join((row.get("Security Name") or "").lower().split())+ for tag, rx in ALWAYS_OUT:+ if rx.search(name):+ return tag+ if COMMON.search(name):+ return "keep"+ for tag, rx in SOFT_OUT:+ if rx.search(name):+ return tag+ return "keep"+++def parse_symdir(text):+ """Nasdaq Trader pipe file -> (rows, file_created). The last line is 'File Creation Time: ...'."""+ lines = [ln for ln in text.replace("\r", "").split("\n") if ln.strip()]+ if not lines or "|" not in lines[0]:+ raise ScanError("not a Nasdaq Trader symbol directory")+ hdr = [h.strip() for h in lines[0].split("|")]+ if "Security Name" not in hdr or not ({"Symbol", "ACT Symbol"} & set(hdr)):+ raise ScanError("not a Nasdaq Trader symbol directory (header %s)" % lines[0][:60])+ rows, created = [], None+ for ln in lines[1:]:+ if ln.startswith("File Creation Time"):+ m = re.search(r"(\d{2})(\d{2})(\d{4})(\d{2}):(\d{2})", ln)+ if m:+ created = "%s-%s-%s %s:%s" % (m.group(3), m.group(1), m.group(2), m.group(4), m.group(5))+ continue+ rows.append(dict(zip(hdr, ln.split("|"))))+ return rows, created+++def build_universe(texts):+ """{filename: text} -> (kept [(SYM, name)], counts, created)."""+ kept, counts, created = {}, {}, None+ for fname in NASDAQ_FILES:+ if fname not in texts:+ raise ScanError("missing %s" % fname)+ rows, c = parse_symdir(texts[fname])+ created = created or c+ counts["rows"] = counts.get("rows", 0) + len(rows)+ for r in rows:+ why = classify(r)+ counts[why] = counts.get(why, 0) + 1+ if why == "keep":+ sym = (r.get("Symbol") or r.get("ACT Symbol")).strip()+ kept[sym] = " ".join((r.get("Security Name") or "").split())+ return sorted(kept.items()), counts, created+++# ---------------------------------------------------------------- daily setups++def rsi(closes, n=14):+ """Wilder's RSI on closes (the same math as the reel's refs/scan.py)."""+ if len(closes) < n + 1:+ return None+ g = [max(0.0, closes[i] - closes[i - 1]) for i in range(1, len(closes))]+ lo = [max(0.0, closes[i - 1] - closes[i]) for i in range(1, len(closes))]+ ag, al = sum(g[:n]) / n, sum(lo[:n]) / n+ for i in range(n, len(g)):+ ag = (ag * (n - 1) + g[i]) / n+ al = (al * (n - 1) + lo[i]) / n+ return 100 - 100 / (1 + ag / al) if al else 100.0+++def daily_closes(series, now_utc):+ """[(date, close)] of COMPLETE daily bars: null closes dropped, today's bar dropped+ until the session closes, anything dated after the clock dropped."""+ now = to_eastern(now_utc)+ today = now.date()+ s = session(today)+ today_done = s is None or now.time() >= s[1]+ out = {}+ for ts, c in zip(series["t"], series["c"]):+ if c is None:+ continue+ d = ts_to_eastern(ts).date()+ if d > today or (d == today and not today_done):+ continue+ out[d] = float(c) # one bar a day: a late duplicate (the live tick) wins+ return sorted(out.items())+++def find_setups(closes):+ """closes (oldest first, >= 30) -> (setup keys, numbers)."""+ c = closes+ last = c[-1]+ hi20 = max(c[-21:-1])+ ma20 = sum(c[-20:]) / 20.0+ ma20_prev = sum(c[-21:-1]) / 20.0+ run = c[-6] / c[-16] - 1+ rng5 = (max(c[-5:]) - min(c[-5:])) / last+ r = rsi(c)+ r_prev = rsi(c[:-1])+ tags = []+ if last > hi20:+ tags.append("breakout_20d")+ if run > 0.10 and rng5 < 0.05:+ tags.append("bull_flag")+ if c[-2] < ma20_prev and last > ma20:+ tags.append("reclaim_ma20")+ if r is not None and r < 30:+ tags.append("oversold")+ if r_prev is not None and r_prev < 30 and last > c[-2]:+ tags.append("oversold_bounce")+ return tags, {"rsi": r, "rsi_prev": r_prev, "high20": hi20, "ma20": ma20,+ "run_pct": run * 100, "range5_pct": rng5 * 100}+++def scan_daily(data, symbols, now_utc, min_price, min_volume):+ """Pure. data = {SYM: series}. Returns (hits, counts, last_date)."""+ hits, dates = [], {}+ counts = {"requested": len(symbols), "fetched": 0, "illiquid": 0, "short": 0, "scanned": 0}+ for sym in symbols:+ s = data.get(sym)+ if not s:+ continue+ counts["fetched"] += 1+ bars = daily_closes(s, now_utc)+ meta = s.get("meta") or {}+ price = meta.get("regularMarketPrice")+ if price is None and bars:+ price = bars[-1][1]+ vol = meta.get("regularMarketVolume")+ if price is None or price < min_price or (min_volume > 0 and (vol is None or vol < min_volume)):+ counts["illiquid"] += 1+ continue+ if len(bars) < MIN_DAILY_BARS:+ counts["short"] += 1+ continue+ counts["scanned"] += 1+ d_last = bars[-1][0]+ dates[d_last] = dates.get(d_last, 0) + 1+ closes = [c for _, c in bars]+ tags, nums = find_setups(closes)+ if tags:+ hits.append({"symbol": sym, "setups": tags, "price": round(closes[-1], 2),+ "close_date": d_last.isoformat(), "rsi": round(nums["rsi"], 1),+ "volume": int(vol) if vol is not None else None})+ hits.sort(key=lambda h: (-(h["price"] * (h["volume"] or 0)), h["symbol"])) # most dollars traded first+ last_date = max(dates, key=lambda d: (dates[d], d)) if dates else None+ counts["hits"] = len(hits)+ return hits, counts, last_date+++# ---------------------------------------------------------------- opening-range breakout++def slot(day, k):+ return datetime.datetime.combine(day, OPEN) + datetime.timedelta(minutes=BAR_MIN * k)+++def session_bars(series, day, cutoff):+ """5-minute bars of `day` that are complete at `cutoff` (naive New York time),+ on the grid, with a close. Sorted, one per slot."""+ s = session(day)+ close_t = s[1] if s else CLOSE+ out = {}+ hs, ls = series.get("h"), series.get("l")+ for i, ts in enumerate(series["t"]):+ c = series["c"][i]+ if c is None:+ continue+ et = ts_to_eastern(ts)+ if et.date() != day or et.second or et.minute % BAR_MIN:+ continue # another day, or the live tick off the grid+ if et.time() < OPEN or et.time() >= close_t:+ continue # pre-market, after hours, the 4:00 PM closing print+ if et + datetime.timedelta(minutes=BAR_MIN) > cutoff:+ continue # still in progress at the cutoff+ v = series.get("v")+ out[et] = {"start": et, "c": float(c),+ "h": None if not hs or hs[i] is None else float(hs[i]),+ "l": None if not ls or ls[i] is None else float(ls[i]),+ "v": (v[i] or 0) if v else 0}+ return [out[k] for k in sorted(out)]+++def usable(bars, day, cutoff, n_range):+ """Every slot from 9:30 to the cutoff is there, and at least the range."""+ want = int((cutoff - slot(day, 0)).total_seconds() // (BAR_MIN * 60))+ s = session(day)+ if s:+ want = min(want, int((datetime.datetime.combine(day, s[1]) - slot(day, 0)).total_seconds()+ // (BAR_MIN * 60)))+ if want < n_range or len(bars) != want:+ return False+ return all(b["start"] == slot(day, k) for k, b in enumerate(bars))+++def orb_candidate(bars, n_range):+ """Stage 1, closes only: some completed bar after the range closed at or above+ the highest close of the range. Necessary for a breakout (range high >= any range close)."""+ top = max(b["c"] for b in bars[:n_range])+ return any(b["c"] >= top for b in bars[n_range:])+++def orb_hit(bars, n_range):+ """Stage 2, real highs and lows: the first completed bar to CLOSE above the range high."""+ rng = bars[:n_range]+ if any(b["h"] is None or b["l"] is None for b in rng):+ return None+ oh = max(b["h"] for b in rng)+ ol = min(b["l"] for b in rng)+ for k in range(n_range, len(bars)):+ b = bars[k]+ if b["c"] > oh:+ closes_at = b["start"] + datetime.timedelta(minutes=BAR_MIN)+ return {"price": round(b["c"], 2), "at": clock_label(closes_at),+ "bar_start": b["start"].strftime("%H:%M"), "bar_index": k,+ "or_high": round(oh, 2), "or_low": round(ol, 2),+ "pct_over": round((b["c"] / oh - 1) * 100, 2), "_t": closes_at}+ return None+++def orb_window(now_utc, at, or_minutes, until, explicit_day=None):+ """-> (day, cutoff naive ET) or raise ScanError with the plain message."""+ now = to_eastern(now_utc)+ day = explicit_day or now.date()+ if or_minutes < BAR_MIN or or_minutes % BAR_MIN or or_minutes > 120:+ raise ScanError("--or-minutes wants a multiple of 5 from 5 to 120 (15 is the classic)")+ ok, why = trading_day(day)+ if not ok:+ raise ScanError("No session on %s (%s): the market is closed. Run orb on a trading day "+ "after the opening range, or replay a past day with --offline." % (day_label(day), why))+ s = session(day)+ range_end = slot(day, or_minutes // BAR_MIN)+ first_close = range_end + datetime.timedelta(minutes=BAR_MIN)+ close_dt = datetime.datetime.combine(day, s[1])+ if at is not None:+ cutoff = datetime.datetime.combine(day, at)+ if explicit_day is None and cutoff > now + datetime.timedelta(seconds=59):+ raise ScanError("--at %s is later than now (%s ET)." % (at.strftime("%H:%M"), clock_label(now)))+ if cutoff > close_dt:+ raise ScanError("--at %s is after the %s close on %s." % (at.strftime("%H:%M"), clock_label(close_dt),+ day_label(day)))+ else:+ cutoff = now.replace(second=0, microsecond=0)+ if cutoff >= close_dt:+ raise ScanError("The market closed at %s ET on %s. Replay the session with --at 10:15."+ % (clock_label(close_dt), day_label(day)))+ if cutoff < first_close:+ raise ScanError("It is %s ET: the %d-minute opening range runs 9:30 to %s and the first bar after it "+ "closes at %s. Run orb again after %s."+ % (clock_label(cutoff), or_minutes, clock_label(range_end), clock_label(first_close),+ clock_label(first_close)))+ if until is not None and cutoff.time() > until:+ raise ScanError("It is %s ET, after %s, your last time for new entries (no_entries_after): an "+ "opening-range breakout found now is expired. Run orb tomorrow after %s, or replay "+ "today with --at 10:15." % (clock_label(cutoff), until.strftime("%H:%M"),+ clock_label(first_close)))+ return day, cutoff+++def scan_orb(stage1, symbols, day, cutoff, or_minutes, min_price=0.0, min_volume=0, confirm=None,+ max_confirm=None):+ """stage1 = {SYM: series} with closes (spark or v8). confirm(sym) -> series with highs/lows+ (None = use the stage-1 series). With confirm and max_confirm, only the max_confirm most+ traded candidates (price x volume so far) are confirmed; the rest are counted as unconfirmed.+ Returns (hits, counts, failed {sym: why})."""+ n_range = or_minutes // BAR_MIN+ counts = {"requested": len(symbols), "fetched": 0, "unusable": 0, "illiquid": 0, "scanned": 0,+ "candidates": 0, "confirmed": 0, "unconfirmed": 0}+ hits, failed, cands = [], {}, []+ for sym in symbols:+ s = stage1.get(sym)+ if not s:+ continue+ counts["fetched"] += 1+ bars = session_bars(s, day, cutoff)+ if not usable(bars, day, cutoff, n_range):+ counts["unusable"] += 1+ continue+ vol = sum(b["v"] for b in bars) if s.get("v") else (s.get("meta") or {}).get("regularMarketVolume") or 0+ if bars[-1]["c"] < min_price or vol < min_volume:+ counts["illiquid"] += 1+ continue+ counts["scanned"] += 1+ if orb_candidate(bars, n_range):+ cands.append((sym, bars, bars[-1]["c"] * vol))+ counts["candidates"] = len(cands)+ if confirm is not None and max_confirm and len(cands) > max_confirm:+ cands.sort(key=lambda x: -x[2])+ counts["unconfirmed"] = len(cands) - max_confirm+ cands = cands[:max_confirm]+ for sym, bars, _ in cands:+ full = bars+ if confirm is not None:+ try:+ s2 = confirm(sym)+ except ScanError as e:+ failed[sym] = str(e)+ continue+ full = session_bars(s2, day, cutoff)+ if not usable(full, day, cutoff, n_range):+ failed[sym] = "the v8 chart has a missing bar"+ continue+ counts["confirmed"] += 1+ h = orb_hit(full, n_range)+ if h:+ hits.append(dict({"symbol": sym, "setups": ["orb"]}, **h))+ hits.sort(key=lambda x: (x["_t"], x["symbol"]))+ for h in hits:+ del h["_t"]+ counts["hits"] = len(hits)+ return hits, counts, failed+++# ---------------------------------------------------------------- fetching++def progress(a, msg):+ if not getattr(a, "json", False) and not getattr(a, "quiet", False):+ print(msg, file=sys.stderr)+++def fetch_spark(symbols, rng, interval, pause, a=None):+ """Batches of 20. -> ({SYM: series}, {SYM: error})."""+ data, failed = {}, {}+ batches = [symbols[i:i + SPARK_MAX] for i in range(0, len(symbols), SPARK_MAX)]+ for k, batch in enumerate(batches):+ if k and pause:+ SLEEP(pause)+ wanted = {to_yahoo(s): s for s in batch}+ try:+ got = parse_spark(yahoo_get(spark_path(batch, rng, interval)), wanted)+ except (ScanError, ValueError) as e:+ for s in batch:+ failed[s] = str(e)+ continue+ for s in batch:+ if s in got:+ data[s] = got[s]+ else:+ failed[s] = "no data from Yahoo"+ if a is not None and len(batches) > 25 and (k + 1) % 50 == 0:+ progress(a, " spark %d of %d requests" % (k + 1, len(batches)))+ return data, failed+++def read_symbols(a, offline_syms=None):+ if a.symbols:+ syms = [s for s in re.split(r"[,\s]+", a.symbols.upper()) if s]+ elif a.watchlist:+ syms = symbols_from_file(a.watchlist)+ elif offline_syms is not None and not a.universe:+ syms = sorted(offline_syms) # offline: every chart in the file, unless a list was given+ else:+ path = a.universe or DEFAULT_UNIVERSE+ if not os.path.exists(path):+ raise ScanError("no %s yet: run `scan.py universe` first, or pass --symbols" % path)+ syms = symbols_from_file(path)+ out = []+ for s in syms:+ if s not in out:+ out.append(s)+ if a.limit:+ out = out[:a.limit]+ if not out:+ raise ScanError("no symbols to scan")+ return out+++def symbols_from_file(path):+ if not os.path.exists(path):+ raise ScanError("no file at %s" % path)+ with open(path, encoding="utf-8") as fh:+ text = fh.read()+ if text.lstrip().startswith(("{", "[")):+ try:+ doc = json.loads(text)+ except ValueError as e:+ raise ScanError("%s is not valid JSON: %s" % (path, e))+ items = doc.get("hits", []) if isinstance(doc, dict) else doc+ return [str(x.get("symbol") if isinstance(x, dict) else x).upper() for x in items if x]+ out = []+ for ln in text.splitlines():+ ln = ln.strip()+ if ln and not ln.startswith("#"):+ out.append(ln.split("|")[0].strip().upper())+ return out+++def read_config(path):+ if not path or not os.path.exists(path):+ return {}+ try:+ with open(path, encoding="utf-8") as fh:+ cfg = json.load(fh)+ except ValueError as e:+ raise ScanError("%s is not valid JSON: %s" % (path, e))+ return cfg if isinstance(cfg, dict) else {}+++def write_json(path, doc):+ d = os.path.dirname(path)+ if d:+ os.makedirs(d, exist_ok=True)+ with open(path, "w", encoding="utf-8") as fh:+ json.dump(doc, fh, indent=2)+ fh.write("\n")+++def money(x):+ return "${:,.2f}".format(x)+++# ---------------------------------------------------------------- commands++def cmd_universe(a):+ t0 = time.time()+ texts = {}+ for k, fname in enumerate(NASDAQ_FILES):+ if a.offline:+ p = os.path.join(a.offline, fname)+ if not os.path.exists(p):+ raise ScanError("no %s in %s" % (fname, a.offline))+ with open(p, encoding="utf-8", errors="replace") as fh:+ texts[fname] = fh.read()+ else:+ if k and a.pause:+ SLEEP(a.pause)+ try:+ texts[fname] = http_get(NASDAQ_URL + fname, timeout=60)+ except urllib.error.HTTPError as e:+ raise ScanError("nasdaqtrader.com answered HTTP %d for %s" % (e.code, fname))+ except (urllib.error.URLError, OSError) as e:+ raise ScanError("could not reach nasdaqtrader.com: %s" % getattr(e, "reason", e))+ kept, counts, created = build_universe(texts)+ if not a.no_write:+ d = os.path.dirname(a.out)+ if d:+ os.makedirs(d, exist_ok=True)+ with open(a.out, "w", encoding="utf-8") as fh:+ for sym, name in kept:+ fh.write("%s|%s\n" % (sym, name))+ dropped = {k: v for k, v in counts.items() if k not in ("keep", "rows")}+ if a.json:+ print(json.dumps({"count": len(kept), "rows": counts.get("rows", 0), "files_created": created,+ "dropped": dropped, "out": None if a.no_write else a.out,+ "seconds": round(time.time() - t0, 1)}, indent=2))+ else:+ print("Nasdaq Trader symbol directories%s: %s rows." % (+ (", files of %s ET" % created) if created else "", "{:,}".format(counts.get("rows", 0))))+ print("Kept %s US-listed common stocks, ordinary shares and ADRs." % "{:,}".format(len(kept)))+ print("Dropped: " + ", ".join("%s %s" % ("{:,}".format(v), k)+ for k, v in sorted(dropped.items(), key=lambda kv: -kv[1])) + ".")+ if not a.no_write:+ print("Wrote %s (one SYMBOL|Name a line)." % a.out)+ return 0 if kept else 1+++def cmd_daily(a):+ t0 = time.time()+ now = parse_now(a.now)+ offline_syms = None+ if a.offline:+ data, failed = load_offline(a.offline)+ offline_syms = sorted(set(data) | set(failed))+ symbols = read_symbols(a, offline_syms)+ if not a.offline:+ progress(a, "Fetching daily closes for %s symbols (%d spark requests)..."+ % ("{:,}".format(len(symbols)), (len(symbols) + SPARK_MAX - 1) // SPARK_MAX))+ data, failed = fetch_spark(symbols, "3mo", "1d", a.pause, a)+ hits, counts, last_date = scan_daily(data, symbols, now, a.min_price, a.min_volume)+ nfailed = len(symbols) - counts["fetched"]+ as_of = ("%s close" % last_date.isoformat()) if last_date else None+ doc = {"created_by": "trader-scanner", "created_at": now.strftime("%Y-%m-%dT%H:%M:%SZ"), "mode": "daily",+ "as_of": as_of, "universe": len(symbols), "scanned": counts["scanned"], "failed": nfailed,+ "source": "yahoo", "filters": {"min_price": a.min_price, "min_volume": a.min_volume},+ "note": NOTE, "hits": hits}+ if a.offline:+ doc["offline"] = os.path.basename(a.offline.rstrip("/"))+ if not a.no_write:+ write_json(a.out, doc)+ if a.json:+ print(json.dumps(dict(doc, counts=counts, seconds=round(time.time() - t0, 1)), indent=2))+ return 0 if hits else 1+ local = to_eastern(now)+ print("Daily scan, %s ET, closes through %s (Yahoo spark, daily closes only)." % (+ local.strftime("%a %Y-%m-%d %H:%M"), last_date.isoformat() if last_date else "nothing"))+ print("Fetched %s of %s charts%s. %s passed the liquidity filter ($%s+ and %s+ shares)%s; "+ "%s scanned." % ("{:,}".format(counts["fetched"]), "{:,}".format(len(symbols)),+ (" (%s failed or had no data)" % "{:,}".format(nfailed)) if nfailed else "",+ "{:,}".format(counts["fetched"] - counts["illiquid"]), _n(a.min_price),+ "{:,}".format(a.min_volume),+ (", %d had under %d days" % (counts["short"], MIN_DAILY_BARS)) if counts["short"] else "",+ "{:,}".format(counts["scanned"])))+ if hits:+ per = [(k, sum(1 for h in hits if k in h["setups"])) for k, _ in SETUPS]+ print("%d chart%s matched a setup: %s." % (len(hits), "" if len(hits) == 1 else "s",+ ", ".join("%d %s" % (n, LABEL[k]) for k, n in per if n)))+ print("Most traded first (price x volume):")+ else:+ print("No setups.")+ for h in hits[:a.show]:+ print(" %-6s %10s RSI %5.1f %s" % (h["symbol"], money(h["price"]), h["rsi"],+ ", ".join(LABEL[t] for t in h["setups"])))+ if len(hits) > a.show:+ print(" ... and %d more in the watchlist (--show N for more)." % (len(hits) - a.show))+ if not a.no_write:+ print("Wrote %s (mode daily, %d hit%s)." % (a.out, len(hits), "" if len(hits) == 1 else "s"))+ print(NOTE + " Next: pick one chart, then /trader-news TICKER.")+ return 0 if hits else 1+++def _n(x):+ x = float(x)+ return str(int(x)) if x == int(x) else "%.2f" % x+++def cmd_orb(a):+ t0 = time.time()+ now = parse_now(a.now)+ at = parse_hhmm(a.at) if a.at else None+ cfg = read_config(a.config)+ until = parse_hhmm(a.until or cfg.get("no_entries_after") or "15:30", "--until")+ data = failed = None+ explicit_day = None+ offline_syms = None+ if a.offline:+ data, failed = load_offline(a.offline)+ offline_syms = sorted(set(data) | set(failed))+ if not a.now:+ days = [ts_to_eastern(s["t"][-1]).date() for s in data.values() if s["t"]]+ if days:+ explicit_day = max(days)+ if at is None:+ raise ScanError("offline replay: give --at HH:MM or --now \"YYYY-MM-DD HH:MM\"")+ day, cutoff = orb_window(now, at, a.or_minutes, until, explicit_day)+ symbols = read_symbols(a, offline_syms)+ confirm = None+ if not a.offline:+ today = to_eastern(parse_now(None)).date()+ if (today - day).days > 6:+ raise ScanError("Yahoo's free 5-minute history is short: replay %s with --offline" % day.isoformat())+ rng = "1d" if day == today else "5d"+ progress(a, "Stage 1: 5-minute closes for %s symbols (%d spark requests)..."+ % ("{:,}".format(len(symbols)), (len(symbols) + SPARK_MAX - 1) // SPARK_MAX))+ data, failed = fetch_spark(symbols, rng, "%dm" % BAR_MIN, a.pause, a)+ done = []++ def confirm(sym):+ if a.pause:+ SLEEP(a.pause)+ done.append(sym)+ if len(done) % 50 == 0:+ progress(a, " stage 2: %d v8 charts so far" % len(done))+ return parse_chart(yahoo_get(chart_path(sym, rng, "%dm" % BAR_MIN)), sym)+ hits, counts, failed2 = scan_orb(data, symbols, day, cutoff, a.or_minutes, a.min_price, a.min_volume, confirm,+ a.max_confirm)+ failed = dict(failed or {})+ failed.update(failed2)+ nfailed = len([s for s in symbols if s in failed])+ as_of = "%s %s ET" % (day.isoformat(), cutoff.strftime("%H:%M"))+ doc = {"created_by": "trader-scanner", "created_at": now.strftime("%Y-%m-%dT%H:%M:%SZ"), "mode": "orb",+ "as_of": as_of, "universe": len(symbols), "scanned": counts["scanned"], "failed": nfailed,+ "unconfirmed": counts["unconfirmed"], "source": "yahoo", "or_minutes": a.or_minutes,+ "interval": "%dm" % BAR_MIN,+ "filters": {"min_price": a.min_price, "min_volume": a.min_volume}, "note": NOTE, "hits": hits}+ if a.offline:+ doc["offline"] = os.path.basename(a.offline.rstrip("/"))+ if not a.no_write:+ write_json(a.out, doc)+ if a.json:+ print(json.dumps(dict(doc, counts=counts, seconds=round(time.time() - t0, 1)), indent=2))+ return 0 if hits else 1+ print("Opening-range breakout scan, %s %s ET: %d-minute range (9:30 to %s), 5-minute bars, Yahoo."+ % (day_label(day), clock_label(cutoff), a.or_minutes, clock_label(slot(day, a.or_minutes // BAR_MIN))))+ print("Fetched %s of %s charts%s; %s usable%s; %s candidates, %s confirmed with real highs and lows."+ % ("{:,}".format(counts["fetched"]), "{:,}".format(len(symbols)),+ (" (%s failed or had no data)" % "{:,}".format(nfailed)) if nfailed else "",+ "{:,}".format(counts["scanned"]),+ (" (%s under the price / volume floor)" % "{:,}".format(counts["illiquid"])) if counts["illiquid"] else "",+ "{:,}".format(counts["candidates"]), "{:,}".format(counts["confirmed"])))+ if counts["unconfirmed"]:+ print("PARTIAL: %s more candidates were not checked (only the %s most traded are; --max-confirm 0 "+ "checks all)." % ("{:,}".format(counts["unconfirmed"]), "{:,}".format(a.max_confirm)))+ if hits:+ print("%d of %s charts closed above their opening-range high by %s:"+ % (len(hits), ("the %s checked" % "{:,}".format(counts["confirmed"])) if counts["unconfirmed"]+ else "{:,}".format(counts["scanned"]), clock_label(cutoff)))+ for h in hits[:a.show]:+ print(" %8s %-6s %10s range %s to %s %+.2f%% over" % (+ h["at"], h["symbol"], money(h["price"]), _p(h["or_low"]), _p(h["or_high"]), h["pct_over"]))+ if len(hits) > a.show:+ print(" ... and %d more in the watchlist (--show N for more)." % (len(hits) - a.show))+ else:+ print("No chart closed above its opening-range high by %s." % clock_label(cutoff))+ if not a.no_write:+ print("Wrote %s (mode orb, %d hit%s)." % (a.out, len(hits), "" if len(hits) == 1 else "s"))+ print(NOTE + " Next: pick one chart, then /trader-news TICKER and /trader-entry TICKER.")+ return 0 if hits else 1+++def _p(x):+ return "{:,.2f}".format(x)+++def main(argv=None):+ ap = argparse.ArgumentParser(description="Chart Scanner (trader-scanner): daily setups and opening-range breakouts.")+ sub = ap.add_subparsers(dest="cmd")++ p = sub.add_parser("universe", help="download Nasdaq Trader's lists -> trader/universe.txt")+ p.add_argument("--out", default=DEFAULT_UNIVERSE)+ p.add_argument("--offline", metavar="DIR", help="a folder with nasdaqlisted.txt and otherlisted.txt")+ p.add_argument("--no-write", action="store_true")+ p.add_argument("--pause", type=float, default=PAUSE)+ p.add_argument("--json", action="store_true")++ def common(p, min_price, min_volume):+ g = p.add_mutually_exclusive_group()+ g.add_argument("--symbols", help="comma-separated tickers instead of the universe")+ g.add_argument("--watchlist", metavar="FILE", help="a watchlist.json (hits) or a text file of tickers")+ p.add_argument("--universe", help="symbol list, one SYMBOL|Name a line (default %s)" % DEFAULT_UNIVERSE)+ p.add_argument("--limit", type=int, help="scan only the first N symbols")+ p.add_argument("--min-price", type=float, default=min_price)+ p.add_argument("--min-volume", type=int, default=min_volume)+ p.add_argument("--offline", metavar="PATH", help="fixture folder or file instead of the network")+ p.add_argument("--now", help='pretend it is this time ("2026-10-19 10:15" New York, or ...Z)')+ p.add_argument("--out", default="trader/watchlist.json")+ p.add_argument("--no-write", action="store_true")+ p.add_argument("--pause", type=float, default=PAUSE, help="seconds between requests (%.1f)" % PAUSE)+ p.add_argument("--show", type=int, default=50, help="hits to print (all are written)")+ p.add_argument("--quiet", action="store_true")+ p.add_argument("--json", action="store_true")++ p = sub.add_parser("daily", help="pre-market setups from daily closes")+ common(p, 5.0, 1000000)+ p = sub.add_parser("orb", help="opening-range breakouts so far today")+ common(p, 5.0, 0)+ p.add_argument("--or-minutes", type=int, default=15)+ p.add_argument("--max-confirm", type=int, default=MAX_CONFIRM,+ help="v8 charts to fetch in stage 2, most traded first (%d; 0 = all)" % MAX_CONFIRM)+ p.add_argument("--at", help="cut the clock at this New York time, HH:MM")+ p.add_argument("--until", help="no new entries after HH:MM (default: config no_entries_after, 15:30)")+ p.add_argument("--config", default="trader/config.json")+ a = ap.parse_args(argv)+ if not a.cmd:+ ap.print_help()+ return 1+ try:+ return {"universe": cmd_universe, "daily": cmd_daily, "orb": cmd_orb}[a.cmd](a)+ except ScanError as e:+ print("scan.py: %s" % e, file=sys.stderr)+ return 1+ except KeyboardInterrupt:+ print("scan.py: stopped", file=sys.stderr)+ return 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/trader-timemachine/SKILL.md b/trader-timemachine/SKILL.mdnew file mode 100644index 0000000..ecef8b1--- /dev/null+++ b/trader-timemachine/SKILL.md@@ -0,0 +1,168 @@+---+name: trader-timemachine+description: >-+ Time Machine. Replays every possible outcome of a trade before you risk a+ dollar: 10,000 simulated sessions plus every past time the setup fired.+ Takes the plan from trader-exit (entry, stop, target), rebuilds the rest of+ the day 10,000 times from the stock's own 5-minute bars over the last 60+ days, and re-runs the same rule on every past session. Prints the odds of+ target first, stop first, or neither by the close, where the price sits at+ the close, the average R, the history, and one honest verdict, then hands+ off to /trader-budget. Use when the user says "run the time machine",+ "replay this trade", "what are the odds", "simulate this trade", "monte+ carlo", "backtest this setup", "how often does this hit the target", "is+ this a coin flip", or after /trader-exit writes a plan, before+ /trader-budget.+argument-hint: "[path to plan.json, or TICKER]"+---++# trader-timemachine++The Time Machine sits between the plan and the money. trader-exit has set+the entry, the stop and the target. Before anything is sized or sent, this+skill asks one question: if today plays out like the stock's own last 60+days, how often does this plan hit the target first, the stop first, or+neither? It answers with 10,000 replays and with the real record of the same+rule on every past session. It is a simulation built from the stock's own+recent bars, not a prediction. Day trading loses most people money, and a+good-looking replay does not change that.++`${CLAUDE_SKILL_DIR}` below is this skill's folder (where this SKILL.md lives).++```bash+python3 "${CLAUDE_SKILL_DIR}/timemachine.py" run # trader/plan.json, 10,000 replays, seed 19+python3 "${CLAUDE_SKILL_DIR}/timemachine.py" run --write # also save trader/timemachine.json+python3 "${CLAUDE_SKILL_DIR}/timemachine.py" run --until 15:55 # end each replay at your flat-by time+python3 "${CLAUDE_SKILL_DIR}/timemachine.py" run --json+python3 "${CLAUDE_SKILL_DIR}/timemachine.py" run --symbol TSLA --date 2026-10-19 \+ --entry 364.18 --stop 358.32 --target 370.04 --entry-time "10:15 AM"+python3 "${CLAUDE_SKILL_DIR}/timemachine.py" chart --from # ASCII fan chart of the saved run+```++Other flags: `--replays N`, `--seed N` (default 19), `--window N` (default 2+bars), `--offline FILE` (a saved Yahoo chart JSON, `.json` or `.json.gz`),+`--now "2026-10-19 10:15"` (New York time) to pin the clock.++## What it reads and writes++| file | what |+| --- | --- |+| `trader/plan.json` | the plan from trader-exit: symbol, date, entry, entry_time / entry_bar, stop, stop_rule, target, target_r, opening range |+| Yahoo chart API | one request: 60 days of 5-minute bars (`range=60d&interval=5m`), free and unofficial, can lag |+| `trader/timemachine.json` | with `--write`: `{plan, mc, history}` plus the verdict. `mc` holds the odds, percentiles, the fan-chart bands, 160 sample paths and a 24-bin histogram of the close |++## How it works++1. **The pool.** It keeps only FULL sessions before the plan's date: all 78+ five-minute bars, 9:30 to 4:00 New York time. Half days, gaps and today+ are left out. Every bar becomes four ratios to the bar before it:+ open, high, low and close over the previous close.+2. **One replay.** Start at the entry price. For each bar left in the day,+ pick a past bar from the same time of day (plus or minus 2 bars) at+ random, and scale it to the current price. Bar by bar, it checks the stop+ first, then the target. A bar that touches both counts as the stop.+3. **10,000 replays** give four odds. Target first. Stop first. Neither,+ which means the trade was still open at `--until` (default 4:00 PM, the+ close, or 1:00 PM on an NYSE early-close day). Green, which means target+ first or above the entry at `--until`.+ R is +1 at a 1R target, -1 at the stop, and otherwise the distance from+ the entry at `--until` divided by the risk. A gap through the stop still+ counts as -1R here. A real fill can be worse.+4. **The history.** The plan's own rule (the same opening range, stop rule+ and target R) runs again on every one of those past sessions. That is+ what really happened, not a simulation.+5. **The verdict** is one line from the numbers. It looks only at the+ replays that hit one side, and asks how often the target came first. A+ bigger target needs to win less often to break even: 1 in (1 + R). That+ is 50 % at 1R, 33 % at 2R, 25 % at 3R. Less than 5 points from break-even:+ "Close to a coin flip" at 1R, "Close to break-even" at any other R. 5 to+ 15 points: "Leans toward the target" or "Leans toward the stop". 15 or+ more: "Strongly toward" one of them. So a 2R plan with target first+ 24.1 % and stop first 50.5 % is close to break-even (it needs 33 % of+ the 74.6 % that hit a side, and got 32 %), not a loser.+6. **Below the verdict**, when it applies: a line when more than 40 % of the+ replays hit neither (the price at `--until` decides those), and the+ average R when its sign goes against the lean. Those can only point the+ other way because of the replays that hit neither.++**The seed.** The draws come from Python's `random.Random(seed)`, seed 19 by+default. Same plan, same data, same seed: the same numbers, on any machine.+Say the seed with every result so the user can repeat it.++**5-minute bars only.** Yahoo keeps 60 days of 5-min bars but only about 7+days of 1-min bars, too few sessions for a fair pool. It refuses, in one+plain line, when there are fewer than 20 full sessions, when the entry bar is+not in the data (wrong date, not closed yet, a future day), or when the plan+does not make sense (a stop above a buy's entry, an entry off the 5-minute+grid). A live in-progress bar is never used.++## Steps++1. Make sure `trader/plan.json` is today's plan from `/trader-exit`. If there+ is none, run that first, or pass the plan as flags.+2. Run `timemachine.py run --write`. Add `--until 15:55` when the plan has a+ flat-by time, so "neither" means still open at the time you would get out.+3. Tell the user, in this order: the four odds, the median and the 5 to 95+ range of the price at the close, the average R, the history line, then the+ verdict line and any line under it exactly as printed. Say the seed.+4. If the verdict is a coin flip or close to break-even, say so plainly. Do+ not dress it up. If the history and the replays disagree, say that too.+5. Say once that this is built from the last 60 days and is not a prediction.+ Earnings, news and halts can do things those 60 days never did. Check+ `/trader-news` for the stock before going on.+6. If the user still wants the trade, hand off to `/trader-budget` to size it.++## Example: the reel++TSLA, Monday 2026-10-19. The 15-minute opening range is 354.47 to 362.18.+The 10:10 bar closes above it: entry 364.18 at 10:15 AM (bar 8), stop 358.32+(the range midpoint, rounded down), target 370.04 (1R, risk 5.86 a share).++```+10,000 replays of the rest of the session, 10:15 AM to 4:00 PM (69 five-minute bars), seed 19.+ target first 29.4 %+ stop first 25.5 %+ neither 45.1 % still open at 4:00 PM+ green 51.7 % target first, or above the entry at 4:00 PM+ Price at 4:00 PM: median 364.36, 90 % of replays between 355.54 and 373.54.+ Average R: +0.034+History: the same rule on each of those 59 real sessions fired 33 times:+13 target, 15 stop, 5 neither. Average R -0.062.+Close to a coin flip: target first 29.4 % vs stop first 25.5 %.+45.1 % of the replays hit neither by 4:00 PM; the price at 4:00 PM decides those.+```++At 1R the target has to come first in half of the replays that hit one+side. It did in 53.6 %. The replays came out close to a coin flip, and the+real history was slightly worse than even. That is the honest answer for this setup, and it is what+the user should hear before `/trader-budget` sizes 8 shares.++## Rules++- Every number comes from the run. Never round a coin flip up into an edge.+- The verdict line and the lines under it are printed by the tool. Repeat+ them, do not rewrite them. Never judge a 2R or 3R plan by target first vs+ stop first alone: the verdict already weighs the target's R.+- Simulated odds are not predictions and not promises. Say it once, plainly.+- Free Yahoo data is unofficial and can lag. Bars are 5-minute bars, checked+ bar by bar, never tick by tick and never real time.+- Always say the seed, so any run can be repeated.+- One plan per run. A changed entry, stop, target or date is a new run.++## What it never does++It never places an order, never sizes a position, never changes the plan,+and never calls a result a sure thing. It never prints a P&L or a profit.+It never uses a bar that has not closed yet, and never mixes today's bars+into the pool.++## Safety++- Education and tooling, not financial advice. A PASS is a rules check, not a recommendation.+- Paper trading by default (`"paper": true`). Going live is the user's own decision, in their own config.+- Nothing in this pack places an order except trader-broker, and only when all three hold: trader-risk+ passed that exact order today, the user typed an explicit yes for that one order in the chat, and the+ user clicked Allow once on Claude's own card because the order tool is set to "Needs approval"+ (Customize > Connectors > tool permissions). Never set an order tool to "Always allow".+- No options, margin, short selling or leverage unless the config allows it and the user confirms.+- Broker keys live in environment variables or the Claude Desktop config, never in the chat.diff --git a/trader-timemachine/timemachine.py b/trader-timemachine/timemachine.pynew file mode 100644index 0000000..026cc78--- /dev/null+++ b/trader-timemachine/timemachine.py@@ -0,0 +1,956 @@+#!/usr/bin/env python3+"""Time Machine for trader-timemachine. Standard library only.++Replays a planned day trade before you risk a dollar: 10,000 simulated runs of+the rest of the session from your entry, plus the same rule on every past+session in the data.++ python3 timemachine.py run # trader/plan.json, 10,000 replays, seed 19+ python3 timemachine.py run --write # also save trader/timemachine.json+ python3 timemachine.py run --until 15:55 # stop each replay at your flat-by time+ python3 timemachine.py run --seed 7 --replays 20000 --json+ python3 timemachine.py run --symbol TSLA --date 2026-10-19 --entry 364.18 \\+ --stop 358.32 --target 370.04 --entry-time "10:15 AM"+ python3 timemachine.py chart # ASCII fan chart of the replays+ python3 timemachine.py chart --from trader/timemachine.json++How the replays work (the reel's sim.py, same algorithm, same random draws):+ 1. Fetch 60 days of 5-minute bars (Yahoo v8 chart, range=60d interval=5m;+ one request). Keep only FULL sessions before the plan's date: 78 bars,+ 9:30 to 4:00 New York time. Half days, gaps and today are left out.+ 2. The pool: for every bar slot 1..77 of the day, each past session's bar as+ ratios to the previous bar's close: (open, high, low, close) / prev close.+ 3. One replay starts at the entry price and walks the rest of the session.+ For each bar i it picks a slot j = i + randint(-window, window), kept in+ 1..77, then one past bar from pool[j] (random.choice), and scales it to+ the current price. The stop is checked before the target in every bar,+ so a bar that touches both counts as the stop (the conservative call).+ 4. Outcomes: "target" or "stop" (whichever was touched first), or "neither"+ when the trade is still open at --until (default 16:00, the close, or+ 13:00 on an NYSE early-close day).+ "green" = target first, or above the entry at --until (below for a sell).+ R = the target's R at the target, -1 at the stop, otherwise+ (price at --until - entry) / risk. A gap through the stop still counts+ -1R here; a real fill can be worse.+ 5. The price at --until: median and the 5th to 95th percentile of all+ replays (pct(a, q) = sorted a at index int(q * n)). The fan chart uses a+ second run of 2,000 paths with the same seed. The histogram has 24 bins+ between the 1st and 99th percentile.+ 6. History: the plan's own rule (an opening-range breakout with the same+ opening range, stop rule and target R) re-run on every one of those past+ full sessions, first close beyond the range = entry, same stop-first rule.++The verdict line looks at the replays that hit one side (target or stop) and+compares the target's share of them, target / (target + stop), with the share+that breaks even at the plan's target R: 1 / (1 + R), so 50 % at 1R and 33 % at+2R. The gap, in percentage points:+ less than 5 points "Close to a coin flip" (1R) / "Close to break-even" (other R)+ 5 to 15 points "Leans toward the target" / "Leans toward the stop"+ 15 points or more "Strongly toward the target" / "Strongly toward the stop"+Below it: a note when more than 40 % of the replays hit neither (the price at+--until decides those), and the average R when its sign goes against the lean.++5-minute bars only: Yahoo keeps 60 days of 5-min bars but only about 7 days of+1-min bars, too few sessions for a fair pool. The run refuses with a plain+message when there are fewer than 20 full sessions or the entry bar is not in+the data. Same plan, same data and same --seed give the same numbers on any+machine. A simulation built from the stock's own recent bars is not a+prediction: earnings, news and halts can do what the last 60 days never did.++Data: https://query2.finance.yahoo.com/v8/finance/chart/<T>?range=60d&interval=5m+(unofficial and free, can lag; falls back to query1 on 429 or 5xx).+--offline FILE reads a saved chart JSON (.json or .json.gz) instead.+Times are New York (ET) wall-clock; --now "2026-10-19 10:15" pins the clock.+"""++import argparse+import datetime+import gzip+import json+import math+import os+import random+import re+import statistics+import sys+import time+import urllib.error+import urllib.parse+import urllib.request++UA = "Mozilla/5.0 (compatible; day-trader-skill/2.0; +https://github.com/Jakeschincariol/day-trader-skill)"+PAUSE = 0.5 # seconds between requests: be polite to free endpoints+BACKOFF = 5.0 # seconds to wait once after a 429+HOSTS = ("query2", "query1")+INTERVAL = 300 # 5-minute bars, in seconds+SESSION_BARS = 78 # 9:30 to 16:00 in 5-minute bars+OPEN_MIN = 9 * 60 + 30+CLOSE_MIN = 16 * 60+MIN_SESSIONS = 20+SAMPLE_PATHS = 160+BAND_PATHS = 2000+BAND_Q = (0.05, 0.25, 0.5, 0.75, 0.95)+HIST_BINS = 24+COIN_FLIP = 0.05 # verdict thresholds, see the docstring+STRONG = 0.15+MANY_NEITHER = 0.40+EPOCH = datetime.datetime(1970, 1, 1)+WEEKDAYS = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")+NYSE_EARLY_CLOSE = { # 1:00 p.m. ET, from https://www.nyse.com/markets/hours-calendars (read 2026-10-13)+ "2026-11-27": "day after Thanksgiving",+ "2026-12-24": "Christmas Eve",+ "2027-11-26": "day after Thanksgiving",+}+EARLY_MIN = 13 * 60+++class TMError(Exception):+ pass+++# ---------------------------------------------------------------- time (copied from trader-alerts)++def _nth_sunday(year, month, n):+ d = datetime.date(year, month, 1)+ d += datetime.timedelta(days=(6 - d.weekday()) % 7)+ return d + datetime.timedelta(weeks=n - 1)+++def eastern_offset(utc):+ """Hours from UTC for New York: -4 in daylight time, -5 otherwise.+ DST runs from 2:00 a.m. on the second Sunday of March to 2:00 a.m. on the+ first Sunday of November (US rule since 2007)."""+ y = utc.year+ start = datetime.datetime.combine(_nth_sunday(y, 3, 2), datetime.time(7, 0)) # 2:00 EST+ end = datetime.datetime.combine(_nth_sunday(y, 11, 1), datetime.time(6, 0)) # 2:00 EDT+ naive = utc.replace(tzinfo=None)+ return -4 if start <= naive < end else -5+++def to_eastern(utc):+ return utc.replace(tzinfo=None) + datetime.timedelta(hours=eastern_offset(utc))+++def eastern_to_utc(local):+ for off in (-4, -5):+ utc = local - datetime.timedelta(hours=off)+ if eastern_offset(utc) == off:+ return utc+ return local + datetime.timedelta(hours=5)+++def parse_now(text):+ """ISO time -> naive UTC. A time without an offset is taken as New York time."""+ if not text:+ return datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0, tzinfo=None)+ t = text.strip().replace("Z", "+00:00")+ try:+ dt = datetime.datetime.fromisoformat(t)+ except ValueError:+ raise TMError("--now wants a time like \"2026-10-19 10:15\" (New York) or ...Z (UTC)")+ if dt.tzinfo is None:+ return eastern_to_utc(dt)+ return (dt - dt.utcoffset()).replace(tzinfo=None)+++def utc_of(ts):+ return EPOCH + datetime.timedelta(seconds=int(ts))+++def parse_clock(text, what):+ """'10:15 AM', '10:15am', '15:55' or '3:55' (a bare 1 to 8 o'clock means p.m.) -> minutes after midnight."""+ m = re.match(r"^\s*(\d{1,2}):(\d{2})\s*(?:([AaPp])\.?\s*[Mm]\.?)?\s*$", str(text or ""))+ if not m:+ raise TMError("%s wants a New York time like 10:15 AM or 15:55, not %r" % (what, text))+ h, mi, ap = int(m.group(1)), int(m.group(2)), (m.group(3) or "").lower()+ if mi > 59 or h > 23 or (ap and not 1 <= h <= 12):+ raise TMError("%s %r is not a clock time" % (what, text))+ if ap == "p" and h != 12:+ h += 12+ elif ap == "a" and h == 12:+ h = 0+ elif not ap and 1 <= h <= 8:+ h += 12+ return h * 60 + mi+++def clock12(minutes):+ h, m = divmod(minutes, 60)+ return "%d:%02d %s" % (h % 12 or 12, m, "AM" if h < 12 else "PM")+++def clock24(minutes):+ return "%02d:%02d" % divmod(minutes, 60)+++# ---------------------------------------------------------------- data++def chart_url(sym, host="query2"):+ return "https://%s.finance.yahoo.com/v8/finance/chart/%s?range=60d&interval=5m" % (+ host, urllib.parse.quote(sym.upper().replace(".", "-")))+++def _sleep(seconds):+ time.sleep(seconds)+++def _get(url, timeout=20):+ req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "application/json"})+ with urllib.request.urlopen(req, timeout=timeout) as r:+ return r.read().decode("utf-8", "replace")+++def fetch_chart(sym):+ """One request for 60 days of 5-min bars. query2 first, one retry after a 429,+ then query1 on 429 or 5xx."""+ last = None+ for n, host in enumerate(HOSTS):+ if n:+ _sleep(PAUSE)+ for attempt in (0, 1):+ url = chart_url(sym, host)+ try:+ return _get(url)+ except urllib.error.HTTPError as e:+ last = e.code+ try:+ e.close()+ except Exception:+ pass+ if e.code == 429 and attempt == 0:+ _sleep(BACKOFF)+ continue+ if e.code == 429 or e.code >= 500:+ break+ if e.code == 404:+ raise TMError("Yahoo has no chart for %s (HTTP 404): check the ticker" % sym.upper())+ raise TMError("Yahoo answered HTTP %d for %s" % (e.code, sym.upper()))+ except urllib.error.URLError as e:+ raise TMError("could not reach Yahoo: %s" % e.reason)+ except OSError as e:+ raise TMError("could not reach Yahoo: %s" % e)+ if last == 429:+ raise TMError("Yahoo is rate limiting (HTTP 429). Wait a minute and run it again.")+ raise TMError("Yahoo answered HTTP %s for %s on both hosts. Try again later." % (last, sym.upper()))+++def read_offline(path, sym):+ """A saved Yahoo chart file (.json or .json.gz), or a folder holding <SYM>-60d5m.json(.gz)."""+ if os.path.isdir(path):+ for name in ("%s-60d5m.json" % sym.upper(), "%s-60d5m.json.gz" % sym.upper()):+ if os.path.exists(os.path.join(path, name)):+ path = os.path.join(path, name)+ break+ else:+ raise TMError("no %s-60d5m.json(.gz) in %s" % (sym.upper(), path))+ if not os.path.exists(path):+ raise TMError("no offline chart file %s" % path)+ opener = gzip.open if path.endswith(".gz") else open+ try:+ with opener(path, "rt", encoding="utf-8") as fh:+ return fh.read()+ except OSError as e:+ raise TMError("could not read %s: %s" % (path, e))+++def chart_result(text, sym):+ try:+ data = json.loads(text)+ except ValueError:+ raise TMError("Yahoo returned something that is not JSON for %s" % sym.upper())+ chart = data.get("chart") if isinstance(data, dict) else None+ if not isinstance(chart, dict):+ raise TMError("Yahoo returned something unexpected for %s" % sym.upper())+ res = chart.get("result")+ if not res:+ err = chart.get("error") or {}+ raise TMError("Yahoo has no data for %s: %s" % (sym.upper(), err.get("description") or "unknown ticker"))+ return res[0]+++def parse_bars(result, now_utc):+ """Yahoo chart result -> (meta, bars, dropped). Regular-session 5-min bars only,+ oldest first. Dropped: bars with a missing price, bars off the 5-minute grid+ (the live tick, e.g. 10:49:45), bars not complete yet (now < start + 5 min,+ where now is the earlier of --now and the data's own regularMarketTime), and+ bars outside 9:30 to 16:00 New York time."""+ meta = result.get("meta") or {}+ stamps = result.get("timestamp") or []+ q = ((result.get("indicators") or {}).get("quote") or [{}])[0] or {}+ cols = [q.get(k) or [] for k in ("open", "high", "low", "close", "volume")]+ as_of = now_utc+ rmt = meta.get("regularMarketTime")+ if isinstance(rmt, (int, float)) and utc_of(rmt) < as_of:+ as_of = utc_of(rmt)+ dropped = {"no_price": 0, "off_grid": 0, "not_complete": 0, "outside_hours": 0}+ bars = {}+ for i, ts in enumerate(stamps):+ o, h, l, c, v = [col[i] if i < len(col) else None for col in cols]+ if ts is None or None in (o, h, l, c):+ dropped["no_price"] += 1+ continue+ ts = int(ts)+ if ts % INTERVAL:+ dropped["off_grid"] += 1+ continue+ start = utc_of(ts)+ local = to_eastern(start)+ mins = local.hour * 60 + local.minute - OPEN_MIN+ if mins < 0 or mins >= SESSION_BARS * 5:+ dropped["outside_hours"] += 1+ continue+ if start + datetime.timedelta(seconds=INTERVAL) > as_of:+ dropped["not_complete"] += 1+ continue+ bars[ts] = {"date": local.date().isoformat(), "slot": mins // 5, "start": local.strftime("%H:%M"),+ "o": o, "h": h, "l": l, "c": c, "v": v or 0}+ return meta, [bars[t] for t in sorted(bars)], dropped+++def split_sessions(bars):+ """{date: {slot: bar}}."""+ days = {}+ for b in bars:+ days.setdefault(b["date"], {})[b["slot"]] = b+ return days+++def full_sessions(days, before):+ """Full sessions (all 78 bars) strictly before the plan's date, oldest first,+ and the short ones that were left out (half days, gaps)."""+ full, short = [], []+ for d in sorted(days):+ if d >= before:+ continue+ s = days[d]+ if len(s) == SESSION_BARS:+ full.append((d, [s[i] for i in range(SESSION_BARS)]))+ else:+ short.append({"date": d, "bars": len(s)})+ return full, short+++# ---------------------------------------------------------------- the simulation (sim.py)++def build_pool(sessions):+ """pool[i] = every past session's bar i as (o, h, l, c) / bar i-1's close, in date order."""+ pool = [[] for _ in range(SESSION_BARS)]+ for _, D in sessions:+ for i in range(1, SESSION_BARS):+ pc = D[i - 1]["c"]+ pool[i].append((D[i]["o"] / pc, D[i]["h"] / pc, D[i]["l"] / pc, D[i]["c"] / pc))+ return pool+++def pct(a, q):+ return a[min(len(a) - 1, int(q * len(a)))]+++def simulate(pool, entry, stop, target, k, last, replays=10000, seed=19, window=2, side="buy"):+ """Monte Carlo replays of bars k+1..last. Same draws and order as the reel's sim.py."""+ long = side == "buy"+ risk = (entry - stop) if long else (stop - entry)+ r_target = round(((target - entry) if long else (entry - target)) / risk, 4)++ def slot(rng, i):+ return i if window == 0 else min(SESSION_BARS - 1, max(1, i + rng.randint(-window, window)))++ rng = random.Random(seed)+ choice = rng.choice+ outcomes, closes, paths = [], [], []+ for n in range(replays):+ p = entry+ outcome = None+ keep = n < SAMPLE_PATHS+ path = [entry]+ for i in range(k + 1, last + 1):+ o, h, l, c = choice(pool[slot(rng, i)])+ hi, lo, cl = p * h, p * l, p * c+ if outcome is None:+ if long:+ if lo <= stop:+ outcome = "stop" # both inside one bar: count the loss (conservative)+ elif hi >= target:+ outcome = "target"+ else:+ if hi >= stop:+ outcome = "stop"+ elif lo <= target:+ outcome = "target"+ p = cl+ if keep:+ path.append(round(p, 2))+ outcomes.append(outcome or "close")+ closes.append(p)+ if keep:+ paths.append(path)+ cnt = {x: outcomes.count(x) for x in ("target", "stop", "close")}+ green = sum(1 for o, p in zip(outcomes, closes)+ if o == "target" or (o == "close" and (p > entry if long else p < entry)))+ Rs = [r_target if o == "target" else -1.0 if o == "stop" else ((p - entry) if long else (entry - p)) / risk+ for o, p in zip(outcomes, closes)]+ srt = sorted(closes)+ # percentile bands per bar for the fan chart: a second run of 2,000 paths, same seed+ rng = random.Random(seed)+ choice = rng.choice+ allp = []+ for n in range(BAND_PATHS):+ p = entry+ path = [entry]+ for i in range(k + 1, last + 1):+ o, h, l, c = choice(pool[slot(rng, i)])+ p = p * c+ path.append(p)+ allp.append(path)+ bands = []+ for j in range(last - k + 1):+ col = sorted(pp[j] for pp in allp)+ bands.append([round(pct(col, q), 2) for q in BAND_Q])+ lo_, hi_ = pct(srt, 0.01), pct(srt, 0.99)+ W = (hi_ - lo_) / HIST_BINS+ bins = [0] * HIST_BINS+ for c in srt:+ b = int((c - lo_) / W) if W > 0 else 0+ if 0 <= b < HIST_BINS:+ bins[b] += 1+ return {+ "replays": replays, "seed": seed, "window": window, "bars_left": last - k,+ "p_target": round(cnt["target"] / replays, 4), "p_stop": round(cnt["stop"] / replays, 4),+ "p_neither": round(cnt["close"] / replays, 4), "p_green": round(green / replays, 4),+ "median_close": round(pct(srt, 0.5), 2), "p5_close": round(pct(srt, 0.05), 2),+ "p95_close": round(pct(srt, 0.95), 2), "avg_R": round(statistics.mean(Rs), 3),+ "r_at_target": r_target, "band_paths": BAND_PATHS, "bands": bands, "sample_paths": paths,+ "hist": {"lo": round(lo_, 2), "hi": round(hi_, 2), "bins": bins},+ }+++# ---------------------------------------------------------------- stop rules and the history replay++def cents_away(x, long):+ """Round a stop to the cent, away from the entry: down for a buy, up for a sell."""+ c = round(x * 100, 4)+ return (math.floor(c) if long else math.ceil(c)) / 100.0+++def opening_range(D, n):+ """(high, low) of the first n bars of a session given as {slot: bar} or a list."""+ rows = [D[i] for i in range(n)]+ return max(b["h"] for b in rows), min(b["l"] for b in rows)+++def rule_stop(rule, oh, ol, entry, long):+ r = rule["stop_rule"]+ if r == "or_mid":+ return cents_away((oh + ol) / 2, long)+ if r in ("or_low", "or_high"):+ return cents_away(ol if long else oh, long)+ frac = rule["stop_pct"] / 100.0+ return cents_away(entry * (1 - frac) if long else entry * (1 + frac), long)+++def history_replay(sessions, rule, last, side="buy"):+ """The plan's rule on every past full session: entry = the first bar after the+ opening range to close beyond it (up to the --until bar), then stop first, then+ target, bar by bar, else the close at --until."""+ long = side == "buy"+ n = rule["or_minutes"] // 5+ trades = []+ for d, D in sessions:+ oh, ol = opening_range(D, n)+ kk = next((i for i in range(n, last + 1) if (D[i]["c"] > oh if long else D[i]["c"] < ol)), None)+ if kk is None:+ continue+ e = round(D[kk]["c"], 2)+ s = rule_stop(rule, oh, ol, e, long)+ risk = (e - s) if long else (s - e)+ if risk <= 0:+ continue+ t = round(e + rule["target_r"] * risk, 2) if long else round(e - rule["target_r"] * risk, 2)+ oc = None+ for b in D[kk + 1:last + 1]:+ if (b["l"] <= s) if long else (b["h"] >= s):+ oc = "stop"+ break+ if (b["h"] >= t) if long else (b["l"] <= t):+ oc = "target"+ break+ cl = D[last]["c"]+ R = ((t - e) if long else (e - t)) / risk if oc == "target" else -1.0 if oc == "stop" else \+ ((cl - e) if long else (e - cl)) / risk+ trades.append({"date": d, "time": clock12(OPEN_MIN + 5 * (kk + 1)), "entry": e, "stop": s, "target": t,+ "outcome": oc or "close", "R": round(R, 2)})+ return {+ "sessions": len(sessions), "triggered": len(trades),+ "target": sum(1 for x in trades if x["outcome"] == "target"),+ "stop": sum(1 for x in trades if x["outcome"] == "stop"),+ "close": sum(1 for x in trades if x["outcome"] == "close"),+ "green": sum(1 for x in trades if x["R"] > 0),+ "avg_R": round(statistics.mean(x["R"] for x in trades), 3) if trades else None,+ "rule": rule, "trades": trades,+ }+++# ---------------------------------------------------------------- the plan++def _num(v, what):+ try:+ x = float(v)+ except (TypeError, ValueError):+ raise TMError("the plan needs a number for %s, got %r" % (what, v))+ if not x > 0 or math.isinf(x):+ raise TMError("the plan's %s must be a positive price, got %r" % (what, v))+ return x+++def load_plan(a, now_utc):+ """The plan from --plan (trader/plan.json) or from the flags, checked and normalized."""+ if a.symbol:+ missing = [f for f in ("entry", "stop", "target", "entry_time") if getattr(a, f) is None]+ if missing:+ raise TMError("with --symbol also give %s" % ", ".join("--" + m.replace("_", "-") for m in missing))+ raw = {"symbol": a.symbol, "side": a.side, "date": a.date or to_eastern(now_utc).date().isoformat(),+ "entry": a.entry, "stop": a.stop, "target": a.target, "entry_time": a.entry_time,+ "setup": a.setup, "opening_range": {"minutes": a.or_minutes}, "stop_rule": a.stop_rule,+ "interval": "5m"}+ src = "flags"+ else:+ if not os.path.exists(a.plan):+ raise TMError("no plan at %s: run /trader-exit first, or pass --symbol --date --entry --stop "+ "--target --entry-time" % a.plan)+ try:+ with open(a.plan, encoding="utf-8") as fh:+ raw = json.load(fh)+ except ValueError as e:+ raise TMError("%s is not valid JSON: %s" % (a.plan, e))+ if not isinstance(raw, dict):+ raise TMError("%s is not a plan" % a.plan)+ src = a.plan+ return normalize_plan(raw, src)+++def normalize_plan(raw, src="flags"):+ """A plan dict (trader/plan.json shape) -> the checked plan the time machine runs."""+ sym = str(raw.get("symbol") or "").strip().upper()+ if not re.match(r"^[A-Z][A-Z0-9.\-]{0,9}$", sym):+ raise TMError("the plan needs a ticker symbol, got %r" % raw.get("symbol"))+ side = str(raw.get("side") or "buy").lower()+ if side not in ("buy", "sell"):+ raise TMError("side must be buy or sell, got %r" % raw.get("side"))+ interval = str(raw.get("interval") or "5m")+ if interval != "5m":+ raise TMError("5-minute bars only (the plan says %s): Yahoo keeps 60 days of 5-min bars but only about "+ "7 days of 1-min bars, too few sessions for a fair replay pool" % interval)+ try:+ date = datetime.date.fromisoformat(str(raw.get("date") or "")).isoformat()+ except ValueError:+ raise TMError("the plan needs a date like 2026-10-19, got %r" % raw.get("date"))+ entry, stop, target = (_num(raw.get(k), k) for k in ("entry", "stop", "target"))+ long = side == "buy"+ if long and not stop < entry < target:+ raise TMError("a buy needs stop < entry < target (got stop %s, entry %s, target %s)" % (stop, entry, target))+ if not long and not target < entry < stop:+ raise TMError("a sell needs target < entry < stop (got target %s, entry %s, stop %s)" % (target, entry, stop))+ k = None+ if raw.get("entry_time"):+ close_min = parse_clock(raw["entry_time"], "entry_time")+ if (close_min - OPEN_MIN) % 5:+ raise TMError("entry_time %s is not on the 5-minute grid (use the bar's close, e.g. 10:15 AM)"+ % raw["entry_time"])+ k = (close_min - OPEN_MIN) // 5 - 1+ if raw.get("entry_bar") is not None:+ try:+ kb = int(raw["entry_bar"])+ except (TypeError, ValueError):+ raise TMError("entry_bar must be a bar number, got %r" % raw["entry_bar"])+ if k is not None and kb != k:+ raise TMError("the plan disagrees with itself: entry_bar %d but entry_time %s is bar %d"+ % (kb, raw["entry_time"], k))+ k = kb+ if k is None:+ raise TMError("the plan needs entry_time (the entry bar's close, e.g. 10:15 AM) or entry_bar")+ if not 0 <= k <= SESSION_BARS - 2:+ raise TMError("the entry must close between 9:35 AM and 3:55 PM to leave bars to replay "+ "(got %s)" % clock12(OPEN_MIN + 5 * (k + 1)))+ orng = raw.get("opening_range") or {}+ or_min = orng.get("minutes", 15) if isinstance(orng, dict) else 15+ try:+ or_min = int(or_min)+ except (TypeError, ValueError):+ raise TMError("opening_range.minutes must be a number")+ if or_min < 5 or or_min % 5 or or_min >= 390:+ raise TMError("opening_range.minutes must be a multiple of 5 (got %s)" % or_min)+ risk = (entry - stop) if long else (stop - entry)+ return {+ "symbol": sym, "side": side, "date": date, "setup": str(raw.get("setup") or "orb"),+ "entry": entry, "entry_time": clock12(OPEN_MIN + 5 * (k + 1)), "entry_bar": k,+ "stop": stop, "target": target, "risk_per_share": round(risk, 2),+ "target_r": round(((target - entry) if long else (entry - target)) / risk, 2),+ "opening_range": dict(orng, minutes=or_min) if isinstance(orng, dict) else {"minutes": or_min},+ "stop_rule": str(raw.get("stop_rule") or "auto"), "interval": "5m",+ "flat_by": raw.get("flat_by"), "from": src,+ }+++def resolve_rule(plan, entry_day):+ """The rule the history replay uses: orb, the plan's opening range, its stop rule+ (or_mid, or_low / or_high, or 'pct' = the plan's stop distance as a percent of+ the entry), and the plan's target R. 'auto' works the stop rule out from the+ plan day's own opening range. None when the setup is not orb."""+ if plan["setup"].lower() != "orb":+ return None+ long = plan["side"] == "buy"+ n = plan["opening_range"]["minutes"] // 5+ rule = {"setup": "orb", "or_minutes": plan["opening_range"]["minutes"], "stop_rule": plan["stop_rule"],+ "target_r": plan["target_r"],+ "stop_pct": round(100.0 * plan["risk_per_share"] / plan["entry"], 4)}+ far = "or_low" if long else "or_high"+ if rule["stop_rule"] == "auto":+ rule["stop_rule"] = "pct"+ if all(i in entry_day for i in range(n)):+ oh, ol = opening_range(entry_day, n)+ if abs(cents_away((oh + ol) / 2, long) - plan["stop"]) < 0.005:+ rule["stop_rule"] = "or_mid"+ elif abs(cents_away(ol if long else oh, long) - plan["stop"]) < 0.005:+ rule["stop_rule"] = far+ elif rule["stop_rule"] in ("or_low", "or_high") and rule["stop_rule"] != far:+ rule["stop_rule"] = "pct"+ elif rule["stop_rule"] not in ("or_mid", far):+ rule["stop_rule"] = "pct"+ if rule["stop_rule"] != "pct":+ del rule["stop_pct"]+ return rule+++# ---------------------------------------------------------------- the run++def _until12(mc):+ t = mc.get("until") or "16:00"+ return clock12(int(t[:2]) * 60 + int(t[3:]))+++def lean(mc):+ """(gap, share, break_even): the target's share of the replays that hit one side,+ minus the share that breaks even at the target's R. None when nothing hit a side."""+ pt, ps = mc["p_target"], mc["p_stop"]+ if pt + ps <= 0:+ return None+ r = mc.get("r_at_target") or 1.0+ share, even = pt / (pt + ps), 1.0 / (1.0 + r)+ return share - even, share, even+++def verdict(mc):+ """One line from the numbers, see the docstring for the thresholds."""+ pt, ps = mc["p_target"], mc["p_stop"]+ lv = lean(mc)+ if lv is None:+ return "No replay reached the target or the stop by %s: the price at %s decides every one." % (+ _until12(mc), _until12(mc))+ d, share, even = lv+ r = mc.get("r_at_target") or 1.0+ one_r = abs(r - 1.0) < 0.005+ if abs(d) < COIN_FLIP:+ head = "Close to a coin flip" if one_r else "Close to break-even"+ elif abs(d) < STRONG:+ head = "Leans toward the target" if d > 0 else "Leans toward the stop"+ else:+ head = "Strongly toward the target" if d > 0 else "Strongly toward the stop"+ odds = "target first %.1f %% vs stop first %.1f %%" % (100 * pt, 100 * ps)+ if one_r:+ return "%s: %s." % (head, odds)+ return ("%s: at %gR the target has to come first in %.0f %% of the replays that hit one side; "+ "it did in %.0f %% (%s)." % (head, round(r, 2), 100 * even, 100 * share, odds))+++def verdict_notes(mc):+ """The lines printed right below the verdict, so nothing reads as one-sided."""+ notes = []+ pn = mc.get("p_neither", 0)+ if pn > MANY_NEITHER and lean(mc) is not None:+ notes.append("%.1f %% of the replays hit neither by %s; the price at %s decides those."+ % (100 * pn, _until12(mc), _until12(mc)))+ lv = lean(mc)+ avg = mc.get("avg_R")+ if lv and abs(lv[0]) >= COIN_FLIP and avg is not None and avg != 0 and (avg > 0) != (lv[0] > 0):+ notes.append("Average R is %+.3f all the same: the replays that hit neither pull it the other way." % avg)+ return notes+++def time_machine(text, plan, now_utc, replays=10000, seed=19, window=2, until=None, source="yahoo"):+ """Chart JSON text + a normalized plan -> the timemachine.json document."""+ if not 1 <= replays <= 1000000:+ raise TMError("--replays must be between 1 and 1,000,000")+ if not 0 <= window <= 10:+ raise TMError("--window must be between 0 and 10 bars")+ sym = plan["symbol"]+ result = chart_result(text, sym)+ meta, bars, dropped = parse_bars(result, now_utc)+ msym = str(meta.get("symbol") or "").upper()+ if msym and msym != sym.replace(".", "-"):+ raise TMError("the data is for %s but the plan is for %s" % (msym, sym))+ gran = meta.get("dataGranularity")+ if gran and gran != "5m":+ raise TMError("the data has %s bars; the time machine needs 5-minute bars" % gran)+ if not bars:+ raise TMError("no complete 5-minute bars for %s in the data" % sym)+ k = plan["entry_bar"]+ early = plan["date"] in NYSE_EARLY_CLOSE+ end_min = EARLY_MIN if early else CLOSE_MIN+ until_min = end_min if until is None else parse_clock(until, "--until")+ if (until_min - OPEN_MIN) % 5 or until_min > end_min:+ raise TMError("--until must be on the 5-minute grid and no later than %s%s"+ % (clock12(end_min), " (an early close)" if early else ""))+ last = (until_min - OPEN_MIN) // 5 - 1+ if last <= k:+ raise TMError("--until %s leaves nothing to replay after the %s entry" % (clock12(until_min),+ plan["entry_time"]))+ days = split_sessions(bars)+ entry_day = days.get(plan["date"], {})+ if k not in entry_day:+ reason = ("no bars for that day" if not entry_day else+ "the data stops at the %s bar" % entry_day[max(entry_day)]["start"])+ raise TMError("the entry is not in the data: no complete %s bar (closing %s) on %s for %s (%s)"+ % (clock24(OPEN_MIN + 5 * k), plan["entry_time"], plan["date"], sym, reason))+ eb = entry_day[k]+ warn = []+ if not eb["l"] - 0.01 <= plan["entry"] <= eb["h"] + 0.01:+ warn.append("the plan's entry %.2f is outside that bar's range %.2f to %.2f"+ % (plan["entry"], eb["l"], eb["h"]))+ sessions, short = full_sessions(days, plan["date"])+ if len(sessions) < MIN_SESSIONS:+ raise TMError("only %d full session(s) of %s before %s in the data; the time machine needs at least %d"+ % (len(sessions), sym, plan["date"], MIN_SESSIONS))+ pool = build_pool(sessions)+ mc = simulate(pool, plan["entry"], plan["stop"], plan["target"], k, last, replays, seed, window, plan["side"])+ mc = dict(mc, until=clock24(until_min), pool_sessions=len(sessions), pool_from=sessions[0][0],+ pool_to=sessions[-1][0],+ band_times=[clock24(OPEN_MIN + 5 * (j + 1)) for j in range(k, last + 1)])+ rule = resolve_rule(plan, entry_day)+ plan_out = {kk: v for kk, v in plan.items() if v is not None}+ if rule:+ plan_out["stop_rule"] = rule["stop_rule"]+ history = history_replay(sessions, rule, last, plan["side"])+ else:+ history = {"sessions": len(sessions), "triggered": 0, "rule": None, "trades": [],+ "note": "skipped: the history replay knows the opening-range breakout (orb) only, "+ "this plan's setup is %r" % plan["setup"]}+ last_bar = bars[-1]+ return {+ "created_by": "trader-timemachine",+ "created_at": now_utc.strftime("%Y-%m-%dT%H:%M:%SZ"),+ "source": source,+ "data": {"symbol": msym or sym, "interval": "5m", "range": "60d",+ "last_bar": "%s %s ET" % (last_bar["date"], last_bar["start"]),+ "dropped": dropped, "short_sessions_left_out": short},+ "plan": plan_out,+ "mc": mc,+ "history": history,+ "verdict": verdict(mc),+ "verdict_notes": verdict_notes(mc),+ "warnings": warn,+ "note": ("A simulation built from %s's own last %d full sessions. It is not a prediction: earnings, "+ "news and halts can do things those sessions never did. Same seed, same numbers." % (sym, len(sessions))),+ }+++# ---------------------------------------------------------------- output++def pc(x):+ return "%.1f %%" % (100.0 * x)+++def report(doc):+ p, m, h = doc["plan"], doc["mc"], doc["history"]+ long = p["side"] == "buy"+ until = clock12(int(m["until"][:2]) * 60 + int(m["until"][3:]))+ wd = WEEKDAYS[datetime.date.fromisoformat(p["date"]).weekday()]+ r = p["target_r"]+ lines = [+ "%s %s, %s %s: entry %.2f at %s (bar %d), stop %.2f, target %.2f (%sR, risk %.2f a share)."+ % (p["symbol"], p["side"], wd, p["date"], p["entry"], p["entry_time"], p["entry_bar"], p["stop"],+ p["target"], ("%g" % r), p["risk_per_share"]),+ "%s replays of the rest of the session, %s to %s (%d five-minute bars), seed %d."+ % ("{:,}".format(m["replays"]), p["entry_time"], until, m["bars_left"], m["seed"]),+ "Each bar is drawn whole from %s's own 5-min bars at the same time of day (+-%d bars) over its last "+ "%d full sessions (%s to %s)." % (p["symbol"], m["window"], m["pool_sessions"], m["pool_from"], m["pool_to"]),+ "",+ " target first %s" % pc(m["p_target"]),+ " stop first %s" % pc(m["p_stop"]),+ " neither %-8s still open at %s" % (pc(m["p_neither"]), until),+ " green %-8s target first, or %s the entry at %s" % (pc(m["p_green"]),+ "above" if long else "below", until),+ "",+ " Price at %s: median %.2f, 90 %% of replays between %.2f and %.2f."+ % (until, m["median_close"], m["p5_close"], m["p95_close"]),+ " Average R: %+.3f (R = the %.2f risk: %sR at the target, -1R at the stop)."+ % (m["avg_R"], p["risk_per_share"], ("+%g" % m["r_at_target"]), ),+ "",+ ]+ if h.get("rule"):+ ru = h["rule"]+ stop_words = {"or_mid": "opening-range midpoint", "or_low": "opening-range low",+ "or_high": "opening-range high"}.get(ru["stop_rule"],+ "%.2f %% from the entry" % ru.get("stop_pct", 0))+ if h["triggered"]:+ lines.append("History: the same rule (%d-min opening range, stop at the %s, %gR target) on each of "+ "those %d real sessions fired %d times: %d target, %d stop, %d neither. Average R %+.3f."+ % (ru["or_minutes"], stop_words, ru["target_r"], h["sessions"], h["triggered"],+ h["target"], h["stop"], h["close"], h["avg_R"]))+ else:+ lines.append("History: the same rule never fired in those %d sessions." % h["sessions"])+ else:+ lines.append("History: " + h.get("note", "skipped."))+ lines += ["", doc["verdict"]] + list(doc.get("verdict_notes") or []) + [""]+ for w in doc.get("warnings") or []:+ lines.append("Note: " + w + ".")+ if doc["data"]["short_sessions_left_out"]:+ lines.append("Left out %d short session(s) (half days or gaps): %s."+ % (len(doc["data"]["short_sessions_left_out"]),+ ", ".join(x["date"] for x in doc["data"]["short_sessions_left_out"])))+ lines.append(doc["note"] + " Repeat this run with --seed %d." % m["seed"])+ return lines+++def render_chart(doc, height=17):+ """ASCII fan chart of the bands: one column per 5-min bar."""+ p, m = doc["plan"], doc["mc"]+ bands, times = m["bands"], m["band_times"]+ lo = min([b[0] for b in bands] + [p["stop"], p["target"]])+ hi = max([b[4] for b in bands] + [p["stop"], p["target"]])+ pad = (hi - lo) * 0.04 or 0.01+ lo, hi = lo - pad, hi + pad+ step = (hi - lo) / (height - 1)++ def row(price):+ return max(0, min(height - 1, int(round((hi - price) / step))))+ grid = [[" "] * len(bands) for _ in range(height)]+ for j, b in enumerate(bands):+ r5, r25, r50, r75, r95 = [row(x) for x in b]+ for r in range(r95, r5 + 1):+ grid[r][j] = "."+ for r in range(r75, r25 + 1):+ grid[r][j] = ":"+ grid[r50][j] = "*"+ marks = {row(p["target"]): "target", row(p["stop"]): "stop"}+ if row(p["entry"]) not in marks:+ marks[row(p["entry"])] = "entry"+ for r in (row(p["target"]), row(p["stop"])):+ grid[r] = ["-" if ch == " " else ch for ch in grid[r]]+ out = ["%s %s, %s replay paths from the %s entry (seed %d)" % (+ p["symbol"], p["date"], "{:,}".format(m.get("band_paths", BAND_PATHS)), p["entry_time"], m["seed"])]+ for r in range(height):+ label = marks.get(r)+ price = {"target": p["target"], "stop": p["stop"], "entry": p["entry"]}.get(label, hi - r * step)+ left = ("%9.2f |" % price) if (label or r in (0, height - 1)) else " |"+ out.append(left + "".join(grid[r]) + (" " + label if label else ""))+ axis = [" "] * len(bands)+ for j in sorted({0, len(bands) // 2, len(bands) - 1}):+ t = times[j]+ hh, mm = int(t[:2]), t[3:]+ lab = "%d:%s" % (hh % 12 or 12, mm)+ s = max(0, min(j, len(bands) - len(lab)))+ axis[s:s + len(lab)] = list(lab)+ out.append(" +" + "-" * len(bands))+ out.append(" " + "".join(axis))+ out.append("* median : middle half of the paths . 90 % of the paths - stop and target")+ return out+++# ---------------------------------------------------------------- commands++def _write(path, doc):+ d = os.path.dirname(path)+ if d:+ os.makedirs(d, exist_ok=True)+ with open(path, "w", encoding="utf-8") as fh:+ json.dump(doc, fh, indent=1)+ fh.write("\n")+++def compute(a):+ now = parse_now(a.now)+ plan = load_plan(a, now)+ if a.offline:+ text, source = read_offline(a.offline, plan["symbol"]), "offline"+ else:+ text, source = fetch_chart(plan["symbol"]), "yahoo"+ return time_machine(text, plan, now, a.replays, a.seed, a.window, a.until, source)+++def cmd_run(a):+ doc = compute(a)+ if a.write:+ _write(a.write, doc)+ if a.json:+ slim = dict(doc, mc={k: v for k, v in doc["mc"].items() if k != "sample_paths"})+ print(json.dumps(slim, indent=2))+ else:+ print("\n".join(report(doc)))+ if a.write:+ print("Wrote %s." % a.write)+ print("Next: /trader-budget sizes it to your budget and your max loss per trade.")+ return 0+++def cmd_chart(a):+ if a.from_file:+ if not os.path.exists(a.from_file):+ raise TMError("no %s: run timemachine.py run --write first" % a.from_file)+ try:+ with open(a.from_file, encoding="utf-8") as fh:+ doc = json.load(fh)+ doc["mc"]["bands"]+ except (ValueError, KeyError, TypeError):+ raise TMError("%s is not a time machine result" % a.from_file)+ else:+ doc = compute(a)+ print("\n".join(render_chart(doc)))+ print("\n".join([doc.get("verdict", "")] + list(doc.get("verdict_notes") or [])))+ return 0+++def main(argv=None):+ ap = argparse.ArgumentParser(description="Time Machine: replay a planned day trade (trader-timemachine).")+ sub = ap.add_subparsers(dest="cmd")++ def common(p):+ p.add_argument("--plan", default="trader/plan.json", help="the plan from trader-exit")+ p.add_argument("--symbol", help="or give the plan as flags: ticker")+ p.add_argument("--side", default="buy", choices=["buy", "sell"])+ p.add_argument("--date", help="the plan's day, YYYY-MM-DD (default today, New York)")+ p.add_argument("--entry", type=float)+ p.add_argument("--stop", type=float)+ p.add_argument("--target", type=float)+ p.add_argument("--entry-time", help='the entry bar\'s close, e.g. "10:15 AM"')+ p.add_argument("--setup", default="orb")+ p.add_argument("--or-minutes", type=int, default=15)+ p.add_argument("--stop-rule", default="auto", choices=["auto", "or_mid", "or_low", "or_high", "pct"])+ p.add_argument("--replays", type=int, default=10000)+ p.add_argument("--seed", type=int, default=19)+ p.add_argument("--window", type=int, default=2, help="draw from the same time of day +- this many bars")+ p.add_argument("--until", help="end each replay at this time (default 16:00, the close)")+ p.add_argument("--offline", metavar="FILE", help="a saved Yahoo chart JSON (.json or .json.gz), no network")+ p.add_argument("--now", help='pretend it is this time ("2026-10-19 10:15" New York, or ISO with Z)')++ p = sub.add_parser("run", help="replay the plan: 10,000 simulated sessions plus the history")+ common(p)+ p.add_argument("--json", action="store_true")+ p.add_argument("--write", nargs="?", const="trader/timemachine.json", metavar="PATH",+ help="save the result (default trader/timemachine.json)")+ p = sub.add_parser("chart", help="ASCII fan chart of the replays")+ common(p)+ p.add_argument("--from", dest="from_file", nargs="?", const="trader/timemachine.json", metavar="PATH",+ help="draw a saved result instead of running again")+ a = ap.parse_args(argv)+ if not a.cmd:+ ap.print_help()+ return 1+ try:+ return {"run": cmd_run, "chart": cmd_chart}[a.cmd](a)+ except TMError as e:+ print("timemachine.py: %s" % e, file=sys.stderr)+ return 1+++if __name__ == "__main__":+ sys.exit(main())