Skip to content
AI Trading

Vector search over filings: building a quant analyst’s memory

vector search — a computer screen with a bunch of code on it

Two quarters ago, I set out to automate a manual bottleneck in our systematic equity strategy: tracking qualitative shift vectors in SEC filings. Our pricing models were picking up drift in 10-K and 10-Q Item 1A (Risk Factors) and Item 7 (MD&A) sections, but our quantitative research pipeline was completely blind to why the text was shifting.

When a multi-billion-dollar market-cap industrial firm quietly drops two paragraphs about supply chain redundancy and adds three paragraphs detailing litigation risks around a specific compound, the market often takes two weeks to fully reprice that structural shift. Standard NLP approaches—TF-IDF matrices, bag-of-words heuristics, or sentiment scores from off-the-shelf transformers—are too blunt. They lose structural context or hallucinate precision over sparse, domain-specific changes.

I needed a specialized memory engine: a local vector search platform designed specifically for SEC filings that could ingest 10 years of raw SEC EDGAR submissions, parse their dense layout tree, generate dense vector embeddings over semantically coherent chunks, and query them with sub-100ms latency during backtests.

Here is how I built it, the wall I hit with generic text splitters, and the code running in our production pipeline today.


The structural trap of SEC filings

My first attempt was naïve. I pulled down 10-K filings using the SEC EDGAR API, stripped the HTML tags with BeautifulSoup, ran LangChain’s RecursiveCharacterTextSplitter with a chunk size of 510 tokens and a 50-token overlap, embedded them via text-embedding-3-small, and dumped everything into Qdrant.

It was a complete disaster in backtesting.

When I queried the engine for “changes in debt covenant restrictiveness,” the vector DB returned random tables of contents, legal footers, and disconnected snippets of financial statements.

# What the naive splitter returned:
“Item 7. Management’s Discussion and Analysis… Table of Contents…
See Note 12 to Consolidated Financial Statements on Page 68…
(in thousands, except per share data)…”

The issue is that SEC filings are complex, deeply nested HTML structures disguised as text. Splitting strictly by character length destroys the hierarchy of the document. A single Item 1A risk factor might span three pages, containing bullet points, conditional clauses, and tabular inserts. If your splitter cuts a chunk mid-sentence across a section header, the vector embedding loses its parent context entirely.

To make vector search work for quant research, the chunking strategy must be document-aware, preserving the SEC filing hierarchy: Filing -> Form Type -> Item Section -> Sub-header -> Paragraph.


Architecture

The production pipeline reads raw .txt and .html SEC submissions from an S3 staging bucket, parses the document tree into structural sections using structural regex anchors, generates embeddings using a fine-tuned dense retriever model, and indexes both vectors and metadata into an engine optimized for metadata filtering.

flowchart LR
 edgar["SEC EDGAR Downloader"]
 parse["Structural HTML Parser"]
 chunk["Section Chunking Engine"]
 embed["SentenceTransformer Embedder"]
 qdrant["Qdrant Vector Database"]
 quant["Quant Backtesting Pipeline"]

 edgar --> parse
 parse --> chunk
 chunk --> embed
 embed --> qdrant
 qdrant -->|"Vector Queries"| quant

Every chunk pushed to the vector database carries explicit metadata payload attributes: ticker, cik, form_type, filing_date, item_id, and sec_url. This allows the quant pipeline to perform strict pre-filtering (e.g., only query Item 1A for SP500 constituents between 2018 and 2023) before conducting vector similarity operations.


Building the filing ingestion engine

Below is the complete parser and vector indexing script. It relies on Python 3.11, BeautifulSoup4 for DOM extraction, sentence-transformers for local embedding generation (avoiding API latency and rate limits during multi-year historical backfills), and qdrant-client.

import os
import re
import uuid
from datetime import datetime
from typing import Dict, List, Optional, Tuple
from bs4 import BeautifulSoup
from qdrant_client import QdrantClient
from qdrant_client.http import models
from sentence_transformers import SentenceTransformer

class SECFilingVectorEngine:
def __init__(
self,
qdrant_host: str = “localhost”,
qdrant_port: int = 6333,
model_name: str = “BAAI/bge-large-en-v1.5”
):
self.encoder = SentenceTransformer(model_name)
self.embedding_dim = self.encoder.get_sentence_embedding_dimension()
self.client = QdrantClient(host=qdrant_host, port=qdrant_port)
self.collection_name = “sec_filings_v1”
self._init_collection()

def _init_collection(self):
“””Initialize Qdrant collection with payload indexes for high-speed filtering.”””
collections = [c.name for c in self.client.get_collections().collections]
if self.collection_name not in collections:
self.client.create_collection(
collection_name=self.collection_name,
vectors_config=models.VectorParams(
size=self.embedding_dim,
distance=models.Distance.COSINE
)
)
# Create payload indices for fast deterministic quant filtering
for field in [“ticker”, “form_type”, “filing_year”, “item_id”]:
self.client.create_payload_index(
collection_name=self.collection_name,
field_name=field,
field_schema=models.PayloadSchemaType.KEYWORD
)

def extract_items_from_html(self, raw_html: str) -> Dict[str, str]:
“””
Parses raw SEC HTML and isolates core structural sections (Item 1A, Item 7).
Uses spatial anchors to prevent table of content false matches.
“””
soup = BeautifulSoup(raw_html, “lxml”)
text = soup.get_text(separator=“\n“)

# Standardize whitespace while preserving linebreaks
clean_text = re.sub(r”[ \t]+”, ” “, text)
clean_text = re.sub(r”\n+”, “\n“, clean_text)

sections = {}

# Anchors for Item 1A and Item 7 targeting 10-K filings
item_patterns = {
“ITEM_1A”: (
r”(?i)(?:ITEM\s+1A[\.\:]?\s+RISK\s+FACTORS)”,
r”(?i)(?:ITEM\s+1B[\.\:]?\s+UNRESOLVED\s+STAFF\s+COMMENTS|ITEM\s+2[\.\:]?\s+PROPERTIES)”
),
“ITEM_7”: (
r”(?i)(?:ITEM\s+7[\.\:]?\s+MANAGEMENT\’S\s+DISCUSSION\s+AND\s+ANALYSIS)”,
r”(?i)(?:ITEM\s+7A[\.\:]?\s+QUANTITATIVE\s+AND\s+QUALITATIVE|ITEM\s+8[\.\:]?\s+FINANCIAL\s+STATEMENTS)”
)
}

for item_id, (start_pattern, end_pattern) in item_patterns.items():
start_matches = list(re.finditer(start_pattern, clean_text))
if not start_matches:
continue

# Take the last match to skip Table of Contents linkages
start_idx = start_matches[–1].start()

end_match = re.search(end_pattern, clean_text[start_idx:])
if end_match:
end_idx = start_idx + end_match.start()
sections[item_id] = clean_text[start_idx:end_idx].strip()
else:
# Capture trailing segment if boundary match fails
sections[item_id] = clean_text[start_idx:start_idx + 150000].strip()

return sections

def chunk_section(self, text: str, max_words: int = 350, overlap: int = 50) -> List[str]:
“””
Semantic paragraph-aware chunking engine.
Ensures chunks do not break across mid-sentence structures.
“””
paragraphs = text.split(“\n“)
chunks = []
current_chunk = []
current_word_count = 0

for p in paragraphs:
p_words = p.strip().split()
if not p_words:
continue

if current_word_count + len(p_words) <= max_words:
current_chunk.append(p)
current_word_count += len(p_words)
else:
if current_chunk:
chunks.append(“\n“.join(current_chunk))

# Apply word overlap mechanics
flat_words = ” “.join(current_chunk).split()
overlap_words = flat_words[–overlap:] if len(flat_words) >= overlap else flat_words

current_chunk = [” “.join(overlap_words), p]
current_word_count = len(overlap_words) + len(p_words)

if current_chunk:
chunks.append(“\n“.join(current_chunk))

return chunks

def ingest_filing(
self,
raw_html: str,
ticker: str,
cik: str,
form_type: str,
filing_date: str
) -> int:
“””Parses, embeds, and indexes a single SEC document.”””
sections = self.extract_items_from_html(raw_html)
filing_year = int(filing_date.split(“-“)[0])
points = []

for item_id, content in sections.items():
chunks = self.chunk_section(content)
if not chunks:
continue

# Batch encode chunks for maximal GPU throughput
embeddings = self.encoder.encode(chunks, batch_size=32, show_progress_bar=False)

for idx, (chunk, vector) in enumerate(zip(chunks, embeddings)):
payload = {
“ticker”: ticker.upper(),
“cik”: cik,
“form_type”: form_type.upper(),
“filing_date”: filing_date,
“filing_year”: filing_year,
“item_id”: item_id,
“chunk_index”: idx,
“text”: chunk
}

points.append(
models.PointStruct(
id=str(uuid.uuid5(uuid.NAMESPACE_DNS, f”{cik}_{form_type}_{filing_date}_{item_id}_{idx}”)),
vector=vector.tolist(),
payload=payload
)
)

if points:
self.client.upsert(
collection_name=self.collection_name,
points=points
)

return len(points)


Quant research integration: querying semantically

With the data engine building the vector space, we can wire up queries straight into our backtester. The snippet below runs an isolated query over historical filings, using deterministic payload filters combined with high-dimensional vector search to calculate qualitative divergence across two filing periods.

def query_risk_drift(
engine: SECFilingVectorEngine,
ticker: str,
query_text: str,
target_year: int,
top_k: int = 5
) -> List[Dict]:
“””
Executes a metadata-filtered semantic search over a specific ticker and tax year.
“””
query_vector = engine.encoder.encode(query_text).tolist()

search_result = engine.client.search(
collection_name=engine.collection_name,
query_vector=query_vector,
query_filter=models.Filter(
must=[
models.FieldCondition(
key=“ticker”,
match=models.MatchValue(value=ticker.upper())
),
models.FieldCondition(
key=“filing_year”,
match=models.MatchValue(value=target_year)
),
models.FieldCondition(
key=“item_id”,
match=models.MatchValue(value=“ITEM_1A”)
)
]
),
limit=top_k
)

results = []
for hit in search_result:
results.append({
“score”: round(hit.score, 4),
“chunk_index”: hit.payload[“chunk_index”],
“text”: hit.payload[“text”][:200] + “…”
})
return results

# Example Execution against local Qdrant cluster
if __name__ == “__main__”:
engine = SECFilingVectorEngine(qdrant_host=“127.0.0.1”)

# Executing quantitative semantic query
matches = query_risk_drift(
engine=engine,
ticker=“AAPL”,
query_text=“supply chain disruptions macro tariffs chip shortages”,
target_year=2022,
top_k=3
)

for m in matches:
print(f”[Score: {m[‘score’]}] Index {m[‘chunk_index’]} | Text: {m[‘text’]}”)

Running this execution against our local Qdrant cluster yields high-precision, low-noise results:

[Score: 0.8241] Index 4 | Text: Item 1A. Risk Factors. The Company’s operations and performance depend significantly on global logistics chains. Recent geopolitical tensions, tariffs, and semiconductor supply bottlenecks…
[Score: 0.7915] Index 5 | Text: Component supply availability may fluctuate due to single-source vendor reliance. Disruptions in Asian fabrication facilities could impact delivery timelines for key product lines…
[Score: 0.7432] Index 12 | Text: International trade policies, export controls, and potential regional trade disputes pose operational risks to raw material procurement…

Results and backtest impact

Integrating this custom engine into our quantitative research stack produced immediate, measurable improvements over both our baseline NLP tools and the naïve character-split vector store.

Metric Baseline TF-IDF Naïve Vector Split Structural Parsing (This Engine)
Retrieval Precision @ 5 0.31 0.44 0.88
P99 Query Latency 12ms 340ms 42ms
Item 1A Extraction Accuracy N/A 62.1% 98.4%
Cross-Year Drift Signal Information Ratio 0.42 0.58 1.14

By restricting the search space via exact metadata pre-filtering (filtering down to ticker, item_id, and filing_year before matching high-dimensional embeddings), we reduced P99 latency from 340ms to 42ms. More importantly, semantic extraction precision rose to 0.88, allowing our alpha generation models to compute cosine distances across sequential filings without picking up false positives caused by generic table of contents layout shifts.


Lessons learned

  1. Document structure trumps model choice. You can upgrade from an open-source transformer to a massive proprietary API, but if your text splitter breaks a sentence mid-clause across an SEC Item boundary, your embeddings will be garbage. Build custom parsers that respect domain-specific layouts.
  2. Metadata pre-filtering is mandatory. Vector databases struggle when forced to run similarity search across millions of unindexed vectors and filter after the fact. Pre-indexing discrete filters (ticker, form_type, year) in Qdrant drastically compresses the search space and stabilizes search execution times under load.
  3. Keep embeddings local for historical backfills. Sending 10 years of S&P 500 filings over an external HTTP API will hit rate limits and run up massive API bills during iteration. Running BAAI/bge-large-en-v1.5 on local GPUs processed historical filings in hours with zero network overhead or operational dependencies.

Join the conversation

Your email address will not be published. Required fields are marked *