How to pull sales comps from property transaction data

The short answer

To pull sales comps, query Datafiniti Property Data at POST /v4/properties/search for your area and property type plus transactions.price:* and a recent transactions.saleDate range. Download the matches, keep each property's latest qualifying sale from the transactions array, and rank them against the subject on floorSizeValue, numBedroom, numBathroom, yearBuilt, and distance. The result is a short comp list and a price-per-square-foot value range.

Datafiniti Team Last updated 10 min read

Key facts

  • Search endpoint: POST https://api.datafiniti.co/v4/properties/search with bearer-token auth.
  • transactions is a nested list of completed sales. Its entries include saleDate, price, and documentType.
  • Filter for sold properties with transactions.price:* and a date range such as transactions.saleDate:[2026-05-18 TO *].
  • Datafiniti's docs say transaction records are typically available within 2 weeks after a property is marked as sold.
  • A search without a download returns at most 10 records. Credits are charged per record returned, and 0 records cost nothing.
  • Larger pulls use "download": true, then GET /v4/downloads/{id} until the status is "completed".

Datafiniti is a data-as-a-service provider that offers Property, People, Business, and Product data through a REST API, bulk downloads, and an MCP server. This guide covers one job: finding recent comparable sales for a property and turning them into a value range your product can show.

Who needs sales comps from an API?

  • Proptech and listing products that show "recent sales nearby" or a price range on a property page.
  • Investors and iBuyers screening deals before they order an appraisal or inspection.
  • Lenders and underwriters sanity-checking a purchase price or an automated valuation.
  • Agents' CMA tools that need sold prices outside a single MLS.
  • AI agents that answer "what did similar homes near this address sell for?" and need sources they can cite.

Why are sales comps hard to build yourself?

A comp is a simple idea: similar homes, nearby, sold recently. Each part of that sentence is a data problem.

  • Sales are recorded county by county. Deed records sit in thousands of county systems with different formats, fees, and update schedules.
  • Not every recorded document is a sale. Deeds of trust, quit claims, and intrafamily transfers sit next to arm's-length sales. Mix them in and your median drops.
  • Sales have to be joined to property facts. A deed rarely carries bedrooms, square footage, or year built. You need a property record to match it to.
  • Listing data alone misses sales. Sold prices scraped from listing sites cover only homes that were listed online.
  • Freshness matters. A comp set that is six months stale in a moving market gives a confident wrong answer.

What fields do you use for sales comps?

FieldTypeWhat it tells you
transactionsnestedList of transactional data after a sale is completed
transactions.saleDatedate (example value)When the sale happened
transactions.pricenumber (example value)Recorded sale price
transactions.documentTypetextRecorded document, such as "Warranty Deed", "Quit Claim", or "Deed of Trust"
transactions.typetextTransaction type; the docs give "NHO" (new home owner) and "REFI" (refinance) as examples
mostRecentSoldPriceAmount, mostRecentSoldPriceDatefloat, dateThe most recent "sale" price from the prices field, a listing-sourced cross-check
propertyTypetextProperty classification, such as "Single Family Dwelling" or "Condo"
numBedroom, numBathroominteger, floatRoom counts for similarity
floorSizeValue, floorSizeUnitfloat, keywordLiving area and its unit, such as "sq ft"
lotSizeValue, lotSizeUnitinteger, keywordLot size and its unit
yearBuiltintegerYear the property was built
latitude, longitudetextCoordinates for distance
geoLocationgeo_shapeCoordinates for radius queries
postalCode, city, province, countrykeyword, textTop-level location fields for filtering
parcelNumbersnestedParcel numbers (number, account, year) for joining to your own records

Transaction entries also carry buyer, seller, and lender names and loan details. You don't need any of them to compute comps, so drop them before you store or display results.

A trimmed record looks like this (fictional example data; name fields omitted):

property record · JSON (fictional)
{
"address": "2214 Larkspur Hollow Dr",
"city": "Charlotte",
"province": "NC",
"postalCode": "28205",
"country": "US",
"propertyType": "Single Family Dwelling",
"numBedroom": 3,
"numBathroom": 2,
"floorSizeValue": 1780,
"floorSizeUnit": "sq ft",
"yearBuilt": 1996,
"latitude": "35.2134",
"longitude": "-80.8011",
"mostRecentSoldPriceAmount": 455000,
"mostRecentSoldPriceDate": "2026-09-30T00:00:00Z",
"transactions": [
{
"saleDate": "2026-09-30T12:00:00Z",
"price": 455000.0,
"documentType": "Warranty Deed",
"parcelNumber": "000-EXAMPLE-01"
},
{
"saleDate": "2014-06-11T12:00:00Z",
"price": 0.0,
"documentType": "Quit Claim",
"parcelNumber": "000-EXAMPLE-01"
}
]
}

How do I pull comps step by step?

Step 1: Define the comp area and size it

Start with the subject property's area and type. Use top-level location fields, a bedroom range, and a six-month sale window computed from today. Wrap the ZIP list in parentheses.

Check the size before you pay for records. The MCP tool df_count is free. Over REST, send "num_records": 1 and read num_found; that costs at most 1 credit.

size_comps.py · Python 3
import os
from datetime import date, timedelta
import requests
API = "https://api.datafiniti.co/v4"
HEADERS = {
"Authorization": f"Bearer {os.environ['DATAFINITI_API_TOKEN']}",
"Content-Type": "application/json",
}
SINCE = (date.today() - timedelta(days=180)).isoformat()
QUERY = (
"country:US AND province:NC AND city:Charlotte "
"AND postalCode:(28205 OR 28209) "
"AND propertyType:\"Single Family Dwelling\" "
"AND numBedroom:[3 TO 4] "
f"AND transactions.price:* AND transactions.saleDate:[{SINCE} TO *]"
)
r = requests.post(f"{API}/properties/search", headers=HEADERS, timeout=60,
json={"query": QUERY, "num_records": 1})
r.raise_for_status()
print("candidate comps:", r.json()["num_found"])

If you have the subject's coordinates, Datafiniti's query syntax also supports a radius: geoLocation:[-80.8052,35.2101,1,mi] (longitude, latitude, distance, unit).

Step 2: Look at one record

Read one record before writing ranking code. Check which documentType values your county uses and whether floorSizeValue is populated.

cURL
curl --request POST \
--url https://api.datafiniti.co/v4/properties/search \
--header "Authorization: Bearer $DATAFINITI_API_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"query": "country:US AND province:NC AND city:Charlotte AND postalCode:(28205 OR 28209) AND propertyType:\"Single Family Dwelling\" AND transactions.price:* AND transactions.saleDate:[2026-05-18 TO *]",
"num_records": 1
}'

Replace the date with one 180 days before today.

Step 3: Download the comp pool and keep qualifying sales

Searches without a download return at most 10 records, so pull the pool as a download. Set num_records to cap spend; you're charged for the records you download. The script keeps each property's latest sale inside the window, skips non-sale documents and refinances, and writes one row per comp.

pull_comps.py · Python 3
import csv
import json
import os
import time
from datetime import date, timedelta
import requests
API = "https://api.datafiniti.co/v4"
HEADERS = {
"Authorization": f"Bearer {os.environ['DATAFINITI_API_TOKEN']}",
"Content-Type": "application/json",
}
SINCE = (date.today() - timedelta(days=180)).isoformat()
QUERY = (
"country:US AND province:NC AND city:Charlotte "
"AND postalCode:(28205 OR 28209) "
"AND propertyType:\"Single Family Dwelling\" "
"AND numBedroom:[3 TO 4] "
f"AND transactions.price:* AND transactions.saleDate:[{SINCE} TO *]"
)
MAX_RECORDS = 500 # caps spend: credits are charged per record
MIN_PRICE = 10000 # drop nominal transfers
SKIP_DOCS = ("quit claim", "intrafamily", "affidavit", "deed of trust",
"loan modification", "lease", "administrative")
def start_download(query, limit):
body = {"query": query, "num_records": limit, "format": "json", "download": True}
r = requests.post(f"{API}/properties/search", headers=HEADERS, json=body, timeout=60)
r.raise_for_status()
data = r.json()
return data.get("download_id") or data.get("id")
def wait_for(download_id):
while True:
r = requests.get(f"{API}/downloads/{download_id}", headers=HEADERS, timeout=60)
r.raise_for_status()
job = r.json()
if job["status"] == "completed":
return job
if job["status"] == "cancelled":
raise RuntimeError("download was cancelled")
time.sleep(10)
def fetch_records(job):
for item in job.get("results") or []:
url = item["url"] if isinstance(item, dict) else item
text = requests.get(url, timeout=300).text.strip()
if text.startswith("["):
yield from json.loads(text)
else:
for line in text.splitlines():
if line.strip():
yield json.loads(line)
def qualifying_sale(rec):
"""Latest arm's-length-looking sale inside the window, or None."""
best = None
for t in rec.get("transactions") or []:
price, sold = t.get("price"), str(t.get("saleDate") or "")[:10]
doc = (t.get("documentType") or "").lower()
if not price or float(price) < MIN_PRICE or sold < SINCE:
continue
if any(s in doc for s in SKIP_DOCS) or (t.get("type") or "").upper() == "REFI":
continue
if best is None or sold > best[0]:
best = (sold, float(price), t.get("documentType"))
return best
records = list(fetch_records(wait_for(start_download(QUERY, MAX_RECORDS))))
rows = []
for rec in records:
sale = qualifying_sale(rec)
if not sale:
continue
size = rec.get("floorSizeValue")
unit = (rec.get("floorSizeUnit") or "").lower()
sqft = float(size) if size and "ft" in unit else None
rows.append({
"id": rec.get("id"),
"address": rec.get("address"),
"postalCode": rec.get("postalCode"),
"latitude": rec.get("latitude"),
"longitude": rec.get("longitude"),
"numBedroom": rec.get("numBedroom"),
"numBathroom": rec.get("numBathroom"),
"sqft": sqft,
"yearBuilt": rec.get("yearBuilt"),
"saleDate": sale[0],
"salePrice": sale[1],
"documentType": sale[2],
"pricePerSqft": round(sale[1] / sqft, 2) if sqft else None,
})
with open("comp_pool.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
print(f"{len(records)} records downloaded, {len(rows)} usable sales")

The query matches properties that have a price and a sale date in the window. Those two conditions can come from different transactions, so the script re-checks the date and price on each entry.

Step 4: Rank comps against the subject and estimate a range

Score each comp on size, rooms, age, and distance, keep the closest six, and apply their price per square foot to the subject.

rank_comps.py · Python 3
import csv
import math
import statistics
SUBJECT = { # the property you are pricing (fictional)
"numBedroom": 3, "numBathroom": 2.0, "sqft": 1850,
"yearBuilt": 1998, "latitude": 35.2101, "longitude": -80.8052,
}
TOP_N = 6
def miles(lat1, lon1, lat2, lon2):
p = math.pi / 180
a = (math.sin((lat2 - lat1) * p / 2) ** 2 + math.cos(lat1 * p)
* math.cos(lat2 * p) * math.sin((lon2 - lon1) * p / 2) ** 2)
return 7918 * math.asin(math.sqrt(a))
def num(v):
try:
return float(v)
except (TypeError, ValueError):
return None
def score(comp):
"""Lower is more similar. Weights are a starting point; tune them."""
sqft, beds, baths = num(comp["sqft"]), num(comp["numBedroom"]), num(comp["numBathroom"])
if not sqft or beds is None:
return None
s = abs(sqft - SUBJECT["sqft"]) / SUBJECT["sqft"] * 10
s += abs(beds - SUBJECT["numBedroom"]) * 2
s += abs((baths or 0) - SUBJECT["numBathroom"]) * 1.5
built = num(comp["yearBuilt"])
s += abs(built - SUBJECT["yearBuilt"]) / 10 if built else 2
lat, lon = num(comp["latitude"]), num(comp["longitude"])
s += miles(SUBJECT["latitude"], SUBJECT["longitude"], lat, lon) * 2 if lat and lon else 3
return s
with open("comp_pool.csv", encoding="utf-8") as f:
pool = [c for c in csv.DictReader(f) if num(c["pricePerSqft"])]
ranked = sorted((c for c in pool if score(c) is not None), key=score)[:TOP_N]
ppsf = sorted(num(c["pricePerSqft"]) for c in ranked)
for c in ranked:
print(f'{c["address"]:<32} {c["saleDate"]} ${num(c["salePrice"]):>10,.0f} '
f'${num(c["pricePerSqft"]):>6,.0f}/sqft score {score(c):.1f}')
if len(ppsf) >= 3:
mid = statistics.median(ppsf) * SUBJECT["sqft"]
q = statistics.quantiles(ppsf, n=4) if len(ppsf) >= 4 else [ppsf[0], 0, ppsf[-1]]
low, high = q[0] * SUBJECT["sqft"], q[2] * SUBJECT["sqft"]
print(f"Indicated value: ${mid:,.0f} (middle range ${low:,.0f} to ${high:,.0f}, "
f"{len(ppsf)} comps)")
else:
print("Fewer than 3 usable comps: widen the date window or the area.")

The weights are a starting point. Size and distance usually matter most; tune them against sales you already know.

Step 5: Put the comps to work

  • Property pages: show the top comps with sale date, price, and distance, plus the middle price range.
  • Deal screening: flag listings priced well above the comp range before anyone opens a spreadsheet.
  • Underwriting checks: compare a contract price or automated value against comps and route outliers to review.
  • Market pages: rerun weekly by ZIP code and publish median price per square foot with the sale count.

To catch new sales as they happen, see How to track property status changes with an API. To run comps for a list of your own addresses, start with How to match an address list to property records.

Can an AI agent pull sales comps?

Yes, for one-off lookups. Connect an MCP client to https://api.datafiniti.co/v4/mcp (Streamable HTTP) with your API token as a bearer header:

MCP client config
{
"mcpServers": {
"datafiniti": {
"type": "http",
"url": "https://api.datafiniti.co/v4/mcp",
"headers": { "Authorization": "Bearer ${DATAFINITI_API_TOKEN}" }
}
}
}

Use "data_type": "property" with df_count (free) to size the query and df_search (up to 50 records per call, charged like REST search) to read candidates. df_get_schema (free) lists field names. For a full pool, use df_start_download and df_download_status. Download result links are valid for 7 days.

Example prompt:

Using Datafiniti property data, find single-family homes in Charlotte, NC ZIP codes 28205 and 28209 with 3 to 4 bedrooms and a transaction sale date after May 18, 2026. Pull 20 of them. For each, take the latest sale with a price over $10,000 that isn't a quit claim or deed of trust, and compute price per square foot. Then list the six most similar to a 3-bed, 2-bath, 1,850 sq ft home built in 1998, and give me the median price per square foot. Don't include buyer or seller names.

What are the common gotchas?

  • Filter per transaction, not per record. transactions.price:* AND transactions.saleDate:[...] can match two different entries. Datafiniti's query docs put conditions for one sub-object inside curly brackets, as in { brokers.emails:* AND brokers.phones:* }; test that form on transactions before relying on it, and re-check in code either way.
  • Not every document is a sale. documentType includes values such as "Quit Claim", "Deed of Trust", "Loan Modification", and "Intrafamily Transfer And Dissolution". Exclude them, and drop very low prices.
  • Refinances live in the same list. The docs show transactions.type values such as "REFI". Skip them.
  • Property facts are current, not as of the sale. floorSizeValue and numBathroom describe the record now. A home renovated after it sold can look more valuable per square foot than it was.
  • Two kinds of sold price. transactions.price is the recorded sale. mostRecentSoldPriceAmount comes from listing prices. Use the transaction for comps and the listing price as a cross-check.
  • Some markets will be thin. Some states don't put sale prices in public records. Check num_found per market before you promise coverage.
  • Recent sales lag. Datafiniti's docs say transaction records typically arrive within 2 weeks after a property is marked sold, so the last few weeks will be incomplete.
  • Parenthesize OR groups. Write postalCode:(28205 OR 28209). Without parentheses, ANDs and ORs combine in ways you didn't intend.
  • Use statusHistory, not statuses. If you also check listing status, statuses is deprecated.

Should you build, license, or buy sales data?

CriterionCollect county records yourselfLicense a primary source (MLS/BBO feeds, county record vendors)Datafiniti Property Data
Suited toA few countiesMarkets where you hold a feed agreementMany markets from one API
Property factsYou match deeds to property recordsDepends on the feedTransactions and property facts on one record
Non-sale documentsYou classify every documentDepends on the feeddocumentType and transactions.type to filter on
Ongoing workPer-county collection and parsingContracts and per-feed integrationQuery upkeep and your own ranking
Choose it whenYour scope is a handful of countiesYou need contractual rights, MLS-only fields, or concessionsYou want recorded sales joined to property facts without running collection

Datafiniti isn't the right fit for every valuation job. A lending decision that requires an appraisal still needs a licensed appraiser. If you need MLS-only details such as seller concessions or days on market for every sale, a licensed MLS feed is the better source. And in markets where sale prices aren't public, any transaction-based comp set will be thin.

Frequently asked questions

What API can I use to get sold prices for comps?

Datafiniti Property Data. Search POST /v4/properties/search with a location plus transactions.price:* and a transactions.saleDate range, and read saleDate, price, and documentType from each record's transactions list.

How do I find homes that sold in the last six months?

Add a date range on transactions.saleDate, such as transactions.saleDate:[2026-05-18 TO *], to a location query. Compute the start date from today in your code.

How do I choose which comps are most similar?

Filter by propertyType and a numBedroom range in the query, then score candidates on square footage, bathrooms, yearBuilt, and distance. Keep the closest few and use the median price per square foot.

How fresh is the sales data?

Datafiniti's docs say homeowner contact details and transaction records are typically available within 2 weeks after a property is marked as sold.

Can I search for comps within a radius?

Yes. Datafiniti's query syntax supports geoLocation:[longitude,latitude,distance,unit], for example geoLocation:[-80.8052,35.2101,1,mi].

How much does it cost to pull comps?

Property searches charge credits per record returned, and nothing when 0 records are found. Size the query first with the free MCP tool df_count, then cap a download with num_records.

Pull your first comp set

Pull comps for one ZIP code with a free trial, or talk to us about volume and delivery.

Sources

Property data schema Find property comps from transaction data Find prices of sold properties Possible values for property fields Constructing property queries How credits work (API) Property Data API reference Search and downloads Get a download MCP server