Every tax season, engineering teams and accounting operators try the same shortcut: dump a 40-page Fidelity, Schwab, Robinhood, or Interactive Brokers Consolidated 1099-B PDF into a multimodal LLM and ask for an IRS Form 8949 CSV.
It looks convincing on the first 5 rows—and silently fails an audit on rows 6 through 400.
Tax preparation has zero tolerance for probabilistic arithmetic. A single inverted Wash Sale Adjustment (Code W) sign, a dropped column coordinate on page 19, or a misclassified 366-day holding period creates an instant mismatch against the IRS CP2000 automated underreporter check.
Here is a breakdown of the 4 deterministic failure modes in brokerage 1099-B PDF parsing, along with a complete, self-contained Python verification harness you can run locally to reconcile every trade line down to the penny.
1. Why Raw PDF Text Extraction Breaks Brokerage Tables
Brokerage statements are multi-column coordinate grids—not linear prose. When you call page.extract_text() with default settings in most PDF libraries, closely spaced numeric columns (Proceeds, Cost Basis, Wash Sale Loss Disallowed) or blank adjustment cells collapse into adjacent tokens.
Preserving horizontal layout coordinates (layout=True in pdfplumber) keeps column alignment intact so line-level regex or x-coordinate slicing doesn't shift a blank Wash Sale column into the Gain/Loss column.
import io import pdfplumber def extract_layout_lines(pdf_bytes: bytes) -> list[str]: lines: list[str] = [] with pdfplumber.open(io.BytesIO(pdf_bytes)) as pdf: for page in pdf.pages: # layout=True preserves horizontal whitespace alignment across columns text = page.extract_text(layout=True) or page.extract_text() or "" for raw_line in text.splitlines(): cleaned = " ".join(raw_line.split()).strip() if cleaned: lines.append(cleaned) return lines 2. The 3 Deterministic Rules of IRS Form 8949
Once you extract (security, date_acquired, date_sold, proceeds, cost_basis, wash_sale_disallowed), you must apply three strict IRS rules—none of which should ever be guessed by a language model:
Rule A: Holding Period Boundary (> 365 days)
- Short-Term (Part I): Held 1 year or less (
(date_sold - date_acquired).days <= 365). Note that buying on2025-03-15and selling on2026-03-15is 365 days—still Short-Term. You must hold for more than 1 year (> 365days, or> 366in a leap-year span) to qualify for Long-Term capital gains rates. - Long-Term (Part II): Held more than 1 year.
Rule B: Form 8949 Checkbox Classification (Box A/B vs Box D/E)
Brokerages report whether cost basis was transmitted to the IRS ("Covered" vs "Noncovered"):
- Covered Securities (Basis Reported to IRS):
- Short-Term → Box A
- Long-Term → Box D
- Noncovered Securities (Basis NOT Reported to IRS):
- Short-Term → Box B
- Long-Term → Box E
Rule C: Wash Sale Disallowed (Code W) Sign Arithmetic
This is the #1 bug in DIY scripts and LLM outputs. On Form 8949:
- Column (d) = Proceeds
- Column (e) = Cost or other basis
- Column (f) = Adjustment Code (
Wfor wash sale loss disallowed) - Column (g) = Amount of adjustment (positive number adding back the disallowed loss)
- Column (h) = Gain or (loss):
Proceeds - Cost Basis + Adjustment
If you sold TSLA for $3,150.00 with a $3,600.00 cost basis, your raw economic loss is -$450.00. If $450.00 is disallowed under the 30-day wash sale rule (IRS Code W), your taxable gain/loss on Form 8949 is:
$3,150.00 - $3,600.00 + $450.00 = $0.00 LLMs frequently subtract the $450 instead of adding it back, reporting -$900.00—double-counting the loss.
3. Complete Deterministic Verification Script (Run Locally)
Before exporting any Form 8949 Excel or CSV file, run a double-entry reconciliation invariant across every parsed trade:
sum(Gain/Loss) == sum(Proceeds) - sum(Cost Basis) + sum(Wash Sales Disallowed) Here is a self-contained Python script using decimal.Decimal (to avoid binary floating-point rounding drift) that parses normalized trade lines, assigns IRS Form 8949 boxes, and verifies the accounting invariant:
from datetime import datetime from decimal import Decimal, ROUND_HALF_UP import re TRADE_LINE_RE = re.compile( r"^([A-Z0-9 .\-/()]{2,34}?)\s+" r"(\d{4}-\d{2}-\d{2}|\d{1,2}/\d{1,2}/\d{2,4})\s+" r"(\d{4}-\d{2}-\d{2}|\d{1,2}/\d{1,2}/\d{2,4})\s+" r"\$?([\d,]+\.\d{2})\s+" r"\$?([\d,]+\.\d{2})\s+" r"\$?([\d,]+\.\d{2})$", re.IGNORECASE, ) def to_decimal(val: str) -> Decimal: cleaned = re.sub(r"[^0-9.-]", "", val) return Decimal(cleaned).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) def parse_date(val: str) -> datetime: for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y"): try: return datetime.strptime(val.strip(), fmt) except ValueError: continue raise ValueError(f"Unrecognized date format: {val}") def classify_1099b_lines(lines: list[str], covered: bool = True) -> dict: trades = [] for line in lines: m = TRADE_LINE_RE.match(line.strip()) if not m: continue security = m.group(1).strip() d_acq = parse_date(m.group(2)) d_sold = parse_date(m.group(3)) proceeds = to_decimal(m.group(4)) basis = to_decimal(m.group(5)) wash_disallowed = to_decimal(m.group(6)) holding_days = (d_sold - d_acq).days term = "Long-Term" if holding_days > 365 else "Short-Term" box = ("D" if covered else "E") if term == "Long-Term" else ("A" if covered else "B") adj_code = "W" if wash_disallowed > Decimal("0.00") else "" net_gain = (proceeds - basis + wash_disallowed).quantize(Decimal("0.01")) trades.append({ "security": security, "date_acquired": d_acq.strftime("%Y-%m-%d"), "date_sold": d_sold.strftime("%Y-%m-%d"), "holding_days": holding_days, "term": term, "form_8949_box": f"Box {box}", "proceeds": proceeds, "cost_basis": basis, "adj_code": adj_code, "wash_sale": wash_disallowed, "gain_loss": net_gain, }) tot_proceeds = sum((t["proceeds"] for t in trades), Decimal("0.00")) tot_basis = sum((t["cost_basis"] for t in trades), Decimal("0.00")) tot_wash = sum((t["wash_sale"] for t in trades), Decimal("0.00")) tot_gain = sum((t["gain_loss"] for t in trades), Decimal("0.00")) # Deterministic reconciliation check: must equal 0.00 reconciliation_delta = tot_gain - (tot_proceeds - tot_basis + tot_wash) assert reconciliation_delta == Decimal("0.00"), f"Ledger mismatch: {reconciliation_delta}" return { "trades": trades, "total_proceeds": tot_proceeds, "total_basis": tot_basis, "total_wash_sales": tot_wash, "net_gain_loss": tot_gain, } if __name__ == "__main__": sample_lines = [ "AAPL (25 sh) 2024-03-15 2026-06-10 $5,850.00 $4,250.00 $0.00", "NVDA (40 sh) 2025-11-20 2026-04-12 $5,400.00 $4,920.00 $0.00", "TSLA (15 sh) 2026-01-10 2026-02-05 $3,150.00 $3,600.00 $450.00", "QQQ (15 sh) 2026-03-01 2026-03-28 $6,420.00 $6,710.00 $290.00", ] report = classify_1099b_lines(sample_lines, covered=True) for t in report["trades"]: print( f"{t['security']:14} | {t['term']:10} ({t['form_8949_box']}) | " f"Code={t['adj_code'] or '-':1} | Wash=${t['wash_sale']:>6} | Net=${t['gain_loss']:>7}" ) print(f"Reconciled Net Gain/Loss: ${report['net_gain_loss']}") Running this produces an exact, auditable breakdown:
AAPL (25 sh) | Long-Term (Box D) | Code=- | Wash=$ 0.00 | Net=$1600.00 NVDA (40 sh) | Short-Term (Box A) | Code=- | Wash=$ 0.00 | Net=$ 480.00 TSLA (15 sh) | Short-Term (Box A) | Code=W | Wash=$450.00 | Net=$ 0.00 QQQ (15 sh) | Short-Term (Box A) | Code=W | Wash=$290.00 | Net=$ 0.00 Reconciled Net Gain/Loss: $2080.00 4. Handling Edge Cases in Production Brokerage PDFs
If you are building an internal parser for Fidelity, Schwab, Robinhood, Vanguard, or IBKR statements, watch out for three real-world layout quirks:
- Various Acquired Dates (
VARIOUS): Dividend reinvestment (DRIP) sales often printVARIOUSinstead of an ISO/US date. Your parser should detectVARIOUSand preserve the Short-Term/Long-Term section header context from the brokerage PDF rather than failing date parsing. - Multi-Line Security Descriptions: Brokerages frequently wrap long ETF names or CUSIP strings onto a second line above or below the numeric row. Accumulate non-numeric buffer lines or extract by y-coordinate bounding boxes in
pdfplumberbefore running regex matching. - Zero-LLM Data Privacy: Brokerage PDFs contain account numbers, SSNs/TINs, and trade histories. Keep parsing strictly in-memory without shipping raw tax PDFs to external third-party LLM endpoints.
5. Want a Ready-to-Use 3-Tab IRS Form 8949 Workbook (No Setup)?
If you don't want to maintain PDF coordinate parsers and Excel formatters yourself, you can test or run your statement through the deterministic Brokerage 1099-B PDF to IRS Form 8949 Excel Converter:
- Zero Login & Zero LLM Calls: Parses 100% deterministically in memory.
- Free Instant Preview + Sample PDF: Click Try Sample on the page to inspect extracted trades, Short-Term vs Long-Term Box classification, and Code
WWash Sale totals before downloading anything. - CPA-Ready 3-Tab Output (
.xlsx,.csv,.json): ExportsForm 8949 Trades,ST vs LT Summary(Part I vs Part II), and a dedicatedWash Sales Audittab. - Automating via API?: Developers integrating tax extraction into bookkeeping or fintech workflows can call
POST /api/v1/tax/1099b-to-8949directly (documented athttps://tools.takefox.com/developers).

