> ## Documentation Index
> Fetch the complete documentation index at: https://docs.usequotable.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Weekly visibility trend

> Pull 90 days of daily visibility for a brand and turn it into weekly averages with week-over-week change and share of voice.

Daily scores move around. Weekly averages show the trend. This recipe reads 90 days of visibility for one brand, groups the days into weeks starting on Monday, and prints the average visibility score, mention rate and share of voice per week, with the change from the week before.

## What you need

| Requirement | Value |
| - | - |
| Scopes | `read:projects`, `read:visibility` |
| Endpoints | `GET /projects/{project_id}`, `GET /projects/{project_id}/visibility` |
| Environment | `QUOTABLE_API_KEY`, `QUOTABLE_PROJECT_ID` |
| Requests per run | 2 |

## How it works

1. `GET /projects/{project_id}` returns the brand's `brand_name`, the key its share of voice uses.
2. `GET /projects/{project_id}/visibility?from=…&to=…` returns one point per tracked day. A range can span up to 366 days, so 90 days is one request with no pagination.
3. The script averages each week's points. Weeks only include days that had a tracking run.

## Code

```javascript visibility-trend.mjs theme={"system"}
// Node.js 20+. Run: node visibility-trend.mjs
const API = "https://app.usequotable.com/api/v1";
const KEY = process.env.QUOTABLE_API_KEY;
const PROJECT_ID = process.env.QUOTABLE_PROJECT_ID;
const DAYS = 90;

async function get(path) {
  for (let attempt = 0; ; attempt++) {
    const res = await fetch(`${API}${path}`, {
      headers: { Authorization: `Bearer ${KEY}` },
    });
    if (res.status === 429 && attempt < 3) {
      const wait = Number(res.headers.get("retry-after") ?? "1");
      await new Promise((r) => setTimeout(r, wait * 1000));
      continue;
    }
    if (!res.ok) {
      const problem = await res.json().catch(() => ({}));
      throw new Error(`${res.status} ${problem.title ?? ""}: ${problem.detail ?? ""} (${problem.instance ?? "no request id"})`);
    }
    return res.json();
  }
}

const isoDay = (date) => date.toISOString().slice(0, 10);
const avg = (values) => values.reduce((sum, v) => sum + v, 0) / values.length;

function weekStart(day) {
  const date = new Date(`${day}T00:00:00Z`);
  const offset = (date.getUTCDay() + 6) % 7; // Monday = 0
  date.setUTCDate(date.getUTCDate() - offset);
  return isoDay(date);
}

const to = new Date();
const from = new Date(to.getTime() - (DAYS - 1) * 86_400_000);

const brand = await get(`/projects/${PROJECT_ID}`);
const series = await get(
  `/projects/${PROJECT_ID}/visibility?from=${isoDay(from)}&to=${isoDay(to)}`,
);

const weeks = new Map();
for (const point of series.data) {
  const key = weekStart(point.date);
  if (!weeks.has(key)) weeks.set(key, []);
  weeks.get(key).push(point);
}

console.log(`${brand.name} (${brand.domain}), ${series.from} to ${series.to}`);
console.log("Week of      Days  Score  Change  Mention rate  Share of voice");

let previous = null;
for (const [week, points] of [...weeks.entries()].sort()) {
  const score = avg(points.map((p) => p.score));
  const mentionRate = avg(points.map((p) => p.mention_rate));
  const sov = avg(points.map((p) => p.share_of_voice[brand.brand_name] ?? 0));
  const change = previous === null ? "" : (score - previous >= 0 ? "+" : "") + (score - previous).toFixed(1);
  console.log(
    `${week}   ${String(points.length).padStart(4)}  ${score.toFixed(1).padStart(5)}  ${change.padStart(6)}  ` +
      `${(mentionRate * 100).toFixed(0).padStart(11)}%  ${(sov * 100).toFixed(0).padStart(13)}%`,
  );
  previous = score;
}
```

```python visibility_trend.py theme={"system"}
# Python 3.10+, pip install requests. Run: python visibility_trend.py
import os
import time
from collections import defaultdict
from datetime import date, datetime, timedelta, timezone

import requests

API = "https://app.usequotable.com/api/v1"
PROJECT_ID = os.environ["QUOTABLE_PROJECT_ID"]
DAYS = 90

session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['QUOTABLE_API_KEY']}"

def get(path, params=None):
    for attempt in range(4):
        res = session.get(f"{API}{path}", params=params, timeout=30)
        if res.status_code == 429 and attempt < 3:
            time.sleep(int(res.headers.get("Retry-After", "1")))
            continue
        if not res.ok:
            problem = res.json() if res.content else {}
            raise RuntimeError(f"{res.status_code} {problem.get('title')}: {problem.get('detail')} ({problem.get('instance')})")
        return res.json()

def week_start(day: str) -> str:
    d = date.fromisoformat(day)
    return (d - timedelta(days=d.weekday())).isoformat()  # Monday

def avg(values):
    return sum(values) / len(values)

today = datetime.now(timezone.utc).date()
start = today - timedelta(days=DAYS - 1)

brand = get(f"/projects/{PROJECT_ID}")
series = get(
    f"/projects/{PROJECT_ID}/visibility",
    {"from": start.isoformat(), "to": today.isoformat()},
)

weeks = defaultdict(list)
for point in series["data"]:
    weeks[week_start(point["date"])].append(point)

print(f"{brand['name']} ({brand['domain']}), {series['from']} to {series['to']}")
print("Week of      Days  Score  Change  Mention rate  Share of voice")

previous = None
for week in sorted(weeks):
    points = weeks[week]
    score = avg([p["score"] for p in points])
    mention_rate = avg([p["mention_rate"] for p in points])
    sov = avg([p["share_of_voice"].get(brand["brand_name"], 0) for p in points])
    change = "" if previous is None else f"{score - previous:+.1f}"
    print(f"{week}   {len(points):>4}  {score:>5.1f}  {change:>6}  {mention_rate * 100:>11.0f}%  {sov * 100:>13.0f}%")
    previous = score
```

## Expected output

```text theme={"system"}
Acme Analytics (acme.com), 2026-07-04 to 2026-10-01
Week of      Days  Score  Change  Mention rate  Share of voice
2026-06-29      2   31.6                   47%             28%
2026-07-06      6   32.0    +0.4           47%             29%
2026-07-13      7   32.7    +0.7           48%             29%
2026-07-20      6   33.7    +1.0           49%             30%
…
2026-09-14      7   41.2    +1.1           58%             37%
2026-09-21      6   41.8    +0.6           59%             38%
2026-09-28      4   42.6    +0.7           60%             39%
```

The first and last weeks are partial, so compare full weeks when you report a trend.

## Variations

> [accordion] Compare against competitors
>
> `share_of_voice` holds every brand named in answers, not just yours. Sum each name's share across the period and sort to see who gained ground.

> [accordion] Run it on a schedule
>
> Instead of polling, subscribe an endpoint to `tracking.run.finalized` and re-run this script when the event arrives. See [Slack alerts from webhooks](https://docs.usequotable.com/guides/slack-alerts-from-webhooks.md).

> [accordion] Every brand at once
>
> Page through `GET /projects` and run the loop per brand. Each brand takes two requests, well inside the 300-per-minute [rate limit](https://docs.usequotable.com/api-reference/rate-limits.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.