This skill should be used when the user asks about Mixpanel product analytics, event data, funnel analysis, retention curves, cohort analysis, segmentation queries, user behavior, conversion rates, churn, DAU/MAU, ARPU, revenue metrics, feature adoption, A/B test results, user paths, flow analysis, or any request to query, explore, visualize, or analyze Mixpanel data using Python. Also use when the user asks to read, write, or manage Mixpanel "business context" — the markdown documentation that grounds AI assistants in an organization's structure and goals.
Analyze Mixpanel data by writing and executing Python code using the mixpanel_headless library and pandas.
Before running bundled helper scripts, set SKILL_DIR to the absolute path of this
skills/mixpanelyst directory.
import mixpanel_headless as mp
ws = mp.Workspace()
result = ws.query("Login", last=30)
print(result.df.head())
Query Engines
Question
Method
Returns
How much? How many? Trends?
ws.query()
QueryResult
Do users convert through a sequence?
ws.query_funnel()
FunnelQueryResult
Do users come back?
ws.query_retention()
RetentionQueryResult
What paths do users take?
ws.query_flow()
FlowQueryResult
Who are they? What do they look like?
ws.query_user()
UserQueryResult
All result types have a .df property returning a pandas DataFrame and a .params dict containing the bookmark JSON.
FlowQueryResult also has .graph (NetworkX DiGraph) and .anytree (list of tree roots).
Guessing event names causes silent empty results. Guessing API parameters causes TypeErrors and invalid queries. Discover both the data schema AND the API surface before writing any query.
Step 1: Discover the data schema
import mixpanel_headless as mp
from mixpanel_headless import Filter, GroupBy, Metric
ws = mp.Workspace()
# 1. Find real event names
events = ws.events()
top = ws.top_events(limit=10)
print("Events:", events[:20])
print("Top:", [(e.event, e.count) for e in top])
# 2. Find real property names for the event you'll query
props = ws.properties("Login") # use an actual event name from step 1
print("Properties:", props)
# 3. (Optional) Check property values to validate filter inputs
vals = ws.property_values("platform", event="Login")
print("Platforms:", vals)
Step 2: Discover the API surface with help.py
help.py is the source of truth for method signatures, parameter names, type constructors, and enum values. The method signatures later in this document are summaries — always verify with help.py before using a method or type you haven't looked up.
Never guess parameter names. If you're unsure whether a parameter is called property or math_property, or what arguments GroupBy() accepts, run help.py first. Wrong parameter names cause TypeErrors that waste tool calls.
# Look up a query method BEFORE writing the query
python3 $SKILL_DIR/scripts/help.py Workspace.query
python3 $SKILL_DIR/scripts/help.py Workspace.query_funnel
# Look up types BEFORE constructing them
python3 $SKILL_DIR/scripts/help.py Filter # → classmethods: .equals(), .less_than(), etc.
python3 $SKILL_DIR/scripts/help.py Metric # → property=, NOT math_property=
python3 $SKILL_DIR/scripts/help.py GroupBy # → property, property_type only
python3 $SKILL_DIR/scripts/help.py MathType # → enum values
# Look up result types to know what columns .df returns
python3 $SKILL_DIR/scripts/help.py QueryResult
python3 $SKILL_DIR/scripts/help.py FlowQueryResult
# Search when you're not sure of the exact name
python3 $SKILL_DIR/scripts/help.py search cohort # → CohortBreakdown, CohortMetric, CohortDefinition, ...
python3 $SKILL_DIR/scripts/help.py search retention # → query_retention, RetentionEvent, RetentionMathType, ...
# List everything
python3 $SKILL_DIR/scripts/help.py types # all public types
python3 $SKILL_DIR/scripts/help.py exceptions # all exceptions
For tutorials and guides: WebFetch(url="https://mixpanel.github.io/mixpanel-headless/llms.txt")
Discovery method signatures
def events(self) -> list[str]: ...
# List all event names (cached).
def properties(self, event: str) -> list[str]: ...
# List all property names for an event (cached).
def property_values(self, property_name: str, *, event: str | None = None, limit: int = 100) -> list[str]: ...
# Get sample values for a property.
def top_events(self, *, type: Literal['general', 'average', 'unique'] = 'general', limit: int | None = None) -> list[TopEvent]: ...
# Get today's most active events. TopEvent has .event (str), .count (int), .percent_change (float).
def funnels(self) -> list[FunnelInfo]: ...
# List saved funnels.
def cohorts(self) -> list[SavedCohort]: ...
# List saved cohorts.
def list_bookmarks(self, bookmark_type: BookmarkType | None = None) -> list[BookmarkInfo]: ...
# List all saved reports (bookmarks).
def lexicon_schemas(self, *, entity_type: EntityType | None = None) -> list[LexiconSchema]: ...
# List Lexicon schemas (event/property definitions).
def clear_discovery_cache(self) -> None: ...
# Clear cached discovery results.
# User Guide: WebFetch(url="https://mixpanel.github.io/mixpanel-headless/guide/discovery/index.md")
Exploratory Analysis Workflow
When exploring an unfamiliar dataset or asked to "find insights," follow this systematic approach. Do NOT skip to querying — explore first.
Step 1: Orient — Map the Event Schema
import mixpanel_headless as mp
ws = mp.Workspace()
events = ws.events()
top = ws.top_events(limit=15)
print("Events:", events)
print("Top events:", [(e.event, e.count) for e in top])
# Profile the top 3-5 events by volume
for event in [e.event for e in top[:5]]:
props = ws.properties(event)
print(f"\n{event} ({len(props)} properties):")
for p in props[:15]:
vals = ws.property_values(p, event=event, limit=10)
print(f" {p}: {vals}")
Step 2: Classify Properties
Infer property types from sampled values to decide how to use each:
Boolean: values are ['true', 'false'] — segment with group_by, often pre-computed behavioral flags
Low-cardinality categorical (<10 values): platform, tier, category — use for group_by
Numeric: values parse as int/float: price, total, count — use for math='average' or math='sum' with math_property=
High-cardinality (>100 values): IDs, names — skip for group_by, may need custom property cleanup
Temporal: ISO dates or epoch values — use for time-based analysis
Property naming patterns that signal analytical value:
*_total, *_count, *_value, *_amount → numeric, aggregate with avg/sum/median
*_name, *_type, *_category, *_tier → categorical, use for breakdowns
*_id, *_uuid → identifiers, skip for breakdowns
Step 3: Scan for Significant Segments
For each boolean and low-cardinality categorical property on key events, run a quick breakdown against a numeric metric:
# Example: scan all interesting properties on a purchase event
numeric_prop = 'order_total' # or whatever the key metric is
interesting_props = [p for p in props if not p.endswith('_id')]
for prop in interesting_props:
vals = ws.property_values(prop, event=event, limit=10)
if len(set(vals)) <= 10: # low cardinality — worth a breakdown
result = ws.query(event, math='average', math_property=numeric_prop,
group_by=prop, last=90, mode='total')
print(f"\n{numeric_prop} by {prop}:")
print(result.df.to_string(index=False))
# Flag segments where metric differs >15% from overall
Step 4: Deep Dive on Significant Findings
When a breakdown reveals a notable difference (>15% between segments):
Quantify: calculate the exact ratio between segments
Cross-reference: does this segment differ on other metrics too?
Investigate causally: run funnels or retention filtered by the segment
Control for confounds: add a second group_by dimension to check if the effect holds
Step 5: Analyze Messy String Properties
When string properties have complex/unreadable values (e.g., campaign names from tools like Braze):
Sample 15-20 values to identify the naming convention
Look for structural patterns: date codes, targeting prefixes, channel suffixes, audience tags
Design regex cleanup rules, one layer per structural element
Create a custom property with ws.create_custom_property(CreateCustomPropertyParams(...))
Verify by querying with the custom property as group_by
Custom Property Formula Reference
Formulas use a SQL-like expression language. Variables (A, B, _A, etc.) map to properties via composedProperties.
REGEX_EXTRACT(haystack, pattern, capture_group) — returns match or capture group
REGEX_REPLACE(haystack, pattern, replacement) — replaces all matches
Regex engine quirks (Mixpanel-specific):
Case-insensitive by default — use (?-i) to switch to case-sensitive matching within a pattern
Backreferences work — $1, $2 capture groups and $0 whole-match all work in REGEX_REPLACE replacements
{n,m} quantifiers conflict with formula syntax — curly braces are parsed as formula constructs. Use repeated character classes instead (e.g., [0-9][0-9][0-9][0-9] instead of [0-9]{4})
\d, \w shorthand classes don't work — use [0-9], [A-Za-z0-9_] explicitly
Escape backslashes carefully — in formula strings, \\\\ may be needed for a literal \ depending on how the formula is constructed (Python string → JSON → regex engine)
CamelCase splitting — insert space between lowercase→uppercase boundaries:
REGEX_REPLACE(text, "(?-i)([a-z])([A-Z])", "$1 $2")
// ChickenSundaysApril → Chicken Sundays April
Practical multi-step cleanup example (campaign names from Braze):
Same parameters as the corresponding query methods, but return dict[str, Any] bookmark params without making an API call. Useful for creating saved reports (bookmarks).
Every query engine has parameters that look like simple settings but are actually analytical choices with outsized influence on results. Before running any query, apply these principles:
Find the master dial. Each engine has one parameter (or small set) that reshapes all downstream metrics. Changing it changes the story. Know which parameter it is and choose deliberately — don't accept defaults blindly.
Match parameters to the domain. There are no universal "correct" values. A social app needs daily retention; a B2B SaaS needs monthly. A food-ordering funnel needs a 1-hour window; an onboarding funnel needs 14 days. The product's natural usage cadence dictates the setting.
Distrust averages. Averages include outliers — one extreme value distorts the whole metric. Use medians (math='median', percentile=50) to see what's typical. If the mean and median diverge, the distribution is skewed and the mean is misleading.
Counting methodology is a modeling choice. "Unique users," "total events," and "sessions" aren't just modes — they answer fundamentally different questions. "How many people?" vs "How much activity?" vs "How many engagement moments?" Choose the counting method that matches the business question.
Know the silent defaults. Parameters are sometimes silently ignored (e.g., math_property with math='unique'), silently constraining (e.g., no funnel re-entry by default), or silently inflating (e.g., unbounded_mode='carry_forward' in retention). If results look surprising, check whether a default is shaping them.
Sweep, don't guess. When unsure which parameter value to use, try several and observe how metrics shift. Where the metric stabilizes or diverges reveals the true signal. The code examples below demonstrate this for each engine.
Comparing Segments Across Multiple Dimensions
When a single breakdown shows a difference, verify it holds across dimensions:
# Step 1: Find the interesting segment
result = ws.query(event, math='average', math_property='order_total',
group_by='deal_sweet_spot', last=90, mode='total')
# Found: deal_sweet_spot=true has 37% higher AOV
# Step 2: Check if it holds across another dimension
result = ws.query(event, math='average', math_property='order_total',
group_by=['deal_sweet_spot', 'platform'], last=90, mode='total')
# Does the sweet spot hold for both iOS and Android?
# Step 3: Check segment rates across a third dimension
result = ws.query(event, math='unique',
group_by=['loyalty_tier', 'deal_sweet_spot'], last=90, mode='total')
# Which tier is most likely to achieve the sweet spot?
Insights Analysis: MathType, Per-User, and the Unit of Analysis
MathType is the most critical Insights parameter. It defines what you're counting — total (event volume), unique (user reach), dau/wau/mau (time-bounded engagement), average/median/percentile (property distributions), sum (revenue totals). Choosing the wrong MathType answers the wrong question silently. Match MathType to the business question: engagement → dau or wau; revenue → sum or average with math_property; adoption → unique; intensity → total.
Per-user aggregation is a two-stage process that fundamentally changes the unit of analysis. per_user='average' with math='average' first computes each user's average, then averages across users. This is NOT the same as a global average — a power user with 1000 events and a casual user with 2 events contribute equally. This is often the right choice (prevents power users from dominating) but it changes the story dramatically:
# Sweep MathTypes to understand an event from multiple angles
event = 'Purchase' # use a real event name
prop = 'order_total' # use a real numeric property
for mt in ['total', 'unique', 'dau', 'average', 'median', 'sum']:
kwargs = {'math': mt, 'last': 30, 'mode': 'total'}
if mt in ('average', 'median', 'sum'):
kwargs['math_property'] = prop
result = ws.query(event, **kwargs)
print(f"{mt:>10}: {result.df['count'].iloc[0]:>12,.2f}")
# total = event volume, unique = user reach, dau = daily engagement,
# average/median = typical transaction, sum = total revenue
# Per-user aggregation: compare global average vs per-user average
global_avg = ws.query(event, math='average', math_property=prop, last=30, mode='total')
per_user_avg = ws.query(event, math='average', math_property=prop,
per_user='average', last=30, mode='total')
print(f"Global avg: {global_avg.df['count'].iloc[0]:.2f}")
print(f"Per-user avg: {per_user_avg.df['count'].iloc[0]:.2f}")
# If these differ significantly, power users are skewing the global average
Prefer medians over averages for property distributions — same principle as funnel time-to-convert. Use math='median' instead of math='average', or math='percentile' with percentile_value=50. Averages include outliers; medians reveal what's typical.
Silent traps:math_property is silently ignored with non-property MathType (e.g., math='unique' discards math_property). rolling reduces data point count without warning (a 30-day rolling window over 59 days produces ~29 points, not 59). unit is silently ignored in mode='total'.
Funnel Analysis: Windows, Modes, and Time
Funnel queries return time data in step metadata columns (avg_time, avg_time_from_start) alongside conversion rates.
Conversion window is the most critical funnel parameter. It defines the maximum time a user has to complete the funnel from their first step. It affects every other metric — conversion rate, time-to-convert, and segment comparisons all shift dramatically with window size.
Choosing a window: Match it to the user journey being measured. Short funnels (ordering food, adding to cart) need tight windows — hours, not days. Long funnels (onboarding, subscription purchase) need wider windows — days or weeks. When unsure, experiment:
# Try progressively tighter windows to find where signal emerges
for window, unit in [(14, 'day'), (7, 'day'), (1, 'day'), (12, 'hour'), (6, 'hour')]:
result = ws.query_funnel(steps, last=90,
conversion_window=window, conversion_window_unit=unit)
final = result.df[result.df['step'] == result.df['step'].max()].iloc[0]
print(f"{window}{unit}: conv={final['overall_conv_ratio']:.3f} "
f"time={final['avg_time_from_start']/3600:.1f}h")
# Look for: conversion stabilizing, time differences appearing at tighter windows
Conversion counting modes change what "conversion" means:
conversion_rate_unique (default): unique users who completed. No re-entry — first attempt in the window or out.
conversion_rate_total: total completions. One user can count multiple times.
Combine with reentry_mode='basic' or reentry_mode='optimized' for multiple attempts. Optimized re-entry picks the best completion path.
Time-to-convert: prefer medians over averages. Average time includes outliers — one slow user inflates the average; one fast user pulls it down. Use median or percentiles for true speed trends:
# Median time via funnel math
result = ws.query_funnel(steps, last=90, math='median')
# Compare segments with filtered funnels + tight window
ios = ws.query_funnel(steps, where=Filter.equals('platform', 'iOS'),
last=90, conversion_window=6, conversion_window_unit='hour')
android = ws.query_funnel(steps, where=Filter.equals('platform', 'Android'),
last=90, conversion_window=6, conversion_window_unit='hour')
# Compare avg_time_from_start on matching steps
When comparing segments across funnels: always try at least 2-3 conversion windows. A difference invisible at 14 days may be stark at 6 hours. This is especially true for speed comparisons — tighter windows filter out noise and reveal which segment completes faster.
order changes what "conversion" means.'loose' (default) requires steps in sequence but allows other events between them. 'any' requires all steps in any order — a user who does C→B→A counts as converting. The difference is dramatic: loose funnels measure sequential workflows; any-order funnels measure feature adoption breadth. When unsure, run both and compare:
# order='loose' vs 'any' — same steps, fundamentally different questions
for ord in ['loose', 'any']:
result = ws.query_funnel(steps, last=90, order=ord)
print(f"order={ord}: {result.overall_conversion_rate:.3f}")
# If 'any' >> 'loose', users are completing all steps but not in the expected order
# This often reveals UX issues — users accomplish the goal but not via the designed path
holding_constant isolates cross-step consistency. Hold a property like 'platform' or 'device_id' constant and users who change values between steps (e.g., sign up on iOS, purchase on Android) are excluded. This reveals single-device vs cross-device conversion and is essential for understanding journeys that span platforms. Maximum 3 properties.
Exclusions disqualify tainted journeys.exclusions=["Logout"] removes users who logged out between funnel steps — unlike flow hidden_events, exclusions completely remove users from the funnel. Use for support escalation events, churn signals, or any action that taints the conversion path. Control which steps the exclusion applies to with Exclusion("Logout", from_step=0, to_step=2) (0-indexed).
Per-step filters narrow individual steps without affecting others.FunnelStep("Purchase", filters=[Filter.greater_than("amount", 50)]) restricts which Purchase events count, but doesn't filter Signup events. Global where filters ALL steps. This distinction is subtle but powerful: filter the population with where, filter the definition of a step with per-step filters.
Session windows are a distinct paradigm.conversion_window_unit='session' constrains the entire funnel to a single engagement session — no multi-session hops. This reveals true in-session conversion behavior, separate from users who spread a journey across days. The third counting mode, math='conversion_rate_session', counts sessions rather than users or events (requires conversion_window_unit='session').
Retention Analysis: The Cohort Bucketing Triple
retention_unit + alignment + bucket_sizes define your entire retention model — retention's equivalent of the funnel conversion window. retention_unit groups users into cohorts (day/week/month). alignment anchors cohorts (birth = each user's clock starts from their event; interval_start = snap to calendar boundaries). bucket_sizes sets measurement points. Changing any one reshapes all downstream metrics.
Match retention_unit to your product's natural usage cadence. Daily products (social, messaging) need retention_unit='day'. Weekly products (task management, fitness) need 'week'. Monthly products (subscriptions, B2B SaaS) need 'month'. When unsure, experiment:
# Sweep retention_unit to find natural product cadence
born, ret = 'Signup', 'Login' # use real event names
for ru in ['day', 'week', 'month']:
result = ws.query_retention(born, ret, retention_unit=ru, last=90)
avg = result.average
if avg is not None and len(avg) > 1:
bucket_1_rate = avg.iloc[1]['rate'] if 'rate' in avg.columns else None
print(f"{ru:>6} retention: bucket 1 = {bucket_1_rate}")
# The unit where bucket-1 retention is highest reveals natural usage cadence
# Custom buckets for milestone-based retention (days 1, 3, 7, 14, 30)
result = ws.query_retention(born, ret, retention_unit='week',
bucket_sizes=[1, 3, 7, 14, 30], unit='day', last=90)
print(result.df[result.df['cohort_date'] == '$overall'])
# Day 1 = activation, Day 7 = habit formation, Day 30 = long-term retention
# Compare alignment modes — can shift results dramatically
for align in ['birth', 'interval_start']:
result = ws.query_retention(born, ret, retention_unit='week',
alignment=align, last=90)
print(f"\nalignment={align}:")
print(result.average.head() if result.average is not None else "No data")
Be wary of unbounded modes — they inflate retention.unbounded_mode='carry_forward' credits future returns to past buckets — a user who returns only on day 30 gets counted as retained in all buckets from 30 onward. carry_back inflates early buckets instead. Useful for "did they ever engage?" analysis but distorts standard retention curves.
retention_cumulative=True masks re-engagement gaps. Cumulative retention creates monotonically increasing curves where each bucket includes all prior buckets. This hides whether users who returned in week 1 ALSO returned in week 2. Standard (non-cumulative) retention reveals re-engagement patterns and true habit formation.
Counting methodology:math='retention_rate' (% who returned — the default), math='unique' (count who returned), math='total' (how many times they returned — events, not users). total reveals engagement intensity; a user logging in 5 times in bucket 1 counts as 5, not 1. Like funnels, the counting choice changes the question.
Flow Analysis: Windows, Cardinality, and Signal-to-Noise
Cardinality controls signal-to-noise — the most important flow-specific parameter. Low cardinality (2-3) reveals dominant paths — the main story. High cardinality (10+) reveals edge cases and niche journeys. Start low to find the narrative, then increase to find exceptions.
conversion_window matters for flows too — identical concept to funnels. Session-based windows (conversion_window_unit='session') reveal in-app behavior within a single engagement. Calendar windows reveal multi-day journeys. A tight window isolates intentional workflows; a wide window captures exploratory meandering:
# Sweep cardinality to find signal-to-noise sweet spot
event = 'Login' # use a real anchor event
for card in [2, 3, 5, 10]:
result = ws.query_flow(event, forward=3, cardinality=card, last=30)
transitions = result.top_transitions(5)
print(f"\ncardinality={card}: {len(transitions)} top transitions")
for src, dst, count in transitions[:3]:
print(f" {src} → {dst}: {count}")
# Low cardinality = clear narrative; high cardinality = exhaustive but noisy
# Compare count types (same principle as funnels)
for ct in ['unique', 'total', 'session']:
result = ws.query_flow(event, forward=3, count_type=ct, last=30)
dropoff = result.drop_off_summary()
print(f"\n{ct}: step 0 dropoff = {dropoff}")
# unique = how many people; total = how much activity; session = how many sessions
# Compare collapse_repeated to separate intent from noise
for collapse in [False, True]:
result = ws.query_flow(event, forward=3, collapse_repeated=collapse,
cardinality=5, last=30)
print(f"\ncollapse_repeated={collapse}:")
for src, dst, count in result.top_transitions(3):
print(f" {src} → {dst}: {count}")
collapse_repeated changes what "a path" means. With False (default), A→A→A→B is a distinct path from A→B — repetitive clicks look like distinct journeys. With True, consecutive duplicates merge, revealing intent over noise. Toggle this to see both the raw behavior and the simplified user intent.
hidden_events vs exclusions — hiding vs disqualifying.hidden_events removes events from display but they still affect path structure and counts. exclusions disqualifies users who performed those events entirely — a much stronger operation. Use hidden_events for decluttering (e.g., ubiquitous page views); use exclusions for removing tainted journeys (e.g., users who churned mid-flow).
Three modes reveal different stories.sankey shows aggregate flow structure and bottlenecks (where do most users go?). paths shows exact user journeys in sequence (what are the top 5 complete paths?). tree shows branching decision points (where do users diverge?). Use all three on the same data to build a complete picture.
User Profile Analysis: Modes, Aggregates, and Distribution Shape
mode is the most critical user query parameter.'profiles' returns individual user records (one row per user). 'aggregate' returns a single statistic. These are fundamentally different operations — profiles is a data extraction, aggregate is a calculation. Aggregate is also dramatically faster (single API call vs paginated fetching).
Sweep aggregate functions to understand distribution shape before building expensive profile queries. count tells you "how many." extremes reveals range (min/max). percentile at 50 gives median. numeric_summary gives mean, variance, and sum-of-squares:
# Sweep aggregate functions to understand a property's distribution
prop = 'lifetime_value' # use a real numeric profile property
for agg in ['count', 'extremes', 'percentile', 'numeric_summary']:
kwargs = {'mode': 'aggregate', 'aggregate': agg}
if agg != 'count':
kwargs['aggregate_property'] = prop
if agg == 'percentile':
kwargs['percentile'] = 50 # median
result = ws.query_user(**kwargs)
print(f"{agg:>16}: {result.aggregate_data}")
# count = population size, extremes = range, percentile@50 = median,
# numeric_summary = full distribution stats
# If mean (from numeric_summary) >> median (from percentile), distribution is right-skewed
# Point-in-time comparison with as_of
today_count = ws.query_user(mode='aggregate', aggregate='count',
where=Filter.equals('plan', 'premium'))
past_count = ws.query_user(mode='aggregate', aggregate='count',
where=Filter.equals('plan', 'premium'), as_of='2025-01-01')
print(f"Premium users: {past_count.value} (Jan 1) → {today_count.value} (today)")
Prefer medians over averages — same principle as funnels and Insights. aggregate='percentile', percentile=50 gives median; numeric_summary gives mean. If they diverge significantly, the distribution is skewed and the mean is misleading.
as_of enables temporal analysis — query profiles as they existed at a past date. Compare population states over time: "how many premium users existed on Jan 1 vs today?" Without as_of, you always see current state, making growth and churn invisible.
Inline CohortDefinition vs saved cohorts. Inline cohorts (cohort=CohortDefinition.all_of(...)) let you define complex behavioral segments on-the-fly without roundtripping to save/delete
…(truncated)
1---2name: mixpanelyst3description: This skill should be used when the user asks about Mixpanel product analytics, event data, funnel analysis, retention curves, cohort analysis, segmentation queries, user behavior, conversion rates, churn, DAU/MAU, ARPU, revenue metrics, feature adoption, A/B test results, user paths, flow analysis, or any request to query, explore, visualize, or analyze Mixpanel data using Python. Also use when the user asks to read, write, or manage Mixpanel "business context" — the markdown documentation that grounds AI assistants in an organization's structure and goals.4allowed-tools: Bash Read Write WebFetch5metadata:6 source: https://skillmd.com/skills/concertonotes/mixpanelyst7---89# mixpanel_headless API Reference1011Analyze Mixpanel data by writing and executing Python code using the `mixpanel_headless` library and `pandas`.12Before running bundled helper scripts, set `SKILL_DIR` to the absolute path of this13`skills/mixpanelyst` directory.1415```python16import mixpanel_headless as mp17ws = mp.Workspace()18result = ws.query("Login", last=30)19print(result.df.head())20```2122## Query Engines2324| Question | Method | Returns |25|----------|--------|---------|26| How much? How many? Trends? | `ws.query()` | `QueryResult` |27| Do users convert through a sequence? | `ws.query_funnel()` | `FunnelQueryResult` |28| Do users come back? | `ws.query_retention()` | `RetentionQueryResult` |29| What paths do users take? | `ws.query_flow()` | `FlowQueryResult` |30| Who are they? What do they look like? | `ws.query_user()` | `UserQueryResult` |3132All result types have a `.df` property returning a pandas DataFrame and a `.params` dict containing the bookmark JSON.33`FlowQueryResult` also has `.graph` (NetworkX DiGraph) and `.anytree` (list of tree roots).3435**Quick lookups** use `python3 -c "..."` one-liners. **Multi-step analysis** writes `.py` files.3637## Discovery — ALWAYS Do Both Steps Before Querying3839Guessing event names causes silent empty results. Guessing API parameters causes TypeErrors and invalid queries. **Discover both the data schema AND the API surface before writing any query.**4041### Step 1: Discover the data schema4243```python44import mixpanel_headless as mp45from mixpanel_headless import Filter, GroupBy, Metric46ws = mp.Workspace()4748# 1. Find real event names49events = ws.events()50top = ws.top_events(limit=10)51print("Events:", events[:20])52print("Top:", [(e.event, e.count) for e in top])5354# 2. Find real property names for the event you'll query55props = ws.properties("Login") # use an actual event name from step 156print("Properties:", props)5758# 3. (Optional) Check property values to validate filter inputs59vals = ws.property_values("platform", event="Login")60print("Platforms:", vals)61```6263### Step 2: Discover the API surface with `help.py`6465**`help.py` is the source of truth for method signatures, parameter names, type constructors, and enum values.** The method signatures later in this document are summaries — always verify with `help.py` before using a method or type you haven't looked up.6667**Never guess parameter names.** If you're unsure whether a parameter is called `property` or `math_property`, or what arguments `GroupBy()` accepts, run `help.py` first. Wrong parameter names cause TypeErrors that waste tool calls.6869```bash70# Look up a query method BEFORE writing the query71python3 $SKILL_DIR/scripts/help.py Workspace.query72python3 $SKILL_DIR/scripts/help.py Workspace.query_funnel7374# Look up types BEFORE constructing them75python3 $SKILL_DIR/scripts/help.py Filter # → classmethods: .equals(), .less_than(), etc.76python3 $SKILL_DIR/scripts/help.py Metric # → property=, NOT math_property=77python3 $SKILL_DIR/scripts/help.py GroupBy # → property, property_type only78python3 $SKILL_DIR/scripts/help.py MathType # → enum values7980# Look up result types to know what columns .df returns81python3 $SKILL_DIR/scripts/help.py QueryResult82python3 $SKILL_DIR/scripts/help.py FlowQueryResult8384# Search when you're not sure of the exact name85python3 $SKILL_DIR/scripts/help.py search cohort # → CohortBreakdown, CohortMetric, CohortDefinition, ...86python3 $SKILL_DIR/scripts/help.py search retention # → query_retention, RetentionEvent, RetentionMathType, ...8788# List everything89python3 $SKILL_DIR/scripts/help.py types # all public types90python3 $SKILL_DIR/scripts/help.py exceptions # all exceptions91```9293For tutorials and guides: `WebFetch(url="https://mixpanel.github.io/mixpanel-headless/llms.txt")`9495### Discovery method signatures9697```python98def events(self) -> list[str]: ...99 # List all event names (cached).100101def properties(self, event: str) -> list[str]: ...102 # List all property names for an event (cached).103104def property_values(self, property_name: str, *, event: str | None = None, limit: int = 100) -> list[str]: ...105 # Get sample values for a property.106107def top_events(self, *, type: Literal['general', 'average', 'unique'] = 'general', limit: int | None = None) -> list[TopEvent]: ...108 # Get today's most active events. TopEvent has .event (str), .count (int), .percent_change (float).109110def funnels(self) -> list[FunnelInfo]: ...111 # List saved funnels.112113def cohorts(self) -> list[SavedCohort]: ...114 # List saved cohorts.115116def list_bookmarks(self, bookmark_type: BookmarkType | None = None) -> list[BookmarkInfo]: ...117 # List all saved reports (bookmarks).118119def lexicon_schemas(self, *, entity_type: EntityType | None = None) -> list[LexiconSchema]: ...120 # List Lexicon schemas (event/property definitions).121122def clear_discovery_cache(self) -> None: ...123 # Clear cached discovery results.124# User Guide: WebFetch(url="https://mixpanel.github.io/mixpanel-headless/guide/discovery/index.md")125```126127## Exploratory Analysis Workflow128129When exploring an unfamiliar dataset or asked to "find insights," follow this systematic approach. Do NOT skip to querying — explore first.130131### Step 1: Orient — Map the Event Schema132133```python134import mixpanel_headless as mp135ws = mp.Workspace()136137events = ws.events()138top = ws.top_events(limit=15)139print("Events:", events)140print("Top events:", [(e.event, e.count) for e in top])141142# Profile the top 3-5 events by volume143for event in [e.event for e in top[:5]]:144 props = ws.properties(event)145 print(f"\n{event} ({len(props)} properties):")146 for p in props[:15]:147 vals = ws.property_values(p, event=event, limit=10)148 print(f" {p}: {vals}")149```150151### Step 2: Classify Properties152153Infer property types from sampled values to decide how to use each:154155- **Boolean**: values are `['true', 'false']` — segment with `group_by`, often pre-computed behavioral flags156- **Low-cardinality categorical** (<10 values): `platform`, `tier`, `category` — use for `group_by`157- **Numeric**: values parse as int/float: `price`, `total`, `count` — use for `math='average'` or `math='sum'` with `math_property=`158- **High-cardinality** (>100 values): IDs, names — skip for `group_by`, may need custom property cleanup159- **Temporal**: ISO dates or epoch values — use for time-based analysis160161Property naming patterns that signal analytical value:162- `is_*`, `has_*`, `was_*`, `post_*` → boolean flags, often pre-computed behavioral segments worth investigating163- `*_total`, `*_count`, `*_value`, `*_amount` → numeric, aggregate with avg/sum/median164- `*_name`, `*_type`, `*_category`, `*_tier` → categorical, use for breakdowns165- `*_id`, `*_uuid` → identifiers, skip for breakdowns166167### Step 3: Scan for Significant Segments168169For each boolean and low-cardinality categorical property on key events, run a quick breakdown against a numeric metric:170171```python172# Example: scan all interesting properties on a purchase event173numeric_prop = 'order_total' # or whatever the key metric is174interesting_props = [p for p in props if not p.endswith('_id')]175176for prop in interesting_props:177 vals = ws.property_values(prop, event=event, limit=10)178 if len(set(vals)) <= 10: # low cardinality — worth a breakdown179 result = ws.query(event, math='average', math_property=numeric_prop,180 group_by=prop, last=90, mode='total')181 print(f"\n{numeric_prop} by {prop}:")182 print(result.df.to_string(index=False))183 # Flag segments where metric differs >15% from overall184```185186### Step 4: Deep Dive on Significant Findings187188When a breakdown reveals a notable difference (>15% between segments):1891. **Quantify**: calculate the exact ratio between segments1902. **Cross-reference**: does this segment differ on other metrics too?1913. **Investigate causally**: run funnels or retention filtered by the segment1924. **Control for confounds**: add a second `group_by` dimension to check if the effect holds193194### Step 5: Analyze Messy String Properties195196When string properties have complex/unreadable values (e.g., campaign names from tools like Braze):1971. Sample 15-20 values to identify the naming convention1982. Look for structural patterns: date codes, targeting prefixes, channel suffixes, audience tags1993. Design regex cleanup rules, one layer per structural element2004. Create a custom property with `ws.create_custom_property(CreateCustomPropertyParams(...))`2015. Verify by querying with the custom property as `group_by`202203### Custom Property Formula Reference204205Formulas use a SQL-like expression language. Variables (A, B, _A, etc.) map to properties via `composedProperties`.206207**Variable binding:** `LET(name, expression, body)` — define intermediate results:208```209LET(raw, A, REGEX_REPLACE(raw, "pattern", "replacement"))210LET(x, A * B, IFS(x < 50, "low", x < 200, "mid", TRUE, "high"))211```212213**Conditionals:** `IF(cond, then, else)`, `IFS(cond1, val1, cond2, val2, ..., TRUE, default)`214215**String functions:** `UPPER(s)`, `LOWER(s)`, `LEN(s)`, `LEFT(s, n)`, `RIGHT(s, n)`, `MID(s, start, count)`, `SPLIT(s, delim, n)`, `HAS_PREFIX(s, p)`, `HAS_SUFFIX(s, p)`, `PARSE_URL(s, "domain")`216217**Regex functions (PCRE2 engine):**218- `REGEX_MATCH(haystack, pattern)` — returns true/false219- `REGEX_EXTRACT(haystack, pattern, capture_group)` — returns match or capture group220- `REGEX_REPLACE(haystack, pattern, replacement)` — replaces all matches221222**Regex engine quirks (Mixpanel-specific):**223- **Case-insensitive by default** — use `(?-i)` to switch to case-sensitive matching within a pattern224- **Backreferences work** — `$1`, `$2` capture groups and `$0` whole-match all work in `REGEX_REPLACE` replacements225- **`{n,m}` quantifiers conflict with formula syntax** — curly braces are parsed as formula constructs. Use repeated character classes instead (e.g., `[0-9][0-9][0-9][0-9]` instead of `[0-9]{4}`)226- **`\d`, `\w` shorthand classes don't work** — use `[0-9]`, `[A-Za-z0-9_]` explicitly227- **Escape backslashes carefully** — in formula strings, `\\\\` may be needed for a literal `\` depending on how the formula is constructed (Python string → JSON → regex engine)228229**CamelCase splitting** — insert space between lowercase→uppercase boundaries:230```231REGEX_REPLACE(text, "(?-i)([a-z])([A-Z])", "$1 $2")232// ChickenSundaysApril → Chicken Sundays April233```234235**Practical multi-step cleanup example** (campaign names from Braze):236```237LET(s1, REGEX_REPLACE(A, "^[0-9][0-9][0-9][0-9][0-9]*_", ""),238LET(s2, REGEX_REPLACE(s1, "^(NW|TARGETED|REGIONAL|NTL)_", ""),239LET(s3, REGEX_REPLACE(s2, "_(Push|Email|NotificationCenter|ModalInAppMessage)_.*$", ""),240LET(s4, REGEX_REPLACE(s3, "_", " "),241 REGEX_REPLACE(s4, " +", " ")242))))243```244245**Type functions:** `STRING(x)`, `NUMBER(x)`, `BOOLEAN(x)`, `DEFINED(x)`246247**Math:** `+`, `-`, `*`, `/`, `%`, `MIN(a,b)`, `MAX(a,b)`, `FLOOR(n)`, `CEIL(n)`, `ROUND(n)`248249**Date:** `DATEDIF(start, end, unit)` — units: D, M, Y, MD, YM, YD. `TODAY()` for current date.250251**List:** `SUM(list)`, `ANY(x, list, expr)`, `ALL(x, list, expr)`, `FILTER(x, list, expr)`, `MAP(x, list, expr)`252253**Comparison:** `==`, `!=`, `<`, `>`, `<=`, `>=` (case-insensitive for strings), `IN` for list membership254255**Logical:** `AND`, `OR`, `NOT(x)`256257**Constants:** `TRUE`, `FALSE`, `UNDEFINED`258259**Creating a custom property via the API:**260```python261from mixpanel_headless import CreateCustomPropertyParams, ComposedPropertyValue262263params = CreateCustomPropertyParams(264 name="Clean Campaign Name",265 resource_type="events",266 display_formula='LET(raw, A, REGEX_REPLACE(REGEX_REPLACE(raw, "^[0-9]+_", ""), "_", " "))',267 composed_properties={268 "A": ComposedPropertyValue(269 resource_type="event", type="string", value="campaign_name",270 label="Campaign Name", property_default_type="string",271 )272 }273)274prop = ws.create_custom_property(params)275ref = CustomPropertyRef(prop.custom_property_id)276result = ws.query(event, group_by=GroupBy(ref), last=30, mode='total')277```278279## Workspace280281```python282class Workspace:283 """Unified entry point for Mixpanel data operations (042 redesign)."""284285 def __init__(286 self,287 *,288 account: str | None = None,289 project: str | None = None,290 workspace: int | None = None,291 target: str | None = None,292 session: Session | None = None,293 ) -> None:294 """Create a new Workspace. Resolution per axis is independent295 (env > param > target > bridge > config); see296 ``mixpanel_headless.auth_types`` and the resolver.297298 With ``session=`` supplied, all other axis kwargs are ignored299 (full bypass).300 """301 ...302303 # --- Properties (read-only) ---304 account: Account # Resolved Account (discriminated union)305 project: Project # Resolved Project306 workspace: WorkspaceRef | None # Resolved workspace, or None for lazy-resolve307 session: Session # The (account, project, workspace) tuple308 api: MixpanelAPIClient # Direct API client access (escape hatch)309310 def use(311 self,312 *,313 account: str | None = None,314 project: str | None = None,315 workspace: int | None = None,316 target: str | None = None,317 persist: bool = False,318 ) -> Self:319 """Switch any axis in-session. Returns self for chaining.320 Preserves the underlying httpx.Client. With persist=True, also321 writes to ~/.mp/config.toml [active]. ``target=`` is mutex322 with the per-axis kwargs.323 """324 ...325```326327Supports context manager: `with mp.Workspace() as ws: ...`328329### Project & Workspace Management330331```python332def me(self, *, force_refresh: bool = False) -> Any: ...333 # Get /me response for current credentials (cached 24h).334335def projects(self) -> list[Project]: ...336 # List accessible projects (v3; returns Project records — id, name,337 # organization_id, timezone). Replaces deprecated discover_projects().338339def workspaces(self, *, project_id: str | None = None) -> list[WorkspaceRef]: ...340 # List workspaces in a project (v3; returns WorkspaceRef records —341 # id, name, is_default). Replaces deprecated discover_workspaces().342343def list_workspaces(self) -> list[PublicWorkspace]: ...344 # List all public workspaces for the current project (App API).345346def resolve_workspace_id(self) -> int: ...347 # Auto-discover and resolve workspace ID (lazy-resolve helper).348349def close(self) -> None: ...350 # Close all resources (HTTP client). Idempotent.351```352353> **Removed (042 redesign — FR-038):** `Workspace.workspace_id` property,354> `set_workspace_id()`, `switch_project()`, `switch_workspace()`,355> `discover_projects()`, `discover_workspaces()`, `current_project`,356> `current_credential`, `test_credentials()`. Use `ws.session.workspace_id`,357> `ws.use(workspace=N)`, `ws.use(project=P)`, `ws.projects()`,358> `ws.workspaces()`, `ws.project`, `ws.account`, and `mp.accounts.test(NAME)`359> respectively.360361### Insights Query362363Run `python3 $SKILL_DIR/scripts/help.py Workspace.query` for the full signature.364365```python366def query(367 self,368 events: str | Metric | CohortMetric | Formula | Sequence[...],369 *,370 from_date: str | None = None, # YYYY-MM-DD, overrides last371 to_date: str | None = None, # YYYY-MM-DD, requires from_date372 last: int = 30, # relative days (ignored if from_date set)373 unit: QueryTimeUnit = 'day',374 math: MathType = 'total', # aggregation: total, unique, dau, average, sum, ...375 math_property: str | None = None, # top-level shorthand; Metric() uses property= instead376 per_user: PerUserAggregation | None = None,377 percentile_value: int | float | None = None,378 group_by: str | GroupBy | CohortBreakdown | FrequencyBreakdown | list[...] | None = None,379 where: Filter | FrequencyFilter | list[...] | None = None,380 formula: str | None = None, # e.g. "(B / A) * 100", requires 2+ events381 formula_label: str | None = None,382 rolling: int | None = None,383 cumulative: bool = False,384 mode: Literal['timeseries', 'total', 'table'] = 'timeseries',385 time_comparison: TimeComparison | None = None,386 data_group_id: int | None = None,387) -> QueryResult:388 # .df columns: timeseries → [date, event, count]389 # total → [event, count]390 # with group_by → adds segment column391 ...392```393394### Funnel Query395396Run `python3 $SKILL_DIR/scripts/help.py Workspace.query_funnel` for the full signature.397398```python399def query_funnel(400 self,401 steps: list[str | FunnelStep], # at least 2 steps required402 *,403 conversion_window: int = 14,404 conversion_window_unit: Literal['second', 'minute', 'hour', 'day', 'week', 'month', 'session'] = 'day',405 order: Literal['loose', 'any'] = 'loose',406 from_date: str | None = None, to_date: str | None = None, last: int = 30,407 unit: QueryTimeUnit = 'day',408 math: FunnelMathType = 'conversion_rate_unique',409 math_property: str | None = None,410 group_by: str | GroupBy | CohortBreakdown | list[...] | None = None,411 where: Filter | list[Filter] | None = None,412 exclusions: list[str | Exclusion] | None = None,413 holding_constant: str | HoldingConstant | list[...] | None = None,414 mode: Literal['steps', 'trends', 'table'] = 'steps',415 reentry_mode: FunnelReentryMode | None = None,416 time_comparison: TimeComparison | None = None,417 data_group_id: int | None = None,418) -> FunnelQueryResult:419 # .df columns: [step, event, count, step_conv_ratio, avg_time]420 # .overall_conversion_rate: float421 ...422```423424### Retention Query425426Run `python3 $SKILL_DIR/scripts/help.py Workspace.query_retention` for the full signature.427428```python429def query_retention(430 self,431 born_event: str | RetentionEvent,432 return_event: str | RetentionEvent,433 *,434 retention_unit: TimeUnit = 'week',435 alignment: RetentionAlignment = 'birth',436 bucket_sizes: list[int] | None = None,437 from_date: str | None = None, to_date: str | None = None, last: int = 30,438 unit: QueryTimeUnit = 'day',439 math: RetentionMathType = 'retention_rate',440 group_by: str | GroupBy | CohortBreakdown | list[...] | None = None,441 where: Filter | list[Filter] | None = None,442 mode: RetentionMode = 'curve',443 unbounded_mode: RetentionUnboundedMode | None = None,444 retention_cumulative: bool = False,445 time_comparison: TimeComparison | None = None,446 data_group_id: int | None = None,447) -> RetentionQueryResult:448 # .df columns: [cohort_date, bucket, count, rate] (+ segment with group_by)449 # .average: synthetic average across cohorts450 ...451```452453### Flow Query454455Run `python3 $SKILL_DIR/scripts/help.py Workspace.query_flow` for the full signature.456457```python458def query_flow(459 self,460 event: str | FlowStep | Sequence[str | FlowStep],461 *,462 forward: int = 3, reverse: int = 0,463 from_date: str | None = None, to_date: str | None = None, last: int = 30,464 conversion_window: int = 7,465 conversion_window_unit: Literal['day', 'week', 'month', 'session'] = 'day',466 count_type: Literal['unique', 'total', 'session'] = 'unique',467 cardinality: int = 3,468 collapse_repeated: bool = False,469 hidden_events: list[str] | None = None,470 mode: Literal['sankey', 'paths', 'tree'] = 'sankey',471 where: Filter | list[Filter] | None = None,472 segments: str | GroupBy | CohortBreakdown | FrequencyBreakdown | list[...] | None = None,473 exclusions: list[str] | None = None,474 data_group_id: int | None = None,475) -> FlowQueryResult:476 # .df, .graph (NetworkX DiGraph), .anytree (tree mode)477 # .top_transitions(n), .drop_off_summary()478 ...479```480481### User Profile Query482483Run `python3 $SKILL_DIR/scripts/help.py Workspace.query_user` for the full signature.484485```python486def query_user(487 self,488 *,489 where: Filter | list[Filter] | str | None = None,490 cohort: int | CohortDefinition | None = None,491 properties: list[str] | None = None,492 sort_by: str | None = None,493 sort_order: Literal['ascending', 'descending'] = 'descending',494 limit: int | None = 1, # None = fetch all matching495 search: str | None = None,496 distinct_id: str | None = None, # single user lookup497 distinct_ids: list[str] | None = None, # batch lookup498 group_id: str | None = None, # query group profiles499 as_of: str | int | None = None, # point-in-time500 mode: Literal['profiles', 'aggregate'] = 'aggregate',501 aggregate: Literal['count', 'extremes', 'percentile', 'numeric_summary'] = 'count',502 aggregate_property: str | None = None,503 percentile: float | None = None,504 segment_by: list[int] | None = None,505 parallel: bool = False, workers: int = 5,506 include_all_users: bool = False,507) -> UserQueryResult:508 # .df, .total, .profiles509 ...510```511512### Build Params (without executing)513514Same parameters as the corresponding query methods, but return `dict[str, Any]` bookmark params without making an API call. Useful for creating saved reports (bookmarks).515516```python517def build_params(self, events, **kwargs) -> dict[str, Any]: ...518def build_funnel_params(self, steps, **kwargs) -> dict[str, Any]: ...519def build_retention_params(self, born_event, return_event, **kwargs) -> dict[str, Any]: ...520def build_flow_params(self, event, **kwargs) -> dict[str, Any]: ...521def build_user_params(self, **kwargs) -> dict[str, Any]: ...522```523524### Multi-Step Analysis Patterns525526Every query engine has parameters that look like simple settings but are actually analytical choices with outsized influence on results. Before running any query, apply these principles:527528- [ ] **Find the master dial.** Each engine has one parameter (or small set) that reshapes all downstream metrics. Changing it changes the story. Know which parameter it is and choose deliberately — don't accept defaults blindly.529- [ ] **Match parameters to the domain.** There are no universal "correct" values. A social app needs daily retention; a B2B SaaS needs monthly. A food-ordering funnel needs a 1-hour window; an onboarding funnel needs 14 days. The product's natural usage cadence dictates the setting.530- [ ] **Distrust averages.** Averages include outliers — one extreme value distorts the whole metric. Use medians (`math='median'`, `percentile=50`) to see what's typical. If the mean and median diverge, the distribution is skewed and the mean is misleading.531- [ ] **Counting methodology is a modeling choice.** "Unique users," "total events," and "sessions" aren't just modes — they answer fundamentally different questions. "How many people?" vs "How much activity?" vs "How many engagement moments?" Choose the counting method that matches the business question.532- [ ] **Know the silent defaults.** Parameters are sometimes silently ignored (e.g., `math_property` with `math='unique'`), silently constraining (e.g., no funnel re-entry by default), or silently inflating (e.g., `unbounded_mode='carry_forward'` in retention). If results look surprising, check whether a default is shaping them.533- [ ] **Sweep, don't guess.** When unsure which parameter value to use, try several and observe how metrics shift. Where the metric stabilizes or diverges reveals the true signal. The code examples below demonstrate this for each engine.534535#### Comparing Segments Across Multiple Dimensions536537When a single breakdown shows a difference, verify it holds across dimensions:538539```python540# Step 1: Find the interesting segment541result = ws.query(event, math='average', math_property='order_total',542 group_by='deal_sweet_spot', last=90, mode='total')543# Found: deal_sweet_spot=true has 37% higher AOV544545# Step 2: Check if it holds across another dimension546result = ws.query(event, math='average', math_property='order_total',547 group_by=['deal_sweet_spot', 'platform'], last=90, mode='total')548# Does the sweet spot hold for both iOS and Android?549550# Step 3: Check segment rates across a third dimension551result = ws.query(event, math='unique',552 group_by=['loyalty_tier', 'deal_sweet_spot'], last=90, mode='total')553# Which tier is most likely to achieve the sweet spot?554```555556#### Insights Analysis: MathType, Per-User, and the Unit of Analysis557558**MathType is the most critical Insights parameter.** It defines what you're counting — `total` (event volume), `unique` (user reach), `dau/wau/mau` (time-bounded engagement), `average/median/percentile` (property distributions), `sum` (revenue totals). Choosing the wrong MathType answers the wrong question silently. Match MathType to the business question: engagement → `dau` or `wau`; revenue → `sum` or `average` with `math_property`; adoption → `unique`; intensity → `total`.559560**Per-user aggregation is a two-stage process** that fundamentally changes the unit of analysis. `per_user='average'` with `math='average'` first computes each user's average, then averages across users. This is NOT the same as a global average — a power user with 1000 events and a casual user with 2 events contribute equally. This is often the right choice (prevents power users from dominating) but it changes the story dramatically:561562```python563# Sweep MathTypes to understand an event from multiple angles564event = 'Purchase' # use a real event name565prop = 'order_total' # use a real numeric property566567for mt in ['total', 'unique', 'dau', 'average', 'median', 'sum']:568 kwargs = {'math': mt, 'last': 30, 'mode': 'total'}569 if mt in ('average', 'median', 'sum'):570 kwargs['math_property'] = prop571 result = ws.query(event, **kwargs)572 print(f"{mt:>10}: {result.df['count'].iloc[0]:>12,.2f}")573# total = event volume, unique = user reach, dau = daily engagement,574# average/median = typical transaction, sum = total revenue575576# Per-user aggregation: compare global average vs per-user average577global_avg = ws.query(event, math='average', math_property=prop, last=30, mode='total')578per_user_avg = ws.query(event, math='average', math_property=prop,579 per_user='average', last=30, mode='total')580print(f"Global avg: {global_avg.df['count'].iloc[0]:.2f}")581print(f"Per-user avg: {per_user_avg.df['count'].iloc[0]:.2f}")582# If these differ significantly, power users are skewing the global average583```584585**Prefer medians over averages for property distributions** — same principle as funnel time-to-convert. Use `math='median'` instead of `math='average'`, or `math='percentile'` with `percentile_value=50`. Averages include outliers; medians reveal what's typical.586587**Silent traps:** `math_property` is silently ignored with non-property MathType (e.g., `math='unique'` discards `math_property`). `rolling` reduces data point count without warning (a 30-day rolling window over 59 days produces ~29 points, not 59). `unit` is silently ignored in `mode='total'`.588589#### Funnel Analysis: Windows, Modes, and Time590591Funnel queries return time data in step metadata columns (`avg_time`, `avg_time_from_start`) alongside conversion rates.592593**Conversion window is the most critical funnel parameter.** It defines the maximum time a user has to complete the funnel from their first step. It affects every other metric — conversion rate, time-to-convert, and segment comparisons all shift dramatically with window size.594595**Choosing a window:** Match it to the user journey being measured. Short funnels (ordering food, adding to cart) need tight windows — hours, not days. Long funnels (onboarding, subscription purchase) need wider windows — days or weeks. When unsure, experiment:596597```python598# Try progressively tighter windows to find where signal emerges599for window, unit in [(14, 'day'), (7, 'day'), (1, 'day'), (12, 'hour'), (6, 'hour')]:600 result = ws.query_funnel(steps, last=90,601 conversion_window=window, conversion_window_unit=unit)602 final = result.df[result.df['step'] == result.df['step'].max()].iloc[0]603 print(f"{window}{unit}: conv={final['overall_conv_ratio']:.3f} "604 f"time={final['avg_time_from_start']/3600:.1f}h")605# Look for: conversion stabilizing, time differences appearing at tighter windows606```607608**Conversion counting modes** change what "conversion" means:609- `conversion_rate_unique` (default): unique users who completed. No re-entry — first attempt in the window or out.610- `conversion_rate_total`: total completions. One user can count multiple times.611- Combine with `reentry_mode='basic'` or `reentry_mode='optimized'` for multiple attempts. Optimized re-entry picks the best completion path.612613**Time-to-convert: prefer medians over averages.** Average time includes outliers — one slow user inflates the average; one fast user pulls it down. Use median or percentiles for true speed trends:614615```python616# Median time via funnel math617result = ws.query_funnel(steps, last=90, math='median')618619# Compare segments with filtered funnels + tight window620ios = ws.query_funnel(steps, where=Filter.equals('platform', 'iOS'),621 last=90, conversion_window=6, conversion_window_unit='hour')622android = ws.query_funnel(steps, where=Filter.equals('platform', 'Android'),623 last=90, conversion_window=6, conversion_window_unit='hour')624# Compare avg_time_from_start on matching steps625```626627**When comparing segments across funnels:** always try at least 2-3 conversion windows. A difference invisible at 14 days may be stark at 6 hours. This is especially true for speed comparisons — tighter windows filter out noise and reveal which segment completes faster.628629**`order` changes what "conversion" means.** `'loose'` (default) requires steps in sequence but allows other events between them. `'any'` requires all steps in any order — a user who does C→B→A counts as converting. The difference is dramatic: loose funnels measure sequential workflows; any-order funnels measure feature adoption breadth. When unsure, run both and compare:630631```python632# order='loose' vs 'any' — same steps, fundamentally different questions633for ord in ['loose', 'any']:634 result = ws.query_funnel(steps, last=90, order=ord)635 print(f"order={ord}: {result.overall_conversion_rate:.3f}")636# If 'any' >> 'loose', users are completing all steps but not in the expected order637# This often reveals UX issues — users accomplish the goal but not via the designed path638```639640**`holding_constant` isolates cross-step consistency.** Hold a property like `'platform'` or `'device_id'` constant and users who change values between steps (e.g., sign up on iOS, purchase on Android) are excluded. This reveals single-device vs cross-device conversion and is essential for understanding journeys that span platforms. Maximum 3 properties.641642**Exclusions disqualify tainted journeys.** `exclusions=["Logout"]` removes users who logged out between funnel steps — unlike flow `hidden_events`, exclusions completely remove users from the funnel. Use for support escalation events, churn signals, or any action that taints the conversion path. Control which steps the exclusion applies to with `Exclusion("Logout", from_step=0, to_step=2)` (0-indexed).643644**Per-step filters narrow individual steps without affecting others.** `FunnelStep("Purchase", filters=[Filter.greater_than("amount", 50)])` restricts which Purchase events count, but doesn't filter Signup events. Global `where` filters ALL steps. This distinction is subtle but powerful: filter the population with `where`, filter the definition of a step with per-step filters.645646**Session windows are a distinct paradigm.** `conversion_window_unit='session'` constrains the entire funnel to a single engagement session — no multi-session hops. This reveals true in-session conversion behavior, separate from users who spread a journey across days. The third counting mode, `math='conversion_rate_session'`, counts sessions rather than users or events (requires `conversion_window_unit='session'`).647648#### Retention Analysis: The Cohort Bucketing Triple649650**`retention_unit` + `alignment` + `bucket_sizes` define your entire retention model** — retention's equivalent of the funnel conversion window. `retention_unit` groups users into cohorts (day/week/month). `alignment` anchors cohorts (`birth` = each user's clock starts from their event; `interval_start` = snap to calendar boundaries). `bucket_sizes` sets measurement points. Changing any one reshapes all downstream metrics.651652**Match `retention_unit` to your product's natural usage cadence.** Daily products (social, messaging) need `retention_unit='day'`. Weekly products (task management, fitness) need `'week'`. Monthly products (subscriptions, B2B SaaS) need `'month'`. When unsure, experiment:653654```python655# Sweep retention_unit to find natural product cadence656born, ret = 'Signup', 'Login' # use real event names657for ru in ['day', 'week', 'month']:658 result = ws.query_retention(born, ret, retention_unit=ru, last=90)659 avg = result.average660 if avg is not None and len(avg) > 1:661 bucket_1_rate = avg.iloc[1]['rate'] if 'rate' in avg.columns else None662 print(f"{ru:>6} retention: bucket 1 = {bucket_1_rate}")663# The unit where bucket-1 retention is highest reveals natural usage cadence664665# Custom buckets for milestone-based retention (days 1, 3, 7, 14, 30)666result = ws.query_retention(born, ret, retention_unit='week',667 bucket_sizes=[1, 3, 7, 14, 30], unit='day', last=90)668print(result.df[result.df['cohort_date'] == '$overall'])669# Day 1 = activation, Day 7 = habit formation, Day 30 = long-term retention670671# Compare alignment modes — can shift results dramatically672for align in ['birth', 'interval_start']:673 result = ws.query_retention(born, ret, retention_unit='week',674 alignment=align, last=90)675 print(f"\nalignment={align}:")676 print(result.average.head() if result.average is not None else "No data")677```678679**Be wary of unbounded modes — they inflate retention.** `unbounded_mode='carry_forward'` credits future returns to past buckets — a user who returns only on day 30 gets counted as retained in all buckets from 30 onward. `carry_back` inflates early buckets instead. Useful for "did they ever engage?" analysis but distorts standard retention curves.680681**`retention_cumulative=True` masks re-engagement gaps.** Cumulative retention creates monotonically increasing curves where each bucket includes all prior buckets. This hides whether users who returned in week 1 ALSO returned in week 2. Standard (non-cumulative) retention reveals re-engagement patterns and true habit formation.682683**Counting methodology:** `math='retention_rate'` (% who returned — the default), `math='unique'` (count who returned), `math='total'` (how many times they returned — events, not users). `total` reveals engagement intensity; a user logging in 5 times in bucket 1 counts as 5, not 1. Like funnels, the counting choice changes the question.684685#### Flow Analysis: Windows, Cardinality, and Signal-to-Noise686687**Cardinality controls signal-to-noise** — the most important flow-specific parameter. Low cardinality (2-3) reveals dominant paths — the main story. High cardinality (10+) reveals edge cases and niche journeys. Start low to find the narrative, then increase to find exceptions.688689**`conversion_window` matters for flows too** — identical concept to funnels. Session-based windows (`conversion_window_unit='session'`) reveal in-app behavior within a single engagement. Calendar windows reveal multi-day journeys. A tight window isolates intentional workflows; a wide window captures exploratory meandering:690691```python692# Sweep cardinality to find signal-to-noise sweet spot693event = 'Login' # use a real anchor event694for card in [2, 3, 5, 10]:695 result = ws.query_flow(event, forward=3, cardinality=card, last=30)696 transitions = result.top_transitions(5)697 print(f"\ncardinality={card}: {len(transitions)} top transitions")698 for src, dst, count in transitions[:3]:699 print(f" {src} → {dst}: {count}")700# Low cardinality = clear narrative; high cardinality = exhaustive but noisy701702# Compare count types (same principle as funnels)703for ct in ['unique', 'total', 'session']:704 result = ws.query_flow(event, forward=3, count_type=ct, last=30)705 dropoff = result.drop_off_summary()706 print(f"\n{ct}: step 0 dropoff = {dropoff}")707# unique = how many people; total = how much activity; session = how many sessions708709# Compare collapse_repeated to separate intent from noise710for collapse in [False, True]:711 result = ws.query_flow(event, forward=3, collapse_repeated=collapse,712 cardinality=5, last=30)713 print(f"\ncollapse_repeated={collapse}:")714 for src, dst, count in result.top_transitions(3):715 print(f" {src} → {dst}: {count}")716```717718**`collapse_repeated` changes what "a path" means.** With `False` (default), A→A→A→B is a distinct path from A→B — repetitive clicks look like distinct journeys. With `True`, consecutive duplicates merge, revealing intent over noise. Toggle this to see both the raw behavior and the simplified user intent.719720**`hidden_events` vs `exclusions` — hiding vs disqualifying.** `hidden_events` removes events from display but they still affect path structure and counts. `exclusions` disqualifies users who performed those events entirely — a much stronger operation. Use `hidden_events` for decluttering (e.g., ubiquitous page views); use `exclusions` for removing tainted journeys (e.g., users who churned mid-flow).721722**Three modes reveal different stories.** `sankey` shows aggregate flow structure and bottlenecks (where do most users go?). `paths` shows exact user journeys in sequence (what are the top 5 complete paths?). `tree` shows branching decision points (where do users diverge?). Use all three on the same data to build a complete picture.723724#### User Profile Analysis: Modes, Aggregates, and Distribution Shape725726**`mode` is the most critical user query parameter.** `'profiles'` returns individual user records (one row per user). `'aggregate'` returns a single statistic. These are fundamentally different operations — profiles is a data extraction, aggregate is a calculation. Aggregate is also dramatically faster (single API call vs paginated fetching).727728**Sweep aggregate functions to understand distribution shape** before building expensive profile queries. `count` tells you "how many." `extremes` reveals range (min/max). `percentile` at 50 gives median. `numeric_summary` gives mean, variance, and sum-of-squares:729730```python731# Sweep aggregate functions to understand a property's distribution732prop = 'lifetime_value' # use a real numeric profile property733for agg in ['count', 'extremes', 'percentile', 'numeric_summary']:734 kwargs = {'mode': 'aggregate', 'aggregate': agg}735 if agg != 'count':736 kwargs['aggregate_property'] = prop737 if agg == 'percentile':738 kwargs['percentile'] = 50 # median739 result = ws.query_user(**kwargs)740 print(f"{agg:>16}: {result.aggregate_data}")741# count = population size, extremes = range, percentile@50 = median,742# numeric_summary = full distribution stats743# If mean (from numeric_summary) >> median (from percentile), distribution is right-skewed744745# Point-in-time comparison with as_of746today_count = ws.query_user(mode='aggregate', aggregate='count',747 where=Filter.equals('plan', 'premium'))748past_count = ws.query_user(mode='aggregate', aggregate='count',749 where=Filter.equals('plan', 'premium'), as_of='2025-01-01')750print(f"Premium users: {past_count.value} (Jan 1) → {today_count.value} (today)")751```752753**Prefer medians over averages** — same principle as funnels and Insights. `aggregate='percentile', percentile=50` gives median; `numeric_summary` gives mean. If they diverge significantly, the distribution is skewed and the mean is misleading.754755**`as_of` enables temporal analysis** — query profiles as they existed at a past date. Compare population states over time: "how many premium users existed on Jan 1 vs today?" Without `as_of`, you always see current state, making growth and churn invisible.756757**Inline `CohortDefinition` vs saved cohorts.** Inline cohorts (`cohort=CohortDefinition.all_of(...)`) let you define complex behavioral segments on-the-fly without roundtripping to save/delete in Mixpanel. Much faster iteration for exploratory analysis. Use saved cohorts for production dashboards and monitoring.758759#### Analytical Building Blocks: Custom Properties, Cohorts, and Frequency760761Raw data is rarely analysis-ready. These three tools transform raw events and properties into analytically useful dimensions, populations, and segments. Recognize when to reach for each — they compose with every query engine.762763**Inline Custom Properties — transform data at query time.** When property values are messy, need bucketing, or you need to derive new dimensions, create an `InlineCustomProperty` rather than querying raw values. Key patterns:764765- **Bucketing continuous values** for breakdowns (revenue → Low/Medium/High)766- **Cleaning messy strings** with IFS/REGEX_EXTRACT (campaign names, UTM parameters)767- **Deriving new dimensions** from arithmetic or date functions (profit margin, days since signup)768- **Fallback chains** across multiple properties (display_name → username → "unknown")769770```python771from mixpanel_headless import InlineCustomProperty, PropertyInput, GroupBy, Filter, Metric772773# Bucket revenue into tiers for breakdown774revenue_tier = InlineCustomProperty(775 formula='IFS(A < 50, "Low", A < 200, "Medium", TRUE, "High")',776 inputs={"A": PropertyInput("revenue", type="number")},777 property_type="string",778)779result = ws.query("Purchase", group_by=GroupBy(property=revenue_tier), last=30, mode='total')780781# Derive profit margin for aggregation782margin = InlineCustomProperty.numeric("(A - B) / A * 100", A="revenue", B="cost")783result = ws.query(Metric("Purchase", math="average", property=margin), last=30)784785# Clean messy strings for segmentation786domain = InlineCustomProperty(787 formula='REGEX_EXTRACT(A, "@(.+)$")',788 inputs={"A": PropertyInput("email", type="string")},789 property_type="string",790)791result = ws.query("Signup", group_by=GroupBy(property=domain), last=30, mode='total')792```793794Use `InlineCustomProperty` for ad-hoc exploration. When a formula proves valuable, persist it with `ws.create_custom_property()` and reference it via `CustomPropertyRef(id)` across reports.795796**Inline Cohorts — define complex populations on-the-fly.** Every analytical question starts with "among WHICH users?" Simple property filters (`where=Filter.equals(...)`) answer "users with attribute X." Inline cohorts answer harder questions: "users who did X at least N times in the last D days AND did NOT do Y AND have property Z." Compose criteria with AND/OR logic:797798```python799from mixpanel_headless import CohortDefinition, CohortCriteria, CohortBreakdown, CohortMetric800801# "Power users": purchased 5+ times in 30 days, never contacted support802power_users = CohortDefinition.all_of(803 CohortCriteria.did_event("Purchase", at_least=5, within_days=30),804 CohortCriteria.did_not_do_event("Support Ticket", within_days=90),805)806807# Use inline cohort as a breakdown — no need to save first808result = ws.query("Login", group_by=CohortBreakdown(power_users, "Power Users"), last=30)809810# Use inline cohort as a filter in user queries811result = ws.query_user(cohort=power_users, mode='aggregate', aggregate='count')812813# Track saved cohort size over time alongside event metrics814result = ws.query(815 [Metric("Login", math="unique"), CohortMetric(saved_cohort_id, "Power Users")],816 formula="(B / A) * 100", formula_label="% Power Users Active", last=90,817)818```819820**Frequency Breakdown/Filter — segment by behavioral intensity.** `FrequencyBreakdown` answers "how do users who did X once differ from users who did X ten times?" `FrequencyFilter` restricts queries to users meeting a frequency threshold. These bridge "what users did" with "who users are":821822```python823from mixpanel_headless import FrequencyBreakdown, FrequencyFilter824825# Break down login behavior by purchase frequency826result = ws.query("Login", math='unique',827 group_by=FrequencyBreakdown("Purchase", bucket_size=3, bucket_min=0, bucket_max=15),828 last=30, mode='total')829# Reveals: do frequent purchasers also log in more?830831# Filter to users who purchased 3+ times in 30 days, then analyze their flow832result = ws.query_flow("Login", forward=3,833 where=FrequencyFilter("Purchase", value=3, date_range_value=30, date_range_unit="day"),834 last=30)835# Reveals: what do repeat purchasers do after logging in?836```837838**When to reach for each:**839- Property values are messy or need derivation → **Custom Property**840- Population requires behavioral criteria (did X, didn't do Y, frequency thresholds) → **Inline Cohort**841- You need to segment by event frequency (how often, not just whether) → **FrequencyBreakdown/Filter**842- You need to compare in-cohort vs out-of-cohort behavior → **CohortBreakdown** with `include_negated=True`843- You need to track a segment's size as a time series → **CohortMetric** (saved cohorts only)844845### Legacy Queries & Counts846847These use older APIs. Prefer the typed query methods above when possible.848849```python850def segmentation(self, event: str, *, from_date: str, to_date: str, on: str | None = None, unit: Literal['day', 'week', 'month'] = 'day', where: str | None = None) -> SegmentationResult: ...851def funnel(self, funnel_id: int, *, from_date: str, to_date: str, unit: str | None = None, on: str | None = None) -> FunnelResult: ...852def retention(self, *, born_event: str, return_event: str, from_date: str, to_date: str, born_where: str | None = None, return_where: str | None = None, interval: int = 1, interval_count: int = 10, unit: Literal['day', 'week', 'month'] = 'day') -> RetentionResult: ...853def event_counts(self, events: list[str], *, from_date: str, to_date: str, type: Literal['general', 'unique', 'average'] = 'general', unit: Literal['day', 'week', 'month'] = 'day') -> EventCountsResult: ...854def property_counts(self, event: str, property_name: str, *, from_date: str, to_date: str, type: Literal['general', 'unique', 'average'] = 'general', unit: Literal['day', 'week', 'month'] = 'day', values: list[str] | None = None, limit: int | None = None) -> PropertyCountsResult: ...855def frequency(self, *, from_date: str, to_date: str, unit: Literal['day', 'week', 'month'] = 'day', addiction_unit: Literal['hour', 'day'] = 'hour', event: str | None = None, where: str | None = None) -> FrequencyResult: ...856def activity_feed(self, distinct_ids: list[str], *, from_date: str | None = None, to_date: str | None = None) -> ActivityFeedResult: ...857def query_saved_report(self, bookmark_id: int, *, bookmark_type: Literal['insights', 'funnels', 'retention', 'flows'] = 'insights', from_date: str | None = None, to_date: str | None = None) -> SavedReportResult: ...858def query_saved_flows(self, bookmark_id: int) -> FlowsResult: ...859def segmentation_numeric(self, event: str, *, from_date: str, to_date: str, on: str, unit: Literal['hour', 'day'] = 'day', where: str | None = None, type: Literal['general', 'unique', 'average'] = 'general') -> NumericBucketResult: ...860def segmentation_sum(self, event: str, *, from_date: str, to_date: str, on: str, unit: Literal['hour', 'day'] = 'day', where: str | None = None) -> NumericSumResult: ...861def segmentation_average(self, event: str, *, from_date: str, to_date: str, on: str, unit: Literal['hour', 'day'] = 'day', where: str | None = None) -> NumericAverageResult: ...862```863864### Entity CRUD (App API)865866All entity methods require a workspace ID. Use `python3 $SKILL_DIR/scripts/help.py Workspace.<method>` for full signatures and parameter types.867User Guide: `WebFetch(url="https://mixpanel.github.io/mixpanel-headless/guide/entity-management/index.md")`868869#### Dashboard (→ `Dashboard`)870871`list_dashboards`, `create_dashboard`, `get_dashboard`, `update_dashboard`, `delete_dashboard`, `bulk_delete_dashboards`, `favorite_dashboard`, `unfavorite_dashboard`, `pin_dashboard`, `unpin_dashboard`, `add_report_to_dashboard`, `remove_report_from_dashboard`, `update_text_card`, `update_report_link`872873**Blueprints:** `list_blueprint_templates` → `list[BlueprintTemplate]`, `create_blueprint`, `get_blueprint_config`, `update_blueprint_cohorts`, `finalize_blueprint`, `create_rca_dashboard`874875**Helpers:** `get_bookmark_dashboard_ids` → `list[int]`, `get_dashboard_erf` → `dict`876877#### Bookmark / Report (→ `Bookmark`)878879`list_bookmarks_v2`, `create_bookmark`, `get_bookmark`, `update_bookmark`, `delete_bookmark`, `bulk_delete_bookmarks`, `bulk_update_bookmarks`, `bookmark_linked_dashboard_ids` → `list[int]`, `get_bookmark_history` → `BookmarkHistoryResponse`880881#### Cohort (→ `Cohort`)882883`list_cohorts_full`, `get_cohort`, `create_cohort`, `update_cohort`, `delete_cohort`, `bulk_delete_cohorts`, `bulk_update_cohorts`884885#### Feature Flag (→ `FeatureFlag`)886887`list_feature_flags`, `create_feature_flag`, `get_feature_flag`, `update_feature_flag`, `delete_feature_flag`, `archive_feature_flag`, `restore_feature_flag`, `duplicate_feature_flag`, `set_flag_test_users`, `get_flag_history` → `FlagHistoryResponse`, `get_flag_limits` → `FlagLimitsResponse`888889#### Experiment (→ `Experiment`)890891`list_experiments`, `create_experiment`, `get_experiment`, `update_experiment`, `delete_experiment`, `launch_experiment`, `conclude_experiment`, `decide_experiment`, `archive_experiment`, `restore_experiment`, `duplicate_experiment`, `list_erf_experiments` → `list[dict]`892893#### Alert (→ `CustomAlert`)894895`list_alerts`, `create_alert`, `get_alert`, `update_alert`, `delete_alert`, `bulk_delete_alerts`, `get_alert_count` → `AlertCount`, `get_alert_history` → `AlertHistoryResponse`, `test_alert`, `get_alert_screenshot_url`, `validate_alerts_for_bookmark`896897#### Annotation (→ `Annotation`)898899`list_annotations`, `create_annotation`, `get_annotation`, `update_annotation`, `delete_annotation`, `list_annotation_tags` → `list[AnnotationTag]`, `create_annotation_tag`900901#### Webhook (→ `ProjectWebhook`)902903`list_webhooks`, `create_webhook`, `update_webhook`, `delete_webhook`, `test_webhook`904905#### Lexicon & Data Governance906907**Event/Property Definitions:** `get_event_definitions`, `update_event_definition`, `delete_event_definition`, `bulk_update_event_definitions`, `get_property_definitions`, `update_property_definition`, `bulk_update_property_definitions`, `export_lexicon`, `get_event_history`, `get_property_history`908909**Tags:** `list_lexicon_tags`, `create_lexicon_tag`, `update_lexicon_tag`, `delete_lexicon_tag`910911**Drop Filters:** `list_drop_filters`, `create_drop_filter`, `update_drop_filter`, `delete_drop_filter`, `get_drop_filter_limits`912913**Custom Properties:** `list_custom_properties`, `create_custom_property`, `get_custom_property`, `update_custom_property`, `delete_custom_property`, `validate_custom_property`914915**Custom Events:** `list_custom_events`, `update_custom_event`, `delete_custom_event`916917**Lookup Tables:** `list_lookup_tables`, `upload_lookup_table`, `download_lookup_table`, `update_lookup_table`, `delete_lookup_tables`918919**Schema Registry:** `list_schema_registry`, `create_schema`, `update_schema`, `create_schemas_bulk`, `update_schemas_bulk`, `delete_schemas`920921**Schema Enforcement:** `get_schema_enforcement`, `init_schema_enforcement`, `update_schema_enforcement`, `replace_schema_enforcement`, `delete_schema_enforcement`922923**Audit & Monitoring:** `run_audit`, `run_audit_events_only`, `list_data_volume_anomalies`, `update_anomaly`, `bulk_update_anomalies`924925**Data Deletion:** `list_deletion_requests`, `create_deletion_request`, `cancel_deletion_request`, `preview_deletion_filters`926927**Other:** `get_tracking_metadata`928929### Business Context930931Read and write the markdown documentation that grounds AI assistants in your organization's structure and goals, exposed as a typed Python API.932933Two scopes — `level="organization"` (shared across the whole org) and `level="project"` (per-project). 50,000-character cap enforced **client-side before any HTTP call** so oversize input fails fast. Org-level operations auto-resolve `organization_id` from the cached `/me` response; pass `organization_id=N` to override.934935Run `python3 $SKILL_DIR/scripts/help.py search business_context` to see all four methods, two types, and one exception.936937```python938from mixpanel_headless import BUSINESS_CONTEXT_MAX_CHARS # 50_000939940# Read941project_ctx = ws.get_business_context(level="project")942org_ctx = ws.get_business_context(level="organization") # auto-resolves org_id943explicit = ws.get_business_context(level="organization", organization_id=42)944945# Read both at once (single round-trip via /business-context/chain)946chain = ws.get_business_context_chain()947print(chain.organization.content)948print(chain.project.content)949950# Write (full-replace; pass "" to clear, or use clear_business_context())951ws.set_business_context("# About Acme\n…", level="project")952ws.set_business_context("# Org-wide standards", level="organization")953ws.clear_business_context(level="project")954955# All return BusinessContext with: level, content, organization_id, project_id956# Plus convenience .is_empty and .character_count properties (Python only)957print(f"{project_ctx.character_count}/{BUSINESS_CONTEXT_MAX_CHARS} chars; "958 f"empty={project_ctx.is_empty}")959```960961**When to reach for this:**962963- User asks "what's the business context for this project/org?" → `get_business_context_chain()`964- User wants to version-control project context as a `.md` file → `ws.set_business_context(Path("ctx.md").read_text(), level="project")` in CI965- User asks to "audit which projects have AI context configured" → iterate `ws.projects()` + `ws.use(project=...)` + `ws.get_business_context(level="project")` and check `.is_empty`966- User asks to seed a new project from the org default → `chain = ws.get_business_context_chain(); ws.set_business_context(chain.organization.content, level="project")`967968**Permissions:** project-scope reads need any project access; project-scope writes need `edit_project_info` on the project. Org-scope writes need `edit_project_info` at the org level (typically OAuth, not service account). The `BusinessContextValidationError` exception is raised client-side BEFORE any HTTP call when content exceeds 50,000 chars, so use it to detect oversize input without burning a round-trip.969970User Guide: `WebFetch(url="https://mixpanel.github.io/mixpanel-headless/guide/business-context/index.md")`971972## Key Types973974Run `python3 $SKILL_DIR/scripts/help.py types` for the full list of all types. Use `help.py <TypeName>` for fields, constructors, and enum values.975Full reference: `WebFetch(url="https://mixpanel.github.io/mixpanel-headless/api/types/index.md")`976977| Type | Purpose |978|------|---------|979| `Filter` | Property filter conditions (`.equals()`, `.contains()`, `.in_cohort()`, etc.) |980| `GroupBy` | Property breakdown with optional bucketing |981| `Formula` | Calculated metric expression referencing events by position (A, B, C...) |982| `Metric` | Event with per-event math/aggregation settings |983| `CohortMetric` | Track cohort size over time as an event metric |984| `FunnelStep` | Funnel step with per-step filters, labels, ordering |985| `Exclusion` | Event to exclude between funnel steps |986| `HoldingConstant` | Property to hold constant across funnel steps |987| `RetentionEvent` | Retention event with per-event filters |988| `FlowStep` | Flow anchor event with per-step forward/reverse configuration |989| `TimeComparison` | Period-over-period comparison (`.relative("month")`, `.absolute_start(...)`) |990| `FrequencyBreakdown` | Break down by how often users performed an event |991| `FrequencyFilter` | Filter by how often users performed an event |992| `CohortBreakdown` | Break down results by cohort membership |993| `CohortDefinition` | Inline cohort definition for user queries |994| `CohortCriteria` | Atomic condition for cohort membership |995| `CustomPropertyRef` | Reference to a persisted custom property by ID |996| `InlineCustomProperty` | Ephemeral computed property defined by formula |997998**Aggregation enums** (use `help.py <EnumName>` to see all values):9991000| Enum | Used by | Common values |1001|------|---------|---------------|1002| `MathType` | `query()` | total, unique, dau, average, sum, min, max, percentile, sessions |1003| `FunnelMathType` | `query_funnel()` | conversion_rate_unique, conversion_rate_total, average, median |1004| `RetentionMathType` | `query_retention()` | retention_rate, retention_count |10051006## Statistical Analysis — numpy, scipy10071008All query results produce pandas DataFrames, which integrate directly with numpy and scipy:10091010```python1011import numpy as np1012from scipy import stats10131014# Compare two segments1015a = result.df[result.df["platform"] == "iOS"]["count"]1016b = result.df[result.df["platform"] == "Android"]["count"]1017t_stat, p_value = stats.ttest_ind(a, b)1018cohens_d = (a.mean() - b.mean()) / np.sqrt((a.std()**2 + b.std()**2) / 2)10191020# Useful scipy.stats tests: ttest_ind, mannwhitneyu, chi2_contingency, pearsonr, spearmanr1021# Useful numpy: np.percentile, np.corrcoef, np.polyfit (trend lines)1022```10231024## Visualization — matplotlib, seaborn10251026Save charts to files for the user. Always use a non-interactive backend:10271028```python1029import matplotlib1030matplotlib.use("Agg")1031import matplotlib.pyplot as plt1032import seaborn as sns10331034fig, ax = plt.subplots(figsize=(10, 5))1035result.df.plot(x="date", y="count", ax=ax)1036ax.set_title("Daily Logins")1037fig.savefig("chart.png", dpi=150, bbox_inches="tight")1038plt.close(fig)10391040# seaborn: sns.lineplot, sns.barplot, sns.heatmap (for retention matrices)1041# Multi-panel: fig, axes = plt.subplots(2, 2) for dashboard-style layouts1042```10431044## Exceptions10451046Full reference: `WebFetch(url="https://mixpanel.github.io/mixpanel-headless/api/exceptions/index.md")`10471048| Exception | When |1049|-----------|------|1050| `MixpanelHeadlessError` | Base for all errors |1051| `ConfigError` | No credentials resolved |1052| `AccountNotFoundError` | Named account doesn't exist |1053| `AuthenticationError` | Invalid credentials (401) |1054| `QueryError` | Invalid query parameters (400) |1055| `BookmarkValidationError` | Params failed validation |1056| `RateLimitError` | Rate limit exceeded (429) |1057| `ServerError` | Mixpanel server error (5xx) |1058| `WorkspaceScopeError` | Workspace resolution error (also raised when org_id can't be auto-resolved for `level="organization"` business-context calls) |1059| `DateRangeTooLargeError` | Date range exceeds API maximum |1060| `OAuthError` | OAuth flow error |1061| `BusinessContextValidationError` | Business context content exceeds 50,000 chars (client-side, before HTTP) |
Run npx get-skill add concertonotes/mixpanelyst in your terminal (requires Node.js), paste this page's agent-chat prompt into Claude, Cursor, or any MCP-connected agent, or download the SKILL.md file and copy it into your agent's skills directory.
This skill should be used when the user asks about Mixpanel product analytics, event data, funnel analysis, retention curves, cohort analysis, segmentation queries, user behavior, conversion rates, churn, DAU/MAU, ARPU, revenue metrics, feature adoption, A/B test results, user paths, flow analysis, or any request to query, explore, visualize, or analyze Mixpanel data using Python. Also use when the user asks to read, write, or manage Mixpanel "business context" — the markdown documentation that grounds AI assistants in an organization's structure and goals. It is listed under Data & Analytics on SkillMD.
This skill has not completed SkillMD's automated safety review yet. Independent scanners report: SkillSpector: CAUTION, Skill Scanner: PASS. Capability flags: executes scripts, makes network calls. SkillMD never runs a skill's scripts for you; review the SKILL.md before installing.
This skill is tagged as working with Claude Code, Claude.ai, OpenAI Codex. SKILL.md is an open format, so most agents that read a skills directory can load it too.
Yes. Installing skills from SkillMD is free, and the skill stays under its author's original license.
ConcertoNotes (@concertonotes) published this skill. Their other Agent Skills are listed on their SkillMD profile.