SEC data in Python
The SEC’s data is free. Each request sends your name and email in the User-Agent, which you set in a notebook with import os and os.environ["SEC_USER_AGENT"] = "Your Name name@example.com". The SEC allows at most 10 requests per second (SEC rules). Run pip install pandas requests. Each script picks one SEC file, a quarter of filings or, for Form 13F, three months. For more, rerun with another URL or loop over links and join the tables with pd.concat. Each script saves one long-format CSV in FOLDER (default Downloads), overwriting any file of the same name.
If a script does not work as it should, email me.
Insider trades (Form 4)
One row per open-market or private purchase or sale of shares or other non-derivative securities on a Form 4, without amendments (Form 4/A). The variables include the trade and filing dates, the company, the reporting owners, the share count, the price and the accession number. The SEC publishes one ZIP file per quarter since 2006. The example covers July to September 2026.
Choose these settings in the code:
URL, the quarter’s ZIP link from the SEC’s Insider Transactions Data Sets page. The folder in the link changes by quarter.CODES, P for purchases and S for sales.SEC_USER_AGENT, your name and email.FOLDER, the output folder.
import io
import os
import zipfile
from pathlib import Path
import pandas as pd
import requests
URL = ("https://www.sec.gov/files/datastandardsinnovation/data/insider-transactions-data-sets/"
"2026q3_form345.zip") # for another quarter, copy its ZIP link from the SEC's page
HEADERS = {"User-Agent": os.environ["SEC_USER_AGENT"]} # your name and email, set as SEC_USER_AGENT
CODES = ["P", "S"] # P for purchases and S for sales, in the open market or in private deals
FOLDER = Path.home() / "Downloads" # change this to the folder for the CSV file
# Step 1. Download the ZIP file into memory
response = requests.get(URL, headers=HEADERS, timeout=120)
response.raise_for_status()
archive = zipfile.ZipFile(io.BytesIO(response.content))
# Step 2. The filings, reporting owners and transactions in securities that are not derivatives
submissions = pd.read_csv(archive.open("SUBMISSION.tsv"), sep="\t", dtype=str,
keep_default_na=False, na_values=[""])
owners = pd.read_csv(archive.open("REPORTINGOWNER.tsv"), sep="\t", dtype=str)
trades = pd.read_csv(archive.open("NONDERIV_TRANS.tsv"), sep="\t", dtype=str)
# Step 3. One row per transaction on a Form 4, with the company and the owners on its filing
columns = ["ACCESSION_NUMBER", "FILING_DATE", "ISSUERCIK", "ISSUERNAME", "ISSUERTRADINGSYMBOL"]
form4 = submissions.loc[submissions["DOCUMENT_TYPE"] == "4", columns]
names = owners.groupby("ACCESSION_NUMBER")["RPTOWNERNAME"].agg("; ".join).rename("OWNERS")
deals = (trades[trades["TRANS_CODE"].isin(CODES)].merge(form4, on="ACCESSION_NUMBER")
.merge(names, on="ACCESSION_NUMBER"))
# Step 4. Named columns, dates and numbers, saved as one CSV file
labels = {"TRANS_DATE": "date", "ISSUERTRADINGSYMBOL": "ticker", "ISSUERNAME": "company",
"OWNERS": "owners", "SECURITY_TITLE": "security", "TRANS_CODE": "code",
"TRANS_SHARES": "shares", "TRANS_PRICEPERSHARE": "price", "FILING_DATE": "filed",
"ISSUERCIK": "cik", "ACCESSION_NUMBER": "accession"}
panel = deals.rename(columns=labels)[list(labels.values())]
panel["date"] = pd.to_datetime(panel["date"], format="%d-%b-%Y")
panel["filed"] = pd.to_datetime(panel["filed"], format="%d-%b-%Y")
panel[["shares", "price"]] = panel[["shares", "price"]].astype(float)
quarter = URL.split("/")[-1].split("_")[0] # such as 2026q3, for the file name
FOLDER.mkdir(parents=True, exist_ok=True)
panel.sort_values("date", kind="stable").to_csv(FOLDER / f"sec_insider_trades_{quarter}.csv", index=False)
print(len(panel), "transactions saved")Full post: How to download SEC Form 4 insider trading data in Python
Institutional holdings (Form 13F)
One row per report and security for share holdings in original reports (13F-HR), without amendments and options. The variables include the manager, the report and filing dates, the shares in millions and the market value in millions of dollars. The example covers filings from June to August 2026, mostly for 30 June 2026.
Choose these settings in the code:
URL, a ZIP link from the SEC’s Form 13F Data Sets page.VALUE_DIVISOR, 1e6 for filings from 3 January 2023, which report VALUE in dollars, and 1e3 for earlier ones, in thousands of dollars.SEC_USER_AGENT, your name and email.FOLDER, the output folder.
import io
import os
import zipfile
from pathlib import Path
import pandas as pd
import requests
URL = ("https://www.sec.gov/files/datastandardsinnovation/data/form-13f-data-sets/"
"01jun2026-31aug2026_form13f.zip") # for other months, copy another ZIP link from the SEC's page
HEADERS = {"User-Agent": os.environ["SEC_USER_AGENT"]} # your name and email, set as SEC_USER_AGENT
VALUE_DIVISOR = 1e6 # dollars to millions (1e3 for filings before 3 January 2023, in thousands)
FOLDER = Path.home() / "Downloads" # change this to the folder for the CSV file
# Step 1. Download the ZIP file into memory
response = requests.get(URL, headers=HEADERS, timeout=300)
response.raise_for_status()
archive = zipfile.ZipFile(io.BytesIO(response.content))
# Step 2. One row per report, with the manager's name from the cover page
submissions = pd.read_csv(archive.open("SUBMISSION.tsv"), sep="\t", dtype=str)
covers = pd.read_csv(archive.open("COVERPAGE.tsv"), sep="\t", dtype=str)
filings = submissions.merge(covers, on="ACCESSION_NUMBER", how="left", validate="one_to_one")
labels = {"ACCESSION_NUMBER": "filing", "CIK": "cik", "FILINGMANAGER_NAME": "manager",
"SUBMISSIONTYPE": "form", "PERIODOFREPORT": "report_date", "FILING_DATE": "filed"}
filings = filings.rename(columns=labels)[list(labels.values())]
# Step 3. All lines of each report, with share or principal amounts and market values in millions
labels = {"ACCESSION_NUMBER": "filing", "NAMEOFISSUER": "issuer", "TITLEOFCLASS": "share_class",
"CUSIP": "cusip", "VALUE": "value_usd_m", "SSHPRNAMT": "shares_m",
"SSHPRNAMTTYPE": "unit", "PUTCALL": "option"}
lines = pd.read_csv(archive.open("INFOTABLE.tsv"), sep="\t", usecols=list(labels), dtype=str)
lines["VALUE"] = lines["VALUE"].astype(float) / VALUE_DIVISOR
lines["SSHPRNAMT"] = lines["SSHPRNAMT"].astype(float) / 1e6
lines = lines.rename(columns=labels)
# Step 4. One row per report and security, from the original reports (13F-HR), shares only, no options
reports = filings[filings["form"] == "13F-HR"]
keep = lines["filing"].isin(reports["filing"]) & (lines["unit"] == "SH") & lines["option"].isna()
panel = (lines[keep].groupby(["filing", "cusip"], as_index=False)
.agg(issuer=("issuer", "first"), share_class=("share_class", "first"),
shares_m=("shares_m", "sum"), value_usd_m=("value_usd_m", "sum"))
.merge(reports[["filing", "cik", "manager", "report_date", "filed"]], on="filing",
validate="many_to_one"))
# Step 5. Dates, saved as one CSV file
panel["report_date"] = pd.to_datetime(panel["report_date"], format="%d-%b-%Y")
panel["filed"] = pd.to_datetime(panel["filed"], format="%d-%b-%Y")
period = URL.split("/")[-1].removesuffix("_form13f.zip") # such as 01jun2026-31aug2026, for the file name
FOLDER.mkdir(parents=True, exist_ok=True)
panel.to_csv(FOLDER / f"sec_13f_holdings_{period}.csv", index=False)
print(len(panel), "holdings saved")Large stakes (Schedule 13D)
One row per initial Schedule 13D filed in July to September 2026, with the event and filing dates, the issuer (CIK and first CUSIP) and the first filer (shares in millions and percent of the class). Unreadable filings go to a second CSV.
Choose these settings in the code:
URL, the master index of a year and quarter, from the first quarter of 2025, because the script reads the XML cover pages mandatory since 18 December 2024.SEC_USER_AGENT, your name and email.FOLDER, the output folder.
import io
import os
import time
from pathlib import Path
from xml.etree import ElementTree
import pandas as pd
import requests
from requests.adapters import HTTPAdapter
from urllib3.util import Retry
URL = "https://www.sec.gov/Archives/edgar/full-index/2026/QTR3/master.idx" # another year and quarter, from 2025 QTR1
HEADERS = {"User-Agent": os.environ["SEC_USER_AGENT"]} # your name and email, set as SEC_USER_AGENT
FOLDER = Path.home() / "Downloads" # change this to the folder for the CSV file
# Step 1. Download the master index and keep one row per initial Schedule 13D, with its folder
response = requests.get(URL, headers=HEADERS, timeout=300)
response.raise_for_status()
columns = ["cik", "company", "form", "filed", "file"]
index = pd.read_csv(io.BytesIO(response.content), encoding="latin-1", sep="|", skiprows=11,
names=columns, dtype=str)
filings = index[index["form"] == "SCHEDULE 13D"].copy()
filings["accession"] = filings["file"].str.split("/").str[-1].str.removesuffix(".txt")
filings["folder"] = ("https://www.sec.gov/Archives/"
+ filings["file"].str.removesuffix(".txt").str.replace("-", "") + "/")
filings = filings.drop_duplicates("accession")
assert len(filings), "The index has no initial Schedule 13D. Pick a quarter from 2025 on."
# Step 2. Each cover page's issuer and first investor, retrying a request up to five times.
# A filing that cannot be read goes to a list of failed filings, and the loop goes on.
NS = {"s": "http://www.sec.gov/edgar/schedule13D"}
retry = Retry(total=5, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504])
session = requests.Session()
session.mount("https://", HTTPAdapter(max_retries=retry))
rows, failed = [], []
for accession, folder in zip(filings["accession"], filings["folder"]):
try:
response = session.get(folder + "primary_doc.xml", headers=HEADERS, timeout=60)
response.raise_for_status()
root = ElementTree.fromstring(response.content)
persons = pd.read_xml(io.BytesIO(response.content), xpath=".//s:reportingPersonInfo",
namespaces=NS, parser="etree")
shares = pd.to_numeric(persons["aggregateAmountOwned"], errors="coerce")
percent = pd.to_numeric(persons["percentOfClass"], errors="coerce")
rows.append({"accession": accession,
"event_date": root.findtext(".//s:dateOfEvent", namespaces=NS),
"issuer": root.findtext(".//s:issuerInfo/s:issuerName", namespaces=NS),
"issuer_cik": root.findtext(".//s:issuerInfo/s:issuerCIK", namespaces=NS),
"cusip": root.findtext(".//s:issuerCusipNumber", namespaces=NS),
"filer": persons["reportingPersonName"].iloc[0],
"shares_m": shares.iloc[0] / 1e6, "percent": percent.iloc[0]})
except Exception as error:
failed.append({"accession": accession, "error": str(error)[:200]})
time.sleep(0.2)
# Step 3. The failed filings (if any) and one row per filing, with the filing date and folder from the master
# index, saved as CSV files
quarter = "_".join(URL.split("/")[-3:-1]) # such as 2026_QTR3, for the file names
FOLDER.mkdir(parents=True, exist_ok=True)
failed_file = FOLDER / f"sec_13d_failed_{quarter}.csv"
if failed:
pd.DataFrame(failed).to_csv(failed_file, index=False)
else:
failed_file.unlink(missing_ok=True) # the list of an earlier run
assert rows, f"No filing could be read. The errors are in {failed_file}."
panel = pd.DataFrame(rows).merge(filings[["accession", "filed", "folder"]], on="accession")
panel["event_date"] = pd.to_datetime(panel["event_date"], format="%m/%d/%Y", errors="coerce")
panel["filed"] = pd.to_datetime(panel["filed"], format="%Y-%m-%d")
panel.to_csv(FOLDER / f"sec_13d_filings_{quarter}.csv", index=False)
print(len(panel), "filings saved,", len(failed), "failed")