TypeScript 中的 Redfin 税務資料:將歷史記錄與預測分開
Redfin tax data in TypeScript: keep history separate from forecasts
Redfin 的 TypeScript 資料處理應把已觀察到的税務資料與購置後的税項預測分開,因為 taxAnnualAmount 和 taxYear 只概括最新提供的税務記錄,並非購置後的税單。缺少税項資料應保留為未知,不可當作零;taxHistory 則應保留原始內容,避免猜測未確立的欄位名稱。重新載入資料只代表最近觀察到頁面資訊,不代表税務年度已更新。
Your rental shortlist can look profitable because its tax number answers the wrong question.
You're comparing potential purchases, and the annual cash flow calculation needs an expense. There's taxAnnualAmount, sitting beside the listing price. Convenient fields make very persuasive assumptions.
taxAnnualAmount and taxYear summarize the latest exposed tax row, not the tax bill after your purchase. Keep that observation. Give the acquisition forecast a separate place to live.
Fetch the evidence before scoring the property
For an acquisition screen, you want properties offered for sale. Searching rental listings answers a different question: what landlords are asking tenants to pay.
This Example input requests the detail enrichment needed for the evidence branch:
import { ApifyClient } from 'apify-client';
import { z } from 'zod';
const run_input = z.object({
mode: z.literal('forSale'),
location: z.string().min(1),
maxItems: z.number().int().min(1).max(20000),
includeDetails: z.literal(true),
}).parse({
mode: 'forSale',
location: 'Austin, TX',
maxItems: 20,
includeDetails: true,
});
const client = new ApifyClient({
token: process.env.APIFY_TOKEN,
});
The Actor calls a cookieless detail endpoint rather than depending on the public HTML property page, which challenges cookieless clients. Enrichment adds one request per emitted listing.
That trade-off belongs in your collection design. A broad discovery pull and a focused underwriting pull don't need identical enrichment budgets.
Wait for the collection to finish before accepting its rows into this screen:
const run = await client
.actor('nimbryxo-studio/redfin-sale-rental-and-sold-listings-scraper')
.call(run_input);
if (run.status !== 'SUCCEEDED') {
throw new Error(`Collection needs review: ${run.status}`);
}
const { items } = await client
.dataset(run.defaultDatasetId)
.listItems();
This gate prevents a failed collection from quietly becoming your acquisition shortlist. It doesn't certify that the available evidence is complete.
Why a successful pull can still leave gaps
Location lookup starts with autocomplete, retries through a connection fallback, then uses verified regions when necessary. An unknown city can require a state-level search followed by city matching.
The Actor checks returned homes against the requested location. Wrong-area homes are dropped rather than emitted, and fallback problems appear in the run status.
That protects geographic relevance. It can't turn a source timeout or an empty deep page into proof that no other candidates exist.
Treat the collection boundary and the underwriting boundary separately. Before comparing shortlist sizes across pulls, inspect location resolution and collection status. A smaller shortlist isn't automatically a thinner market.
Property identity has another boundary: the Actor deduplicates by property ID. Your ingestion job still needs its own policy across repeated runs.
For evidence storage, preserve snapshots under the run identity and property identity. For a current shortlist, select the observation you intend to use explicitly. Dataset position is a poor replacement for either decision.
Keep the amount attached to its year
The source doesn't expose every detail for every property. Empty fields are omitted, so enabling enrichment doesn't make every tax observation usable.
Missing taxes must remain unknown. Converting absence into zero quietly rewards the least complete listing.
The parser below accepts plain numbers or decimal strings for tax summaries. Other encodings go to review. These are consumer acceptance rules, not assumptions about every source record.
It also keeps taxHistory opaque. The yearly rows describe taxes due, land value, and improvement value, but their nested key names aren't established here. Guessing those names would manufacture a schema.
Validate the fields you can interpret and preserve the original item alongside them:
const decimal = z.union([
z.number(),
z.string().regex(/^\d+(?:\.\d+)?$/).transform(Number),
]).pipe(z.number().finite().nonnegative());
const taxYearSchema = decimal.pipe(z.number().int().positive());
const Listing = z.object({
propertyId: z.string().min(1),
taxAnnualAmount: decimal.optional(),
taxYear: taxYearSchema.optional(),
taxHistory: z.unknown().optional(),
apn: z.string().min(1).optional(),
county: z.string().min(1).optional(),
countyUrl: z.string().min(1).optional(),
state: z.string().min(1).optional(),
scrapedAt: z.string().datetime({ offset: true }),
});
const evidence = items.map((source) => {
const parsed = Listing.safeParse(source);
if (!parsed.success) {
return {
kind: 'review' as const,
source,
issues: parsed.error.issues,
};
}
const row = parsed.data;
return {
kind: 'accepted' as const,
source,
taxHistory: row.taxHistory,
observed: {
propertyId: row.propertyId,
amount: row.taxAnnualAmount,
taxYear: row.taxYear,
apn: row.apn,
county: row.county,
countyUrl: row.countyUrl,
state: row.state,
scrapedAt: row.scrapedAt,
},
};
});
type Observed = Extract<
(typeof evidence)[number],
{ kind: 'accepted' }
>['observed'];
A recent scrapedAt means you recently observed the page's data. It doesn't make an older tax year current.
That distinction matters when you rerun collection. Refreshing the evidence timestamp must never refresh the accounting period by accident.
Put acquisition taxes on a separate branch
Property-tax treatment after purchase depends on the jurisdiction, assessment rules, and applicable exemptions. The seller's circumstances may not survive your acquisition.
Taxes due, assessed values, and transaction prices also measure different things. Neither price nor soldPrice is automatically the assessment basis your model needs.
Keep the branches visible:
listing detail
├─ historical observation → year, amount, history, source snapshot
└─ parcel context → public-record review → acquisition assumptions
↓
rental cash flow
Use apn, county, and countyUrl to support a public-record cross-check. Scope parcel identifiers to their jurisdiction; an APN alone isn't a universal property key.
County context may also be insufficient to identify every taxing authority. Your reviewed policy needs to resolve that scope, including relevant exemptions and charges.
The following configuration belongs to your workflow. It accepts independently checked assumptions through an environment variable and defaults to an empty list rather than inventing a tax rate.
const Scenario = z.object({
label: z.string().min(1),
assessmentBasis: decimal,
exemptionDeduction: decimal,
annualRate: decimal,
annualFixedCharges: decimal,
});
const ScreenPolicy = z.object({
propertyId: z.string().min(1),
state: z.string().min(1),
county: z.string().min(1),
apn: z.string().min(1),
oldestAcceptedTaxYear: taxYearSchema,
annualRent: decimal,
annualOperatingCostsExcludingTax: decimal,
annualDebtService: decimal,
maxAnnualTaxSpread: decimal,
scenarios: z.array(Scenario).min(2),
});
const policyRows = z.array(ScreenPolicy).parse(
JSON.parse(process.env.RENTAL_SCREEN_INPUTS ?? '[]'),
);
const policies = new Map(
policyRows.map((policy) => [policy.propertyId, policy]),
);
if (policies.size !== policyRows.length) {
throw new Error('Duplicate acquisition inputs need review');
}
Here, annualRate is a decimal multiplier, not a percentage label. Keep a reference to the checked policy and its applicable period alongside your scenario inputs.
The calculation below is a deliberately narrow model: taxable basis after an exemption deduction, multiplied by an annual rate, plus fixed charges. Use it only where your jurisdiction review supports that arithmetic.
Where local rules require caps, phased changes, special assessments, or different exemption mechanics, replace the calculator. Don't squeeze the policy into a convenient interface.
Rank scenarios, then decide what needs review
Historical evidence and scenario assumptions should meet at a review gate.
A stale year needs attention. Conflicting parcel context needs attention. A shortlist whose economics swing materially across your tax assumptions also needs attention.
Those are workflow rules you choose. They aren't guarantees supplied by the Actor.
This function calculates annual cash flow while keeping those reasons attached:
type ScenarioResult = {
label: string;
annualTax: number;
annualCashFlow: number;
};
type ScreenResult =
| {
status: 'review';
propertyId: string;
reasons: string[];
scenarios?: ScenarioResult[];
}
| {
status: 'rankable';
propertyId: string;
scenarios: ScenarioResult[];
worstAnnualCashFlow: number;
};
function screen(observed: Observed): ScreenResult {
const propertyId = observed.propertyId;
const policy = policies.get(propertyId);
if (!policy) {
return {
status: 'review',
propertyId,
reasons: ['Checked acquisition inputs are missing'],
};
}
const reasons: string[] = [];
if (observed.amount === undefined || observed.taxYear === undefined) {
reasons.push('Historical tax amount or year is missing');
} else if (observed.taxYear < policy.oldestAcceptedTaxYear) {
reasons.push('Historical tax year needs a freshness review');
}
if (
observed.state !== policy.state ||
observed.county !== policy.county ||
observed.apn !== policy.apn
) {
reasons.push('Parcel context is missing or conflicts');
}
const scenarios = policy.scenarios.map((scenario) => {
const taxableBasis = Math.max(
0,
scenario.assessmentBasis - scenario.exemptionDeduction,
);
const annualTax =
taxableBasis * scenario.annualRate + scenario.annualFixedCharges;
return {
label: scenario.label,
annualTax,
annualCashFlow:
policy.annualRent -
policy.annualOperatingCostsExcludingTax -
policy.annualDebtService -
annualTax,
};
});
const taxes = scenarios.map((scenario) => scenario.annualTax);
const spread = Math.max(...taxes) - Math.min(...taxes);
if (spread > policy.maxAnnualTaxSpread) {
reasons.push('Tax scenario sensitivity exceeds your review threshold');
}
if (reasons.length) {
return { status: 'review', propertyId, reasons, scenarios };
}
return {
status: 'rankable',
propertyId,
scenarios,
worstAnnualCashFlow: Math.min(
...scenarios.map((scenario) => scenario.annualCashFlow),
),
};
}
The parcel comparison is intentionally strict. Formatting differences can trigger review too. Resolve aliases through a checked jurisdiction mapping rather than stripping punctuation until identifiers happen to match.
Notice what the historical amount does here: it establishes whether usable evidence exists. It never enters the acquisition expense formula.
What breaks when history becomes a forecast
The Redfin Sale, Rental & Sold Listings Scraper supplies the evidence branch.
The consumer owns the meaning assigned to it. These shortcuts break that boundary:
| Consumer shortcut | Consequence in your rental screen |
|---|---|
| Subtract the historical amount as the acquisition expense | Ownership assumptions disappear inside an apparently factual number |
| Replace absent tax data with zero | Incomplete properties gain artificial cash flow |
| Treat assessed value as purchase price | Your scenario uses a valuation basis you haven't justified |
| Rank directly in source order | Search relevance becomes an investment preference |
| Overwrite each previous observation | You lose the evidence needed to explain a changed ranking |
A jump in tax history can justify investigation. It doesn't establish why the amount changed.
Likewise, a narrow scenario spread only describes the assumptions you supplied. It can't prove that those assumptions cover the relevant policy.
Build the shortlist from eligible scenario results, and keep everything else available for review:
const screened = evidence.flatMap((entry) =>
entry.kind === 'accepted' ? [screen(entry.observed)] : [],
);
const ranked = screened
.filter(
(result): result is Extract<ScreenResult, { status: 'rankable' }> =>
result.status === 'rankable',
)
.sort(
(left, right) =>
right.worstAnnualCashFlow - left.worstAnnualCashFlow ||
left.propertyId.localeCompare(right.propertyId),
);
const reviewQueue = {
sourceRows: evidence.filter((entry) => entry.kind === 'review'),
underwriting: screened.filter((result) => result.status === 'review'),
};
This ranking answers a specific question: which eligible property has the strongest annual cash flow under its least favorable supplied tax scenario?
It doesn't answer which property is the best investment. Acquisition costs, repairs, financing risk, vacancy assumptions, and your own constraints still belong in that decision.
With no checked acquisition inputs, the code produces review work instead of confident rankings. An empty shortlist can be an honest result.
Before the shortlist leaves your terminal
- Keep the source snapshot, scrape timestamp, and tax year together.
- Cross-check parcel context within the relevant jurisdiction.
- Record the policy reference behind every acquisition scenario.
- Review stale evidence and material sensitivity before ranking.
- Label historical observations and modeled expenses separately in exports.
The tax figure should earn its place in your model, not inherit it from a convenient field name.
Drafted with AI assistance and reviewed for accuracy.
來源:DEV Community · dev.to