Skip to main content

Overview

Trends show what topics are currently popular on Twitter. You can retrieve global trends, location-specific trends, and categorized trends (news, sports, entertainment). This is useful for content discovery, monitoring viral topics, or analyzing social media trends.

Trend Class

Represents a trending topic on Twitter.

Attributes

name
str
The name of the trending topic or hashtag.
tweets_count
int | None
The number of tweets associated with this trend (may be None).
domain_context
str
The context or domain associated with the trend (e.g., “Politics”, “Sports”).
A list of related trend names grouped under this main trend.

PlaceTrend Class

Represents a trend for a specific geographic location.

Attributes

name
str
The name of the trend.
url
str
The URL to view this trend on Twitter.
query
str
The search query string for this trend.
tweet_volume
int
The volume of tweets about this trend.
promoted_content
None
Whether this is promoted content (always None for organic trends).

Location Class

Represents a geographic location where trends are available.

Attributes

woeid
int
The Yahoo! Where On Earth ID for this location.
name
str
The name of the location (e.g., “New York”, “London”).
country
str
The country name.
country_code
str
The two-letter country code (e.g., “US”, “GB”).
parentid
int
The WOEID of the parent location.
placeType
dict
Information about the place type.
url
str
The URL for this location’s trends.

Methods

Retrieves trending topics for this location.
trends = await location.get_trends()
Returns: PlaceTrends - Dictionary containing trends and metadata.
Retrieve trending topics by category.
trends = await client.get_trends('trending')
category
str
required
The category of trends to retrieve:
  • 'trending' - General trending topics
  • 'for-you' - Personalized trends based on your interests
  • 'news' - News-related trends
  • 'sports' - Sports-related trends
  • 'entertainment' - Entertainment-related trends
count
int
default:"20"
The number of trends to retrieve.
retry
bool
default:"true"
If no trends are fetched, continuously retry until trends are retrieved.
additional_request_params
dict | None
Additional parameters to add to the API request. Often used as {'candidate_source': 'trends'} when the default doesn’t work.
Returns: list[Trend] - A list of Trend objects. Retrieve the top 50 trending topics for a specific location.
trends = await client.get_place_trends(woeid)
woeid
int
required
The Yahoo! Where On Earth ID of the location. Get available WOEIDs using get_available_locations().
Returns: PlaceTrends - Dictionary containing:
  • trends (list[PlaceTrend]): List of trending topics
  • as_of (str): Timestamp when trends were captured
  • created_at (str): When the trend data was created
  • locations (dict): Location information

Client.get_available_locations()

Retrieve all locations where trends are available.
locations = await client.get_available_locations()
Returns: list[Location] - A list of Location objects.

Usage Examples

# Get general trending topics
trends = await client.get_trends('trending', count=10)

print("Top 10 Trending Topics:")
for i, trend in enumerate(trends, 1):
    print(f"{i}. {trend.name}")
    if trend.domain_context:
        print(f"   Context: {trend.domain_context}")
    if trend.grouped_trends:
        print(f"   Related: {', '.join(trend.grouped_trends[:3])}")
# Get all available locations
locations = await client.get_available_locations()

print(f"Found {len(locations)} locations with trends")

# Find specific location
ny_location = next((loc for loc in locations if loc.name == 'New York'), None)
if ny_location:
    print(f"New York WOEID: {ny_location.woeid}")
# Get tweets from a trending topic
trends = await client.get_trends('trending', count=10)

for trend in trends[:3]:  # Top 3 trends
    print(f"\nTrend: {trend.name}")
    
    # Search for tweets about this trend
    tweets = await client.search_tweet(trend.name, 'Latest', count=20)
    
    print(f"Found {len(tweets)} recent tweets")
    for tweet in tweets[:5]:
        print(f"  @{tweet.user.screen_name}: {tweet.text[:60]}...")
import asyncio
from datetime import datetime

async def track_trends(duration_minutes=60, interval_minutes=5):
    """Track how trends change over time."""
    trend_history = []
    iterations = duration_minutes // interval_minutes
    
    for i in range(iterations):
        timestamp = datetime.now()
        trends = await client.get_trends('trending', count=10)
        
        trend_names = [t.name for t in trends]
        trend_history.append({
            'timestamp': timestamp,
            'trends': trend_names
        })
        
        print(f"[{timestamp}] Top trend: {trends[0].name}")
        
        if i < iterations - 1:
            await asyncio.sleep(interval_minutes * 60)
    
    return trend_history

# Track trends for 1 hour, checking every 5 minutes
history = await track_trends()

Finding Tweet Volume

# Get place trends (includes tweet volume)
trends = await client.get_place_trends(1)  # Worldwide

# Sort by tweet volume
sorted_trends = sorted(
    [t for t in trends['trends'] if t.tweet_volume],
    key=lambda x: x.tweet_volume,
    reverse=True
)

print("Trends by Tweet Volume:")
for i, trend in enumerate(sorted_trends[:10], 1):
    print(f"{i}. {trend.name} - {trend.tweet_volume:,} tweets")

Analyzing Trend Context

from collections import Counter

# Get trends and analyze their contexts
trends = await client.get_trends('trending', count=50)

# Count trends by domain context
contexts = [t.domain_context for t in trends if t.domain_context]
context_counts = Counter(contexts)

print("Trend Contexts:")
for context, count in context_counts.most_common():
    print(f"{context}: {count} trends")

# Find trends with grouped trends
trends_with_groups = [t for t in trends if t.grouped_trends]

print(f"\nTrends with related topics: {len(trends_with_groups)}")
for trend in trends_with_groups[:5]:
    print(f"\n{trend.name}")
    print(f"  Related: {', '.join(trend.grouped_trends)}")

Creating a Trend Dashboard

import json

async def create_trend_dashboard():
    """Create a comprehensive trend dashboard."""
    dashboard = {
        'timestamp': datetime.now().isoformat(),
        'categories': {}
    }
    
    categories = ['trending', 'news', 'sports', 'entertainment']
    
    for category in categories:
        trends = await client.get_trends(category, count=10)
        dashboard['categories'][category] = [
            {
                'name': t.name,
                'context': t.domain_context,
                'related': t.grouped_trends
            }
            for t in trends
        ]
    
    # Save to file
    with open('trend_dashboard.json', 'w', encoding='utf-8') as f:
        json.dump(dashboard, f, indent=2, ensure_ascii=False)
    
    print("Dashboard created: trend_dashboard.json")
    return dashboard

dashboard = await create_trend_dashboard()

Notes

The 'for-you' category returns personalized trends based on your account’s interests and activity.
WOEIDs (Where On Earth IDs) are Yahoo’s geographic identifiers. WOEID 1 represents worldwide trends.
Not all trends include tweet volume counts. This data is often available for place trends but not for category trends.
Trends can change rapidly. The retry parameter helps handle cases where the API temporarily returns empty results.
Rate limits apply to trend endpoints. Avoid making too many requests in a short time period.

Common WOEIDs

LocationWOEID
Worldwide1
United States23424977
United Kingdom23424975
New York2459115
London44418
Tokyo1118370
Paris615702
Los Angeles2442047

Build docs developers (and LLMs) love