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

# Category Trend Analysis

> Analyze trending Yelp categories in a local market to identify consumer trends and investment opportunities

## Scenario

What's trending in your local market? New açaí bowl shops opening? Bubble tea exploding? You search Yelp for recently opened businesses in trending categories, analyze their ratings and review velocity, then use Mave to identify consumer trends and predict where the market is heading.

**Flow:** Yelp `GET /businesses/search` (multiple trending categories) → Compare: new business counts, ratings, review velocity → Mavera `POST /mave/chat` → Consumer trend report

## Code

<CodeGroup>
  ```python Python theme={"dark"}
  import os, requests, time

  YELP = os.environ["YELP_API_KEY"]
  MV = os.environ["MAVERA_API_KEY"]
  YELP_H = {"Authorization": f"Bearer {YELP}"}
  MV_H = {"Authorization": f"Bearer {MV}", "Content-Type": "application/json"}

  LOCATION = "Austin, TX"
  CATEGORIES = [
      "bubbletea", "acaibowls", "juicebars", "poke",
      "korean", "ramen", "mediterranean", "vegan",
      "coffee", "cocktailbars", "breweries", "wine_bars",
  ]

  # 1. Search each category
  category_data = []
  for cat in CATEGORIES:
      r = requests.get(f"https://api.yelp.com/v3/businesses/search",
          headers=YELP_H,
          params={"categories": cat, "location": LOCATION, "limit": 50, "sort_by": "review_count"})
      if r.status_code == 429:
          time.sleep(2)
          continue
      r.raise_for_status()
      bizes = r.json().get("businesses", [])
      total = r.json().get("total", 0)

      if not bizes:
          continue

      avg_rating = sum(b.get("rating", 0) for b in bizes) / len(bizes)
      avg_reviews = sum(b.get("review_count", 0) for b in bizes) / len(bizes)
      high_rated = sum(1 for b in bizes if b.get("rating", 0) >= 4.5)
      price_dist = {}
      for b in bizes:
          p = b.get("price", "N/A")
          price_dist[p] = price_dist.get(p, 0) + 1

      category_data.append({
          "category": cat,
          "total_in_area": total,
          "sampled": len(bizes),
          "avg_rating": round(avg_rating, 1),
          "avg_review_count": round(avg_reviews),
          "high_rated_pct": round(high_rated / len(bizes) * 100) if bizes else 0,
          "price_distribution": price_dist,
          "top_3": [b["name"] for b in sorted(bizes, key=lambda x: -x.get("review_count", 0))[:3]],
      })
      time.sleep(0.5)

  # 2. Mave trend analysis
  cat_block = "\n".join(
      f"- {d['category']}: {d['total_in_area']} total, avg {d['avg_rating']}/5, "
      f"avg {d['avg_review_count']} reviews, {d['high_rated_pct']}% rated 4.5+. "
      f"Top: {', '.join(d['top_3'])}"
      for d in sorted(category_data, key=lambda x: -x["total_in_area"])
  )

  analysis = requests.post("https://app.mavera.io/api/v1/mave/chat",
      headers=MV_H,
      json={"message": f"""Analyze category trends in {LOCATION} from Yelp data.

  {cat_block}

  Produce:
  1. Emerging trends (categories with high ratings but low total count — growth signal)
  2. Saturated categories (high count, declining quality — mature market)
  3. Consumer behavior shifts (what do category patterns tell us about local preferences?)
  4. Investment opportunities (where should a new business or product launch?)
  5. Seasonal or demographic factors driving these trends"""}).json()

  print(f"=== Category Trends in {LOCATION} ===")
  print(analysis.get("content", "")[:1500])
  ```

  ```javascript JavaScript theme={"dark"}
  const YELP = process.env.YELP_API_KEY;
  const MV = process.env.MAVERA_API_KEY;
  const YELP_H = { Authorization: `Bearer ${YELP}` };
  const MV_H = { Authorization: `Bearer ${MV}`, "Content-Type": "application/json" };

  const LOCATION = "Austin, TX";
  const CATEGORIES = ["bubbletea", "acaibowls", "poke", "korean", "ramen", "vegan", "coffee", "cocktailbars"];

  const categoryData = [];
  for (const cat of CATEGORIES) {
    const params = new URLSearchParams({ categories: cat, location: LOCATION, limit: "50", sort_by: "review_count" });
    const res = await fetch(`https://api.yelp.com/v3/businesses/search?${params}`, { headers: YELP_H });
    if (res.status === 429) { await new Promise((r) => setTimeout(r, 2000)); continue; }
    const data = await res.json();
    const bizes = data.businesses || [];
    if (!bizes.length) continue;

    const avgRating = +(bizes.reduce((s, b) => s + (b.rating || 0), 0) / bizes.length).toFixed(1);
    const avgReviews = Math.round(bizes.reduce((s, b) => s + (b.review_count || 0), 0) / bizes.length);
    const highRated = Math.round(bizes.filter((b) => (b.rating || 0) >= 4.5).length / bizes.length * 100);
    const top3 = bizes.sort((a, b) => (b.review_count || 0) - (a.review_count || 0)).slice(0, 3).map((b) => b.name);

    categoryData.push({ category: cat, total: data.total || 0, avgRating, avgReviews, highRated, top3 });
    await new Promise((r) => setTimeout(r, 500));
  }

  const catBlock = categoryData
    .sort((a, b) => b.total - a.total)
    .map((d) => `- ${d.category}: ${d.total} total, avg ${d.avgRating}/5, ${d.avgReviews} reviews, ${d.highRated}% 4.5+. Top: ${d.top3.join(", ")}`)
    .join("\n");

  const analysis = await fetch("https://app.mavera.io/api/v1/mave/chat", {
    method: "POST", headers: MV_H,
    body: JSON.stringify({
      message: `Category trends in ${LOCATION}:\n\n${catBlock}\n\nProduce: 1) Emerging trends 2) Saturated categories 3) Consumer shifts 4) Investment opportunities 5) Drivers`,
    }),
  }).then((r) => r.json());

  console.log(`=== Trends in ${LOCATION} ===`);
  console.log((analysis.content || "").slice(0, 1500));
  ```
</CodeGroup>

## Example Output

```text theme={"dark"}
=== Category Trends in Austin, TX ===

## Emerging Trends (high quality, low count — growth phase)
- **Poke** (23 total, avg 4.4/5, 78% rated 4.5+): Strong quality signal.
  Early movers doing well. Room for 10+ more locations.
- **Korean** (31 total, avg 4.3/5): Korean BBQ and fried chicken
  trending with younger demographics. K-culture tailwind.

## Saturated Categories
- **Coffee** (183 total, avg 4.0/5): Mature. New entrants need strong
  differentiation. Quality declining as volume increases.
- **Cocktail bars** (120 total, avg 3.9/5): Oversupplied. Average
  ratings declining — sign of a mature market.

## Consumer Behavior Shifts
- Health-forward categories (acai, juice bars, poke) growing fastest
- Asian fusion (Korean, ramen, poke) replacing traditional American
- Bubble tea velocity suggests Gen Z influence on market

## Investment Opportunities
1. Korean fried chicken (high demand, few operators)
2. Poke + açaí combo concept (health-forward, underserved in South Austin)
3. Vegan cocktail bar (two trends in one, zero operators)
```

## Error Handling

<AccordionGroup>
  <Accordion title="Category aliases">Yelp uses specific category aliases (e.g., `bubbletea` not `bubble_tea`). Find valid aliases at [Yelp Category List](https://www.yelp.com/developers/documentation/v3/all_category_list).</Accordion>
  <Accordion title="Total count vs sampled">The `total` field in search results may be large, but you can only paginate to 1,000 results. Use `total` for market size, `sampled` for analysis.</Accordion>
</AccordionGroup>
