By Mukul Dutt, founder of Edgrapi (an API for SEC and US government data). Last updated November 2026.
Who in Congress traded NVDA last month, and did any NVDA insiders buy?
You can answer both with free government data and about 150 lines of Python. A politician stock tracker needs two sources, House periodic transaction reports (PTRs) from the House Clerk for members of Congress and SEC Form 4 filings from EDGAR for corporate insiders. Both are free, neither needs a key, and both have parsing traps that quietly drop trades if you don't handle them.
I built this pipeline for my own product, so this is the version that survived real data. Everything below ran on November 25, 2026, and every output block is what came back that day.
You need Python 3, requests and pypdf.
pip install requests pypdf
What does a politician stock tracker need?
A politician stock tracker needs the House Clerk's yearly disclosure index, the PTR PDFs it points to, and a parser for the trade rows inside them. An insider trading tracker needs SEC Form 4 XML from EDGAR. The two sources have different formats, different deadlines and different failure modes, so treat them as two pipelines that share one output table.
Here's how the two compare, based on my runs on NVDA:
| Insider trades (SEC Form 4) | Congress trades (House PTRs) | |
|---|---|---|
| Where | EDGAR, data.sec.gov
|
House Clerk, disclosures-clerk.house.gov
|
| Format | Clean XML | PDF, typed or scanned |
| Deadline | 2nd business day after the trade | 30 days from notice or 45 days from the trade |
| Amounts | Exact shares and price | Dollar ranges only |
| Find by ticker | Yes, via the company's CIK | No, you read every PDF |
| My NVDA run | 40 filings in 24 seconds | 150 PDFs in 95 seconds |
The Senate is a separate site with its own problems, which I'll get to later.
How do I pull insider trades from SEC EDGAR in Python?
EDGAR's APIs are free and keyless, but the SEC asks every script to send a User-Agent with a real name and email, and its fair access page caps you at 10 requests per second. Skip the header and you get 403 errors that look like an outage. The route is three hops, ticker to CIK, CIK to recent filings, filing to Form 4 XML.
The primaryDocument field points at the rendered HTML version, inside an xslF345X05/ folder. Strip that folder and you get the raw XML.
import time
import xml.etree.ElementTree as ET
import requests
HEADERS = {"User-Agent": "Jane Dev jane@example.com"} # SEC wants a real name + email here
def cik_for(ticker):
r = requests.get("https://www.sec.gov/files/company_tickers.json", headers=HEADERS)
for row in r.json().values():
if row["ticker"] == ticker.upper():
return row["cik_str"]
raise ValueError(f"unknown ticker {ticker}")
def recent_form4s(cik, limit=40):
url = f"https://data.sec.gov/submissions/CIK{cik:010d}.json"
recent = requests.get(url, headers=HEADERS).json()["filings"]["recent"]
out = []
for form, acc, doc, filed in zip(recent["form"], recent["accessionNumber"],
recent["primaryDocument"], recent["filingDate"]):
if form in ("4", "4/A"):
# primaryDocument points at the rendered HTML (xslF345X05/...); drop the
# xsl folder to get the raw XML
raw = doc.split("/")[-1]
out.append((form, filed, f"https://www.sec.gov/Archives/edgar/data/{cik}/"
f"{acc.replace('-', '')}/{raw}"))
if len(out) >= limit:
break
return out
The submissions API only holds the most recent 1,000 or so filings in its recent block. For deeper history you page through the extra files listed under filings.files.
What does transaction code P mean on a Form 4?
Code P is an open-market or private purchase, the only Form 4 code where an insider bought stock with their own money. The SEC's Form 4 instructions list S for sales, A for grants, M for option exercises, G for gifts and F for shares withheld to pay tax. Form 4 is due before the end of the second business day after the trade, so this data is nearly current.
On a big-cap name like NVDA, almost every row is S, A, M or G.
Sales need one more check. Since the SEC's December 2022 rule change, Form 4 has a checkbox that flags trades made under a Rule 10b5-1 plan. Those trades were scheduled months earlier, so they say little about what the insider thinks today.
In the XML that checkbox is the aff10b5One element. Older filings mention the plan only in a footnote, so I check both.
def parse_form4(url):
root = ET.fromstring(requests.get(url, headers=HEADERS).content)
owner = root.findtext("reportingOwner/reportingOwnerId/rptOwnerName")
# filing-level checkbox, added to Form 4 in April 2023
plan_box = (root.findtext("aff10b5One") or "").strip().lower() in ("1", "true")
plan_notes = {fn.get("id") for fn in root.iter("footnote")
if "10b5-1" in "".join(fn.itertext())}
rows = []
for tx in root.iter("nonDerivativeTransaction"):
refs = {f.get("id") for f in tx.iter("footnoteId")}
rows.append({
"owner": owner,
"date": tx.findtext("transactionDate/value"),
"code": tx.findtext("transactionCoding/transactionCode"),
"shares": float(tx.findtext("transactionAmounts/transactionShares/value") or 0),
"price": float(tx.findtext("transactionAmounts/transactionPricePerShare/value") or 0),
"plan": plan_box or bool(refs & plan_notes),
})
return rows
How do I stop Form 4 amendments from double-counting trades?
Group transactions by owner and trade date, and let the most recently filed document win. A Form 4/A restates an earlier filing, so counting both doubles the trade, and the XML has no clean pointer from the amendment back to the original. Keying on owner plus date is the practical fix, and in my NVDA run it collapsed one amendment correctly.
if __name__ == "__main__":
cik = cik_for("NVDA")
filings = recent_form4s(cik)
# A 4/A restates an earlier Form 4. Group rows by (owner, trade date) and let the
# most recently filed document win, so an amendment replaces what it corrects.
latest = {}
for form, filed, url in filings:
time.sleep(0.15) # stay well under SEC's 10 requests/second
for t in parse_form4(url):
key = (t["owner"], t["date"])
if key not in latest or filed > latest[key][0]:
latest[key] = (filed, url, [])
if latest[key][1] == url:
latest[key][2].append(t)
rows = [(filed, url, t) for filed, url, ts in latest.values() for t in ts]
buys = [r for r in rows if r[2]["code"] == "P"]
sells = [r for r in rows if r[2]["code"] == "S"]
print(f"{len(filings)} filings, {len(rows)} transactions after amendments")
print(f"open-market sales: {len(sells)} ({sum(r[2]['plan'] for r in sells)} under a 10b5-1 plan)")
print(f"open-market buys (code P): {len(buys)}")
for filed, url, t in buys:
print(filed, t["owner"], t["shares"], "@", t["price"], url)
Output on NVDA, about 24 seconds:
40 filings, 76 transactions after amendments
open-market sales: 44 (22 under a 10b5-1 plan)
open-market buys (code P): 0
Zero buys is the real answer for NVDA. Its insiders are paid in stock and sell on schedules.
The useful number is the 22 planned sales, half of all sales. A naive insider trading tracker would flag those loudest, and they carry the least information. Run the same script on a small-cap and you'll usually see some P rows.
How do I track congressional stock trades for free?
Download the House Clerk's yearly index, keep the rows with filing type P, and read each PTR PDF for trade rows. Under the rules on the House Ethics financial disclosure page, members report transactions over $1,000 within 30 days of learning about them or 45 days of the trade, whichever comes first. The index has no tickers, so finding one stock means reading every PDF.
The House Clerk publishes the index as a zip, 2026FD.zip, with a tab-separated file inside. As of November 25, 2026, it listed 481 PTRs filed this year.
import io, re, time, zipfile
import requests
from pypdf import PdfReader
HEADERS = {"User-Agent": "Jane Dev jane@example.com"}
YEAR = 2026
BASE = "https://disclosures-clerk.house.gov/public_disc"
def ptr_index(year):
"""Every periodic transaction report (FilingType P) filed this year, newest first."""
z = zipfile.ZipFile(io.BytesIO(
requests.get(f"{BASE}/financial-pdfs/{year}FD.zip", headers=HEADERS).content))
lines = z.read(f"{year}FD.txt").decode("utf-8", "replace").splitlines()[1:]
out = []
for line in lines:
f = line.split("\t")
if len(f) >= 9 and f[4] == "P":
m, d, y = f[7].split("/")
out.append({"member": f"{f[2]} {f[1]}", "district": f[5],
"filed": f"{y}-{int(m):02d}-{int(d):02d}", "doc_id": f[8].strip()})
return sorted(out, key=lambda r: r["filed"], reverse=True)
Pad the dates before sorting. The index writes dates like 9/4/2026, and my first run sorted September above November as strings, so my "newest 150" was really a late-summer sample until I caught it.
Why does my congressional trade parser miss trades?
Most missed trades come from scanned PDFs with no text layer, a regex that expects a clean $low - $high range, and index entries whose PDF isn't posted yet. In my run, 20 of the newest 150 PTRs were scans, about 13%, and they returned nothing. The top amount bracket reads "Over $50,000,000" with no upper bound, so a strict regex silently drops the largest trades.
Every typed PTR row carries the ticker in parentheses, an asset-type tag, P, S or E, two dates and a dollar range.
The text extraction also jams the transaction date and notification date together with no space. Partial sales print as S (partial). My first parser missed both.
# "(NVDA) [ST]" then type, trade date, notification date, amount range.
# The PDF text layer often runs the two dates together with no space.
ROW = re.compile(r"\(([A-Z.]{1,6})\)\s*\[[A-Z]{2}\]\s*([PSE])(?:\s*\(partial\))?\s+"
r"(\d{2}/\d{2}/\d{4})\s*(\d{2}/\d{2}/\d{4})\s*(?:Over\s*)?\$([\d,]+)"
r"(?:\s*-\s*\$([\d,]+))?")
def trades_in(doc_id, year):
pdf = requests.get(f"{BASE}/ptr-pdfs/{year}/{doc_id}.pdf", headers=HEADERS).content
if not pdf.startswith(b"%PDF"):
return [], None # listed in the index, PDF not posted yet
text = "\n".join(p.extract_text() or "" for p in PdfReader(io.BytesIO(pdf)).pages)
# one trade split across sub-accounts is printed once per account
return list(dict.fromkeys(ROW.findall(text))), bool(text.strip())
if __name__ == "__main__":
ticker, scan = "NVDA", 150
index = ptr_index(YEAR)
print(f"{len(index)} PTRs filed in {YEAR}; scanning the newest {scan}")
unreadable = missing = 0
for f in index[:scan]:
time.sleep(0.2)
rows, has_text = trades_in(f["doc_id"], YEAR)
missing += has_text is None
unreadable += has_text is False
for tk, kind, traded, _, lo, hi in rows:
if tk == ticker:
side = {"P": "buy", "S": "sell", "E": "exchange"}[kind]
print(f["filed"], f["member"], f["district"], side, traded,
f"${lo}-${hi or '+'}", f"{BASE}/ptr-pdfs/{YEAR}/{f['doc_id']}.pdf")
print(f"{missing} not posted yet, {unreadable} with no text layer (scanned)")
Output, about 95 seconds for 150 PDFs (trimmed):
481 PTRs filed in 2026; scanning the newest 150
2026-11-18 Michael Rulli OH06 sell 10/28/2026 $1,001-$15,000 .../20036855.pdf
2026-11-05 Maria Elvira Salazar FL27 buy 10/23/2026 $1,001-$15,000 .../20035778.pdf
2026-10-27 Pete Sessions TX17 sell 10/02/2026 $15,001-$50,000 .../20035563.pdf
2026-10-22 Cleo Fields LA06 buy 10/01/2026 $1,001-$15,000 .../20035669.pdf
...
1 not posted yet, 20 with no text layer (scanned)
The one unposted PDF crashed pypdf on my first run. The Clerk's server answered with a 404 HTML page, requests doesn't raise on a 404 by default, and the %PDF header check is what fixed it.
Dates are loose too. One PTR filed November 23 lists an NVDA trade dated April 29, well past the 45-day window, and the PDF won't tell you whether that's a late filing or a typo.
What about Senate stock trades?
Senate trades are filed on the Senate's own eFD site, efdsearch.senate.gov, not with the House Clerk. The site puts searches behind an agreement page and a session, and it has been refusing scripted requests, so a free Senate tracker means browser automation or a paid data source. Every script in this article is House only, and so is the hosted option below.
Which trades should a politician stock tracker alert on?
Alert on discretionary buys and ignore most of the rest. For insiders, that means code P purchases, especially when two or more insiders buy within a few weeks. For Congress, it means purchases in the larger dollar ranges and trades in sectors a member's committee oversees. Grants, option exercises, tax withholding and 10b5-1 plan sales are noise for a buy signal.
This is the filter I use.
- Drop everything except codes P and S. On NVDA that left 44 of 76 transactions, all of them sales.
- Flag 10b5-1 sales separately instead of alerting on them. They were 22 of NVDA's 44 sales.
- Keep code P buys, and rank clusters of several insiders above single buys.
- For Congress, skip the smallest bracket, $1,001-$15,000, unless the member trades the stock repeatedly. A trade there can be as small as $1,001.
- Sort congressional alerts by filing date, not trade date. The trade date tells you when it happened, but the filing date is when you could have known.
If a backtest enters on the trade date, it assumes you knew about a trade weeks before the public did. Every result built that way looks better than anything you could have traded.
Check whose account a congressional trade sits in, too. PTRs mark spouse and joint accounts, and a lot of headline trades turn out to be a spouse's managed account rather than the member's own decision.
Free scripts or a hosted API: which should you use?
Use the free scripts if you track one or two tickers a week. Use a hosted API if you need many tickers, fast answers, or no PDF parsing at all. The House scan above downloads 150 PDFs to answer one ticker, so a real tracker runs it as a background job with a database behind it.
That background job is what Edgrapi is. It's my product, so weigh this section accordingly.
It keeps House PTRs parsed in a table as they're posted, parses and caches Form 4s per ticker, and the same NVDA question becomes two requests:
import os
import requests
API = "https://api.edgrapi.com/v1"
HEADERS = {"X-API-Key": os.environ["EDGRAPI_KEY"]}
ins = requests.get(f"{API}/insider/NVDA", params={"limit": 40}, headers=HEADERS).json()
for f in ins["filings"]:
for t in f.get("transactions", []):
if t["code"] == "P":
print("insider buy", f["filed"], f["owner"], t["value"], f["url"])
cong = requests.get(f"{API}/congress/NVDA", headers=HEADERS).json()
for t in cong["trades"]:
print(t["action"], t["transaction_date"], t["member"],
t["amount_low"], t["amount_high"], t["disclosure_url"])
Each congressional trade links to the original House PDF, so you can still cite the source. The NVDA congress trades Edgrapi had on file the day I wrote this match what the free scan found.
The insider call costs 5 credits and the congress call 2. The free tier is 50 credits with no card, enough for about seven tickers, and Starter is $10 a month for 10,000 credits.
The data limits carry over. Coverage is House only, trades can show up 45 days or more after they happen, amounts stay as ranges, and scanned PTRs are missing there too because it reads the same text layer.
Two more gaps. /v1/insider returns original Form 4s, so keep the 4/A handling from the script if amendments matter to you. And its plan_10b5_1 flag is read from footnotes, not the aff10b5One checkbox. On these 40 NVDA filings the two agreed on all 22 planned sales, but read the checkbox yourself if you need it exactly.
If you'd rather ask an AI agent, there's a hosted MCP server at https://api.edgrapi.com/mcp, and Claude or another agent gets the filing links back with the answer.
Frequently asked questions
How do I track congressional stock trades for free?
Use the House Clerk's yearly disclosure index, 2026FD.zip for this year, to list every periodic transaction report, then download each PTR PDF and read its trade rows with a PDF library like pypdf. It costs nothing and needs no key. Expect about 13% of recent PDFs to be scans with no text layer, which need OCR or get missed.
Is there an API for congressional stock trades?
The House has no official API for trades, only the yearly index file and PDFs on the Clerk's site, and the Senate's eFD site has none either. Third-party APIs parse those filings into JSON. Edgrapi, which I build, has a House-only endpoint at 2 credits per call, and others like Quiver Quantitative sell congressional data on paid plans.
How late can members of Congress report a stock trade?
Under the STOCK Act, House members must report a transaction over $1,000 within 30 days of learning about it or 45 days after the trade, whichever is earlier, according to the House Ethics Committee. In practice some filings arrive much later. One PTR filed November 23, 2026 listed an NVDA trade dated April 29.
What does transaction code P mean on a Form 4?
Code P marks an open-market or private purchase, so the insider spent their own money on the stock. The SEC's Form 4 instructions define it alongside S for sales, A for grants, M for option exercises and F for shares withheld for tax. For an insider trading tracker, P is the code worth alerting on.
Where do insider trading trackers get their data?
Almost all of them parse SEC Form 4 filings from EDGAR, which are free XML documents filed within two business days of each trade. Sites like OpenInsider and paid terminals repackage the same filings. You can pull them yourself through data.sec.gov with a User-Agent header and at most 10 requests per second.
Can I track Senate stock trades with Python?
Not easily for free. Senate periodic transaction reports live on efdsearch.senate.gov behind an agreement page and session, and the site has been refusing scripted requests. Your options are browser automation, which is fragile, or a paid data source that covers the Senate. Edgrapi's congress data is House only, so it won't help here.
Run the NVDA scripts on your own watchlist this week
Copy the two scripts, swap NVDA for the tickers you care about, and run them once. Then cache the House index and the PDFs you've already read, so the next run only fetches what was filed since. If the PDF downloads become the slow part, that's the point where a hosted API pays for itself.
Mukul Dutt builds Edgrapi, an API and MCP server for SEC filings, insider trades, 13F holdings, House congressional trades and federal contract data. The scripts in this post are the free version of what Edgrapi runs in production.
Top comments (0)