# Market stats by area

Source: https://help.ruuster.com/idx/guide-market-stats

> Get market numbers for any area, as a snapshot of the last 30 days or month by month, such as active listings, contracts, months of inventory and median prices, and show them with the date and the source.

Three endpoints answer market statistics for one area. Area pages and listing appointments use them
to answer the questions buyers and sellers ask, with numbers and a date, which is what search engines
and AI assistants quote.

| Endpoint | Answers |
|---|---|
| `GET /v1/market/snapshot` | Every metric for one rolling window ending now (7 to 365 days), with the window before it beside each |
| `GET /v1/market` | The monthly series, for trend charts |
| `GET /v1/market/metrics` | The catalog: each metric's definition and formula, and which of your boards supply it |

## A snapshot for a listing appointment

How many months of inventory are there for waterfront condos over $500,000 in a ZIP code, counting
contracts as they are signed rather than closings?

cURL:

```bash
curl -s -G "https://idx.ruuster.com/v1/market/snapshot" \
  --data-urlencode zip=30308 \
  --data-urlencode window=30 \
  --data-urlencode metrics=activeListings,wentUnderContract,closings12m,monthsOfInventory,monthsOfInventoryMls \
  -H "Authorization: Bearer $IDX_SECRET_KEY"
```

TypeScript:

```typescript
import { createClient } from "@ruuster/idx";

const idx = createClient({ secretKey: process.env.IDX_SECRET_KEY });

const r = await idx.market.snapshot({
  zip: "30308",
  window: 30,
  metrics: ["activeListings", "wentUnderContract", "closings12m", "monthsOfInventory", "monthsOfInventoryMls"],
});
if (!r.ok) throw new Error(`${r.error.code}: ${r.error.message}`);
console.log(r.data);
```

Python:

```python
import os

import requests

res = requests.get(
    "https://idx.ruuster.com/v1/market/snapshot",
    params={
        "zip": "30308",
        "window": "30",
        "metrics": "activeListings,wentUnderContract,closings12m,monthsOfInventory,monthsOfInventoryMls",
    },
    headers={"Authorization": "Bearer " + os.environ["IDX_SECRET_KEY"]},
    timeout=30,
)
body = res.json()
if not body["ok"]:
    raise RuntimeError(body["error"]["code"] + ": " + body["error"]["message"])
print(body["data"])
```

PHP:

```php
<?php

$query = http_build_query([
    'zip' => '30308',
    'window' => '30',
    'metrics' => 'activeListings,wentUnderContract,closings12m,monthsOfInventory,monthsOfInventoryMls',
], '', '&', PHP_QUERY_RFC3986);
$ch = curl_init('https://idx.ruuster.com/v1/market/snapshot' . '?' . $query);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('IDX_SECRET_KEY')],
    CURLOPT_TIMEOUT => 30,
]);
$body = json_decode(curl_exec($ch), true);
curl_close($ch);
if (!$body['ok']) {
    throw new RuntimeException($body['error']['code'] . ': ' . $body['error']['message']);
}
print_r($body['data']);
```

Each metric in `data.metrics` has `current`, `prior` (the window before) and `yearAgo`, each with
`value`, `average` (price and time metrics), `share` (where a metric has one), `count` (the listings
behind it) and `breakdown` (price bands, mix by type or bedrooms, over, at and under list). `boards`,
`partial` and `partialReason` say which of your boards fed it. `prior` and `yearAgo` are null, with
their reason, where the index can't answer: it holds each listing's current status only, and about
12 months of history.

## Months of inventory: two formulas

| Name | Formula | Use it for |
|---|---|---|
| `monthsOfInventory` | Active listings now / listings that went under contract in the last 30 days | The market right now: contracts lead closings by a month or two |
| `monthsOfInventoryMls` | Active listings now / (closings in the last 12 months / 12) | Comparing with MLS reports, which print this one |
| `monthsOfSupply` (`/v1/market` only) | Active listings now / average monthly closings of the last 3 whole months | The monthly series' own number |

`marketType` reads the real-time number when there is one, else the MLS-style one, and `basis` says
which: a seller's market under 3 months, balanced from 3 to 6, a buyer's market over 6. Every answer
names these formulas in `data.definitions`; say which one you quote.

**Went under contract** counts the listings whose contract date falls in the window, whatever their
status now: still pending, still active under contract, or already closed. The contract date is the
first one present of the purchase contract date, the pending date and the contract status change
date. A board whose listings of one status rarely carry a contract date is left out of that status,
and the answer names it in `partialReason`; the real-time months of inventory leaves such a board out
entirely, so its contracts never look short.

## Filters and breakdowns

Both market endpoints take the same filters beside the one location:

| Filter | What it does |
|---|---|
| `subdivision` | A subdivision or building, exact, as the MLS spells it (repeat for several) |
| `mlsArea` | The board's own area code (repeat for several) |
| `mls` | Only some of your boards; a board that isn't yours is 400 |
| `priceMin`, `priceMax` | Asking price for sale, sold price once closed |
| `bedsMin`, `bedsMax`, `bathsMin`, `bathsMax` | Bedrooms and bathrooms |
| `sqftMin`, `sqftMax`, `lotAcresMin`, `lotAcresMax` | Living area and lot size |
| `yearMin`, `yearMax` | Year built |
| `waterfront`, `newConstruction` | `true` for only those, `false` to leave them out |
| `type`, `subtype` | Property type, as in search |
| `listingType` | `sale` (the default) or `lease`; sales and leases never share a number |

`groupBy` splits every metric by one dimension: `zip`, `city`, `subdivision`, `type`, `beds` or
`priceBand`, at most 50 groups, largest first. A home listed on two of your boards counts once in
every count. Any median, average, sum or ratio over fewer than 3 listings is null, in a group as
anywhere, so a small group never shows one home's price.

## The monthly series

`GET /v1/market` answers the same area month by month. Send exactly one location, in any of the
forms search takes: a `where` object from suggest, a `boundariesId`, `zip`, `city` and `state`
together, a `bbox`, a `polygon`, `near` with `radiusMiles`, or a saved `shape`. Add the filters above,
and `months` (1 to 24, default 12) for the length of the history.

## Ask for one area

Send exactly one location, in any of the forms search takes: a `where` object from suggest, a
`boundariesId`, `zip`, `city` and `state` together, a `bbox`, a `polygon` or a saved `shape`. Add
`type` or `subtype` to narrow to one kind of home, and `months` (1 to 24, default 12) for the length
of the history.

cURL:

```bash
curl -s -G "https://idx.ruuster.com/v1/market" \
  --data-urlencode zip=30308 \
  --data-urlencode months=12 \
  -H "Authorization: Bearer $IDX_SECRET_KEY"
```

TypeScript:

```typescript
import { createClient } from "@ruuster/idx";

const idx = createClient({ secretKey: process.env.IDX_SECRET_KEY });

const r = await idx.market({
  zip: "30308",
  months: 12,
});
if (!r.ok) throw new Error(`${r.error.code}: ${r.error.message}`);
console.log(r.data);
```

Python:

```python
import os

import requests

res = requests.get(
    "https://idx.ruuster.com/v1/market",
    params={
        "zip": "30308",
        "months": "12",
    },
    headers={"Authorization": "Bearer " + os.environ["IDX_SECRET_KEY"]},
    timeout=30,
)
body = res.json()
if not body["ok"]:
    raise RuntimeError(body["error"]["code"] + ": " + body["error"]["message"])
print(body["data"])
```

PHP:

```php
<?php

$query = http_build_query([
    'zip' => '30308',
    'months' => '12',
], '', '&', PHP_QUERY_RFC3986);
$ch = curl_init('https://idx.ruuster.com/v1/market' . '?' . $query);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('IDX_SECRET_KEY')],
    CURLOPT_TIMEOUT => 30,
]);
$body = json_decode(curl_exec($ch), true);
curl_close($ch);
if (!$body['ok']) {
    throw new RuntimeException($body['error']['code'] . ': ' . $body['error']['message']);
}
print_r($body['data']);
```

## What comes back

`data.measures` holds one series per measure:

| Measure | What it is | Unit |
|---|---|---|
| `medianListPrice` | Median asking price of the homes for sale now | dollars |
| `medianSoldPrice` | Median sold price, by month | dollars |
| `medianPricePerSqft` | Median sold price per square foot, by month | dollars per square foot |
| `medianDaysOnMarket` | Median days from listing to sale, by month | days |
| `listToSaleRatio` | Each closing's own sold price divided by its own list price, then the median of those, by month (0.987 is 98.7%) | ratio |
| `activeInventory` | Homes for sale now | count |
| `newListings` | Homes listed, by month | count |
| `closings` | Homes sold, by month | count |
| `monthsOfSupply` | Homes for sale now divided by the average monthly sales of the last three whole months | months |
| `absorptionRate` | Average monthly sales of the last three whole months as a share of the homes for sale now | percent |
| `wentUnderContract` | Homes that went under contract, by contract month | count |
| `salesVolume` | The total of the sold prices, by month | dollars |
| `averageSoldPrice` | Average sold price, by month | dollars |
| `monthsOfInventory` | Real-time months of inventory, now | months |
| `monthsOfInventoryMls` | MLS-style months of inventory, now | months |

Each measure has:

- `current`: the latest month's value for sales measures, and the value today for the measures that
  describe what is for sale now. `currentCount` is how many listings it is based on.
- `series`: one point per month, oldest first, each `{ month, value, count }`. A median based on
  fewer than three listings has `value` null and keeps its `count`. A month before the sold history
  begins has `value` null and `count` 0.
- `boards`, `partial` and `partialReason`: how many of your boards fed the measure, whether that is
  fewer than all of them, and which were left out and why.

`data.location` gives the area's `label`, its `viewport` and its `boundary` outline when it has one.
`data.from`, `data.through` and `data.asOf` date the answer.

## Sold numbers and coverage

- Sold measures come only from boards that show sold data, within each board's sold window. On an
  area whose boards show no sold data, those measures are null. Hide those tiles; never show a zero.
- Sold history covers about the last twelve months. `data.coverage.soldFrom` is the first month with
  sold history, and `data.coverage.monthsWithoutHistory` says how many months of your period come
  before it. Their sold values are null.
- A board that hides a field, such as days on market, is left out of that one measure, and its
  `partial` is true.

## Showing the numbers

The examples repo builds the lead sentence and the four tiles of an area page from one call. It uses
`fmt.usd` for prices and `fmt.change(series, 12)` for the change from a year earlier, and returns null
for every number the boards don't show:

<p class="code-title"><code>content/answer.ts</code></p>

```ts
// The answer at the top of an area page: one sentence with today's numbers and the date, then the
// questions people ask about the area, each answered in its first sentence (plain market facts only).
import type { MarketData, MarketSeries } from "@ruuster/idx";
import { fmt, idx } from "@/lib/idx";
import type { Area, AreaQuestion } from "@/content/areas";

export type AreaAnswer = {
  /** The lead sentence: homes for sale, prices, days on market, the date. */
  lead: string;
  /** Market questions with their answers (a question whose number is missing is left out). */
  questions: AreaQuestion[];
  /** The date the numbers are from (ISO). */
  asOf: string;
};

const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

/** "2026-10" → "October 2026". */
export function monthName(month: string): string {
  const m = /^(\d{4})-(\d{2})$/.exec(month);
  if (!m) return month;
  return `${MONTHS[Number(m[2]) - 1] ?? m[2]} ${m[1]}`;
}

/** The latest month of a series that has a value, or null. */
export function latestPoint(s: MarketSeries | undefined): { month: string; value: number } | null {
  if (!s) return null;
  for (let i = s.series.length - 1; i >= 0; i--) {
    const p = s.series[i];
    if (p.value !== null) return { month: p.month, value: p.value };
  }
  return null;
}

/** Builds the answer from a GET /v1/market answer. Pure: the page passes the data in. */
export function answerFromMarket(market: MarketData, areaName: string): AreaAnswer {
  const m = market.measures;
  const updated = `Updated ${fmt.date(market.asOf)}.`;
  const sentences: string[] = [];

  const inventory = m.activeInventory?.current ?? null;
  const asking = m.medianListPrice?.current ?? null;
  if (inventory !== null && asking !== null) {
    sentences.push(`${areaName} has ${fmt.count(inventory)} ${inventory === 1 ? "home" : "homes"} for sale today, at a median asking price of ${fmt.usd(asking)}.`);
  } else if (inventory !== null) {
    sentences.push(`${areaName} has ${fmt.count(inventory)} ${inventory === 1 ? "home" : "homes"} for sale today.`);
  }

  const sold = latestPoint(m.medianSoldPrice);
  const ratio = m.listToSaleRatio?.current ?? null;
  const dom = m.medianDaysOnMarket?.current ?? null;
  if (sold) {
    let s = `Homes that sold in ${monthName(sold.month)} closed at a median of ${fmt.usd(sold.value)}`;
    if (ratio !== null) s += `, or ${(ratio * 100).toFixed(1)}% of asking`;
    if (dom !== null) s += `, after ${fmt.count(dom)} days on market`;
    sentences.push(`${s}.`);
  }
  sentences.push(updated);

  const questions: AreaQuestion[] = [];
  if (sold) {
    const change = fmt.change(m.medianSoldPrice, 12);
    const year = Number(sold.month.slice(0, 4)) - 1;
    const since = change ? ` That is a change of ${change} from ${monthName(`${year}${sold.month.slice(4)}`)}.` : "";
    questions.push({ question: `What is the median home price in ${areaName}?`, answer: `${fmt.usd(sold.value)} for homes sold in ${monthName(sold.month)}.${since}` });
  } else if (asking !== null) {
    questions.push({ question: `What is the median home price in ${areaName}?`, answer: `The median asking price of the homes for sale today is ${fmt.usd(asking)}.` });
  }
  const supply = m.monthsOfSupply?.current ?? null;
  if (dom !== null || supply !== null) {
    const parts: string[] = [];
    if (dom !== null && sold) parts.push(`The median home sold in ${fmt.count(dom)} days in ${monthName(sold.month)}.`);
    else if (dom !== null) parts.push(`The median home sold in ${fmt.count(dom)} days.`);
    if (supply !== null) parts.push(`At the current pace of sales, the homes for sale today would sell in ${fmt.count(supply)} months.`);
    questions.push({ question: `How fast are homes selling in ${areaName}?`, answer: parts.join(" ") });
  }
  const fresh = latestPoint(m.newListings);
  if (inventory !== null) {
    let a = `${fmt.count(inventory)} ${inventory === 1 ? "home is" : "homes are"} for sale today.`;
    if (fresh) a += ` ${fmt.count(fresh.value)} new ${fresh.value === 1 ? "listing" : "listings"} came on the market in ${monthName(fresh.month)}.`;
    questions.push({ question: `How many homes are for sale in ${areaName}?`, answer: a });
  }

  return { lead: sentences.join(" "), questions, asOf: market.asOf };
}

/** GET /v1/market for the area (13 months, so the change against a year earlier has both ends), then the answer. */
export async function areaAnswer(area: Area): Promise<{ answer: AreaAnswer; market: MarketData } | null> {
  const r = await idx.market({ where: area.where, months: 13 });
  if (!r.ok) return null;
  return { answer: answerFromMarket(r.data, area.name), market: r.data };
}
```

The `MarketStats` recipe component draws the tiles from `m.data.measures` and leaves out any measure
whose value is null.

## Writing rules for market numbers

- Show every line of `data.attribution` with the numbers, for example "Based on information from
  Stellar MLS for the period November 8, 2025 through November 8, 2026". Each board's rules ask for
  it.
- Always print the date the numbers are from (`data.asOf`).
- Say which months of inventory you show: real-time or MLS-style.
- Say what the number is: "median sold price in October", not "home values".
- Describe homes and places, never who lives there. [Fair housing](https://help.ruuster.com/idx/fair-housing)
  has the rules for area copy.

## Caching

Market answers to calls from your pages are cached at the edge for an hour, and the numbers change
slowly. On your server, re-render area pages with their listings (every few minutes) and fetch the
market numbers hourly or daily.
