Skip to main content

Overview

The Statistics API provides comprehensive analytics for accounts and alerts, including mention counts, reach, sentiment distribution, and source breakdown. Statistics can be grouped by hour, day, week, or month.

Methods

Get Stats

Fetch statistics for an account or alert with flexible time period configuration.
from mention import StatsPeriod

client.get_stats(
    account_id: str,
    alert_id: str | None = None,
    *,
    from_date: datetime | str | None = None,
    to_date: datetime | str | None = None,
    period: StatsPeriod = StatsPeriod.DAY
) -> StatsResponse
account_id
string
required
The account ID
alert_id
string
The alert ID (optional - if None, returns account-level stats)
from_date
datetime | string
Start date for statistics period (ISO 8601 format)
to_date
datetime | string
End date for statistics period (ISO 8601 format)
period
StatsPeriod
default:"day"
Time grouping period (hour, day, week, month)
Returns: StatsResponse containing detailed statistics and breakdowns Example:
from mention import MentionClient, StatsPeriod
from datetime import datetime, timedelta

client = MentionClient(access_token="your-token")

# Get last 30 days of stats grouped by day
to_date = datetime.now()
from_date = to_date - timedelta(days=30)

stats = client.get_stats(
    "acc_123456",
    "alert_123",
    from_date=from_date,
    to_date=to_date,
    period=StatsPeriod.DAY
)

print(f"Total mentions: {stats.total_mentions}")
print(f"Total reach: {stats.total_reach:,}")

print("\nSentiment Distribution:")
for sentiment, count in stats.sentiment_distribution.items():
    print(f"  {sentiment}: {count}")

print("\nSource Distribution:")
for source, count in stats.sources_distribution.items():
    print(f"  {source}: {count}")

print("\nDaily Breakdown:")
for data in stats.data:
    print(f"  {data.period}: {data.mentions_count} mentions, {data.reach:,} reach")
Response:
{
  "account_id": "acc_123456",
  "alert_id": "alert_123",
  "period": "day",
  "from_date": "2024-01-01T00:00:00Z",
  "to_date": "2024-01-30T23:59:59Z",
  "total_mentions": 1523,
  "total_reach": 2500000,
  "sentiment_distribution": {
    "positive": 892,
    "neutral": 456,
    "negative": 175
  },
  "sources_distribution": {
    "twitter": 650,
    "news": 320,
    "blog": 280,
    "reddit": 150,
    "facebook": 123
  },
  "data": [
    {
      "period": "2024-01-01",
      "mentions_count": 45,
      "reach": 75000,
      "sentiment_positive": 28,
      "sentiment_neutral": 12,
      "sentiment_negative": 5,
      "sources": [
        {
          "source": "twitter",
          "mentions_count": 25,
          "reach": 50000,
          "sentiment_positive": 15,
          "sentiment_neutral": 8,
          "sentiment_negative": 2
        },
        {
          "source": "news",
          "mentions_count": 20,
          "reach": 25000,
          "sentiment_positive": 13,
          "sentiment_neutral": 4,
          "sentiment_negative": 3
        }
      ]
    }
  ]
}

Period Grouping

Hour

StatsPeriod.HOUR Group statistics by hour - useful for real-time monitoring and recent activity:
Sync
from mention import StatsPeriod
from datetime import datetime, timedelta

# Last 24 hours by hour
stats = client.get_stats(
    "acc_123456",
    "alert_123",
    from_date=datetime.now() - timedelta(hours=24),
    to_date=datetime.now(),
    period=StatsPeriod.HOUR
)

for data in stats.data:
    print(f"{data.period}: {data.mentions_count} mentions")

Day

StatsPeriod.DAY (default) Group statistics by day - ideal for trend analysis:
Sync
# Last 30 days by day
stats = client.get_stats(
    "acc_123456",
    "alert_123",
    from_date=datetime.now() - timedelta(days=30),
    period=StatsPeriod.DAY
)

Week

StatsPeriod.WEEK Group statistics by week - good for longer-term trends:
Sync
# Last 12 weeks by week
stats = client.get_stats(
    "acc_123456",
    "alert_123",
    from_date=datetime.now() - timedelta(weeks=12),
    period=StatsPeriod.WEEK
)

Month

StatsPeriod.MONTH Group statistics by month - for annual reports:
Sync
# Last 12 months by month
stats = client.get_stats(
    "acc_123456",
    "alert_123",
    from_date=datetime.now() - timedelta(days=365),
    period=StatsPeriod.MONTH
)

Account-Level Stats

Get aggregated statistics for all alerts in an account:
Sync
# Don't specify alert_id for account-level stats
account_stats = client.get_stats(
    "acc_123456",
    from_date=datetime.now() - timedelta(days=30),
    period=StatsPeriod.DAY
)

print(f"Account total mentions: {account_stats.total_mentions}")
print(f"Account total reach: {account_stats.total_reach:,}")

Use Cases

Sentiment Analysis

Analyze sentiment trends over time:
Sync
from mention import StatsPeriod
from datetime import datetime, timedelta

stats = client.get_stats(
    "acc_123456",
    "alert_123",
    from_date=datetime.now() - timedelta(days=30),
    period=StatsPeriod.DAY
)

# Calculate sentiment percentages
total = stats.total_mentions
if total > 0:
    positive_pct = (stats.sentiment_distribution.get('positive', 0) / total) * 100
    negative_pct = (stats.sentiment_distribution.get('negative', 0) / total) * 100
    neutral_pct = (stats.sentiment_distribution.get('neutral', 0) / total) * 100
    
    print(f"Sentiment Breakdown:")
    print(f"  Positive: {positive_pct:.1f}%")
    print(f"  Neutral: {neutral_pct:.1f}%")
    print(f"  Negative: {negative_pct:.1f}%")

Source Performance

Compare performance across different sources:
Sync
stats = client.get_stats(
    "acc_123456",
    "alert_123",
    from_date=datetime.now() - timedelta(days=30),
    period=StatsPeriod.DAY
)

print("Source Performance:")
for source, count in sorted(
    stats.sources_distribution.items(),
    key=lambda x: x[1],
    reverse=True
):
    percentage = (count / stats.total_mentions) * 100
    print(f"  {source}: {count} mentions ({percentage:.1f}%)")

Trend Detection

Identify trends and spikes in mentions:
Sync
import statistics

stats = client.get_stats(
    "acc_123456",
    "alert_123",
    from_date=datetime.now() - timedelta(days=30),
    period=StatsPeriod.DAY
)

daily_counts = [d.mentions_count for d in stats.data]
avg = statistics.mean(daily_counts)
stdev = statistics.stdev(daily_counts) if len(daily_counts) > 1 else 0

print(f"Average mentions per day: {avg:.1f}")
print(f"Standard deviation: {stdev:.1f}")

print("\nSpikes detected:")
for data in stats.data:
    if data.mentions_count > avg + (2 * stdev):
        print(f"  {data.period}: {data.mentions_count} mentions (spike!)")

Models

StatsResponse

Response containing comprehensive statistics.
FieldTypeDescription
account_idstringAccount ID
alert_idstringAlert ID (if alert-specific)
periodstringTime period grouping
from_datestringStart date
to_datestringEnd date
datalist[StatsData]Time-series data
total_mentionsintegerTotal mentions in period
total_reachintegerTotal reach
sentiment_distributiondictSentiment counts
sources_distributiondictSource counts

StatsData

Statistics data for a specific time period.
FieldTypeDescription
periodstringPeriod identifier (date/time)
mentions_countintegerMentions in this period
reachintegerReach in this period
sentiment_positiveintegerPositive mentions
sentiment_negativeintegerNegative mentions
sentiment_neutralintegerNeutral mentions
sourceslist[SourceStats]Per-source breakdown

SourceStats

Statistics for a specific source.
FieldTypeDescription
sourcestringSource name
mentions_countintegerMentions from this source
reachintegerReach from this source
sentiment_positiveintegerPositive mentions
sentiment_negativeintegerNegative mentions
sentiment_neutralintegerNeutral mentions

StatsPeriod

Time period enumeration:
  • HOUR: Hourly grouping
  • DAY: Daily grouping
  • WEEK: Weekly grouping
  • MONTH: Monthly grouping

Build docs developers (and LLMs) love