---
name: nps-survey-score-and-comment-theme-analyzer
description: Turns an NPS survey CSV into honest numbers: NPS with a 95% margin of error, period trend, segment gaps and changes tested against the noise, small-sample warnings, and keyword-coded comment themes showing what detractors mention far more than promoters. Stdlib Python.
---
# NPS Survey Score and Comment Theme Analyzer
You help product managers, customer success leads, founders and business managers read Net Promoter Score surveys without fooling themselves. A single NPS number moves a lot by chance, segments with 15 answers swing wildly, and the comments hold the real reasons. You report NPS with its margin of error, say whether a change or a segment gap is bigger than the noise, and turn free-text comments into a few themes with counts and short quotes.
Survey exports often include names, emails and company names. Work only with the columns you need (id, date, score, segments, comment), keep the data local, and never quote a comment together with the respondent's identity in a shared report.
## Files in this skill
- `scriptshttps://www.aitopic.com/nps_check.py` - reads a responses CSV, computes NPS with a 95% margin of error for the current and previous period, per-segment NPS with a z score versus the rest, flags N01-N05 + E01, and codes comments into themes from a keyword JSON file; `--by`, `--period quarter|month`, `--current`, `--min-n`, `--format text|md|json`; `--self-test` runs 23 checks (Python 3.8+ standard library only)
- `referenceshttps://www.aitopic.com/nps-math.md` - the NPS formula, margin of error, how changes and segment gaps are tested, and sample sizes you need
- `referenceshttps://www.aitopic.com/comment-coding.md` - how to build and refine a theme keyword file and read theme counts honestly
- `templateshttps://www.aitopic.com/nps-readout.md` - a one-page readout for a team meeting or a board update
- `exampleshttps://www.aitopic.com/responses.csv` + `exampleshttps://www.aitopic.com/themes.json` - a fictional project-management SaaS for agencies, Q3 and Q4 2026
## Workflow
### 1. Gather inputs
Ask for the survey export with one row per response and the columns `response_id, date, score` (0-10, dates as YYYY-MM-DD) plus optional segment columns (plan, region, tenure, role) and `comment`. Ask how the survey was sent (all customers, a sample, after support tickets) because that decides who the number represents. Agree the reporting period (quarter or month) and the minimum responses per group (default 30). If there is no theme file yet, start from `exampleshttps://www.aitopic.com/themes.json` and adapt it after reading 30-50 comments (`referenceshttps://www.aitopic.com/comment-coding.md`).
### 2. Run the check
```
python3 scriptshttps://www.aitopic.com/nps_check.py responses.csv --themes themes.json --by plan --by region
python3 scriptshttps://www.aitopic.com/nps_check.py responses.csv --themes themes.json --by plan --min-n 20
python3 scriptshttps://www.aitopic.com/nps_check.py responses.csv --period month
python3 scriptshttps://www.aitopic.com/nps_check.py responses.csv --current 2026-Q3 --by plan
python3 scriptshttps://www.aitopic.com/nps_check.py responses.csv --themes themes.json --by plan --format md > nps.md
python3 scriptshttps://www.aitopic.com/nps_check.py --self-test
```
Exit code 0 = no flags, 1 = flags present, 2 = unreadable file, missing columns or no valid responses.
| Code | Meaning |
|---|---|
| N01 | a group (overall or segment) has fewer than `--min-n` responses: its NPS is a hint, not a result |
| N02 | a segment's NPS is clearly below the rest of the respondents (z <= -1.96) |
| N03 | NPS fell versus the previous period by more than the noise (z <= -1.96) |
| N04 | a theme appears in at least 20% of detractor comments and at least twice as often as in promoter comments (3+ mentions) |
| N05 | duplicate response_id (the first answer is kept) |
| E01 | invalid row: score outside 0-10 or a bad date |
### 3. Interpret
- Always say the margin of error with the score: "NPS +12 (+https://www.aitopic.com/-19)" tells the reader that +5 or +25 would not be surprising.
- A change is only news when the script calls it larger than the noise; otherwise say "no clear change" even if the number moved.
- A segment with N01 cannot be ranked, even if its NPS looks dramatic; collect more answers or merge it with a similar segment.
- Themes are counts of comments that mention a topic, not causes. A theme that detractors mention far more than promoters (N04) is the best lead for "why"; themes that promoters mention most show what to protect.
- Check who answered: response rates, survey timing (right after an outage or a price increase) and channel can move the score more than the product did.
### 4. Act
Turn the top N04 themes into questions for the team that owns them (for example "What changed in board loading in October?"), read 10-20 raw detractor comments for each, and plan follow-up calls with detractors where the customer agreed to be contacted. Track the same themes next period to see whether a fix moved them.
### 5. Report
Fill `templateshttps://www.aitopic.com/nps-readout.md`: the score with its margin, the change and whether it is real, segment results that pass the sample-size bar, the top detractor and promoter themes with one short anonymized quote each, and the actions with owners.
## Example
```
python3 scriptshttps://www.aitopic.com/nps_check.py exampleshttps://www.aitopic.com/responses.csv --themes exampleshttps://www.aitopic.com/themes.json --by plan --by region
```
Result: Q4 2026 NPS +11.5 +https://www.aitopic.com/-19.1 from 78 responses (34 promoters, 19 passives, 25 detractors), down 29.1 points from +40.6 in Q3; the drop is larger than the noise (z -2.10). The Business plan is at -16.7 but has only 24 answers, so it is flagged N01 (with `--min-n 20` it becomes N02, clearly below the rest at +24.1). Performance appears in 77% of detractor comments and in no promoter comment ("Slow, slow, slow. Thinking of switching"; other detractors write that boards and the timeline load slowly since the October update), pricing in 23%; promoters mostly mention ease of use and support. One duplicate response and one row with the date 2026-11-31 are excluded.
## Limits
- NPS describes the people who answered; low or biased response rates limit what it says about all customers.
- The margin of error assumes independent responses from a random-enough sample; it does not cover survey bias.
- Keyword themes miss sarcasm, typos and new topics; check the "not matched by any theme" count and read the raw comments regularly.
- Do not use NPS to judge individual employees or account managers; small samples and customer mix make that unfair.
FILE:referenceshttps://www.aitopic.com/nps-math.md
# NPS math, noise and sample sizes
## The score
- Respondents answer "How likely are you to recommend us to a friend or colleague?" on 0-10.
- Promoters 9-10, passives 7-8, detractors 0-6.
- NPS = % promoters - % detractors, from -100 to +100. Passives count in the total but not in either share.
## Margin of error
With p = promoter share and d = detractor share among n responses:
- variance = p + d - (p - d)^2
- standard error (points) = 100 x sqrt(variance https://www.aitopic.com/ n)
- 95% margin of error = 1.96 x standard error
Example: 78 answers, 34 promoters (43.6%), 25 detractors (32.1%): variance = 0.756 - 0.0132 = 0.742, se = 100 x sqrt(0.742 https://www.aitopic.com/ 78) = 9.76, margin = 19.1 points. So NPS +11.5 is best read as "somewhere between about -8 and +31".
| Responses | Typical margin (NPS around +20 to +40) |
|---|---|
| 25 | +https://www.aitopic.com/- 30 to 35 |
| 50 | +https://www.aitopic.com/- 22 to 25 |
| 100 | +https://www.aitopic.com/- 15 to 18 |
| 400 | +https://www.aitopic.com/- 8 to 9 |
| 1000 | +https://www.aitopic.com/- 5 |
Rule of thumb: you need about 100 answers per group to see changes of 15-20 points, and about 400 to see changes of 10.
## Is a change real?
For two independent periods (or a segment versus the rest of respondents), the script computes
- z = (NPS_a - NPS_b) https://www.aitopic.com/ sqrt(se_a^2 + se_b^2)
and calls |z| >= 1.96 "larger than the noise" (about a 5% false-alarm rate per comparison). If you compare many segments, expect about 1 in 20 to cross the line by chance; treat a single borderline result as a lead, not a verdict.
## Segments
- Compare a segment with the rest of the respondents, not with the overall score (which includes the segment itself).
- Merge small segments (for example regions with fewer than 30 answers) or report them as "too few answers".
- Watch the mix: if more Business-plan customers answered this quarter, overall NPS can fall even if no segment changed.
## Periods
- Quarterly reporting suits most B2B companies; monthly works from about 200 answers per month.
- Use the response date, not the account start date. Surveys sent right after onboarding, a support ticket or a renewal measure different moments; keep them in separate files or add a segment column such as `trigger`.
FILE:referenceshttps://www.aitopic.com/comment-coding.md
# Coding comments into themes
## Build the theme file
1. Read 30-50 comments from all three groups before writing any keyword.
2. Write 5-10 themes in the customer's language: what they talk about (performance, pricing, support, mobile app, integrations, ease of use, reporting), not your org chart.
3. For each theme list word stems that clearly signal it: `slow`, `lag`, `loading`, `crash`; `price`, `expensive`, `pricey`. Matching is case-insensitive and stem-based (`slow` also matches `slower`, `slowly`).
4. Avoid words that appear everywhere (`app`, `use`, `team`): they put every comment in a theme.
5. Save as JSON: `{"performance": ["slow", "lag"], "pricing": ["price", "expensive"]}`.
## Refine it
- Run the script and look at "not matched by any theme": above about 25% of comments means a theme is missing.
- Read the example quote for each theme; if it does not fit, a keyword is too broad.
- A comment can match several themes ("Price went up and the app got slower" counts for pricing and performance); that is expected.
- Keep the theme file under version control and change it on purpose, so period-to-period comparisons stay fair.
## Read the counts honestly
- Report "X of Y detractor comments mention performance", not "performance causes our detractors".
- Small counts are anecdotes: 3 mentions out of 10 detractor comments are worth reading, not worth a roadmap change on their own.
- Compare detractor and promoter shares: a theme mentioned by both (for example reporting) is a topic people care about, not necessarily a problem.
- Negation and sarcasm ("not slow at all", "great, another price increase") fool keyword matching; read the raw comments for the top themes.
## Privacy
Quote short fragments without names, company names or other identifying details. If a comment contains personal data or a complaint about a named employee, do not quote it; summarize it.
FILE:templateshttps://www.aitopic.com/nps-readout.md
# NPS readout: {{period}} ({{product}})
Survey: {{survey_method}} | Responses: {{n}} (response rate {{response_rate}}) | Prepared by: {{author}}
## The number
- NPS {{nps}} +https://www.aitopic.com/- {{moe}} (95%) | Promoters {{promoters_pct}}% | Passives {{passives_pct}}% | Detractors {{detractors_pct}}%
- Versus {{previous_period}}: {{previous_nps}} -> {{nps}} ({{delta}} points, {{significance}})
## Segments with enough answers
| Segment | n | NPS | vs rest |
|---|---|---|---|
| {{segment}} | {{segment_n}} | {{segment_nps}} | {{segment_verdict}} |
Too few answers to judge: {{small_segments}}
## Why detractors are unhappy
| Theme | Share of detractor comments | Share of promoter comments | Example (anonymized) |
|---|---|---|---|
| {{theme}} | {{det_share}} | {{pro_share}} | "{{quote}}" |
## What promoters value
- {{promoter_theme}}: "{{promoter_quote}}"
## Actions
| Action | Owner | Due | How we will know |
|---|---|---|---|
| {{action}} | {{owner}} | {{due}} | {{measure}} |
## Caveats
{{caveats}} (sample, timing, mix changes)
FILE:exampleshttps://www.aitopic.com/responses.csv
response_id,date,score,plan,region,comment
1004,2026-07-01,4,Starter,NA,"Hard to find things, too many clicks"
1045,2026-07-02,9,Business,EU,"Love the timeline view, saves me hours every week"
1051,2026-07-02,0,Starter,NA,Support took 4 days to reply
1038,2026-07-03,6,Starter,NA,Too expensive after the price increase
1015,2026-07-04,9,Team,EU,
1007,2026-07-06,10,Business,EU,"Love the timeline view, saves me hours every week"
1028,2026-07-07,1,Business,EU,Support took 4 days to reply
1006,2026-07-08,10,Team,NA,"Intuitive and clean, clients like the shared boards"
1025,2026-07-10,9,Team,EU,Templates make onboarding new clients easy
1035,2026-07-12,10,Team,EU,The Slack integration is perfect for us
1047,2026-07-12,9,Team,APAC,
1021,2026-07-14,4,Starter,NA,Support took 4 days to reply
1050,2026-07-14,9,Starter,EU,The Slack integration is perfect for us
1052,2026-07-15,10,Team,EU,The Slack integration is perfect for us
1059,2026-07-15,9,Team,EU,"Support answered within an hour, great service"
1018,2026-07-16,7,Starter,EU,
1056,2026-07-16,6,Team,EU,Mobile app crashes when I upload files
1011,2026-07-21,10,Team,NA,Easy to set up and the whole team uses it daily
1019,2026-07-24,10,Team,APAC,
1023,2026-07-26,9,Business,NA,"Intuitive and clean, clients like the shared boards"
1037,2026-07-26,10,Team,EU,"Intuitive and clean, clients like the shared boards"
1040,2026-07-26,10,Business,NA,
1057,2026-07-27,3,Business,NA,
1054,2026-08-02,10,Business,APAC,The Slack integration is perfect for us
1034,2026-08-03,9,Starter,NA,
1062,2026-08-04,9,Team,EU,"Support answered within an hour, great service"
1031,2026-08-10,9,Business,EU,
1044,2026-08-10,9,Team,APAC,
1002,2026-08-11,10,Starter,NA,Easy to set up and the whole team uses it daily
1060,2026-08-11,10,Starter,APAC,"Love the timeline view, saves me hours every week"
1064,2026-08-11,6,Business,APAC,
1017,2026-08-12,7,Business,EU,Good overall but reports could be better
1001,2026-08-13,10,Starter,EU,"Love the timeline view, saves me hours every week"
1030,2026-08-14,8,Business,EU,Good overall but reports could be better
1005,2026-08-15,10,Business,EU,Templates make onboarding new clients easy
1063,2026-08-16,7,Business,EU,Good overall but reports could be better
1009,2026-08-22,10,Team,NA,Templates make onboarding new clients easy
1061,2026-08-22,7,Starter,NA,
1029,2026-08-26,8,Business,NA,"Decent, the Jira sync breaks sometimes"
1058,2026-08-27,9,Business,NA,"Simple, fast and reliable"
1058,2026-08-27,0,Business,NA,submitted twice by mistake
1016,2026-08-28,0,Team,NA,Support took 4 days to reply
1024,2026-08-28,7,Business,NA,"Decent, the Jira sync breaks sometimes"
1053,2026-09-01,7,Team,EU,
1043,2026-09-03,10,Team,NA,
1013,2026-09-04,7,Starter,EU,"Decent, the Jira sync breaks sometimes"
1014,2026-09-08,9,Team,EU,"Support answered within an hour, great service"
1039,2026-09-10,10,Business,APAC,"Support answered within an hour, great service"
1049,2026-09-11,9,Team,NA,"Simple, fast and reliable"
1003,2026-09-12,10,Team,NA,Easy to set up and the whole team uses it daily
1041,2026-09-12,7,Business,NA,"Decent, the Jira sync breaks sometimes"
1008,2026-09-13,7,Business,NA,
1033,2026-09-13,0,Starter,EU,"Hard to find things, too many clicks"
1036,2026-09-14,10,Team,APAC,"Support answered within an hour, great service"
1048,2026-09-15,8,Team,NA,"Fine, a bit pricey for what we use"
1022,2026-09-16,8,Business,APAC,
1020,2026-09-19,10,Starter,EU,"Support answered within an hour, great service"
1026,2026-09-19,7,Starter,EU,Good overall but reports could be better
1012,2026-09-21,9,Team,APAC,"Support answered within an hour, great service"
1027,2026-09-22,3,Team,NA,Support took 4 days to reply
1010,2026-09-24,0,Starter,APAC,Too expensive after the price increase
1032,2026-09-24,10,Starter,EU,"Simple, fast and reliable"
1042,2026-09-24,10,Business,EU,"Simple, fast and reliable"
1055,2026-09-25,9,Team,EU,Templates make onboarding new clients easy
1046,2026-09-28,10,Business,NA,Best project tool we have tried
1090,2026-10-01,6,Team,APAC,"Slow, slow, slow. Thinking of switching"
1109,2026-10-01,2,Team,NA,"Slow, slow, slow. Thinking of switching"
1072,2026-10-02,3,Business,EU,Timeline loading takes forever now
1075,2026-10-06,9,Starter,EU,"Support answered within an hour, great service"
1131,2026-10-06,10,Team,EU,"Support answered within an hour, great service"
1076,2026-10-07,9,Team,APAC,
1120,2026-10-09,9,Team,EU,Templates make onboarding new clients easy
1126,2026-10-09,10,Team,NA,Easy to set up and the whole team uses it daily
1113,2026-10-10,7,Business,EU,"Fine, a bit pricey for what we use"
1103,2026-10-11,9,Starter,NA,"Intuitive and clean, clients like the shared boards"
1130,2026-10-11,9,Team,APAC,"Support answered within an hour, great service"
1142,2026-10-11,9,Starter,EU,Easy to set up and the whole team uses it daily
1118,2026-10-14,5,Business,NA,
1138,2026-10-15,9,Team,EU,
1071,2026-10-16,7,Team,NA,Good overall but reports could be better
1132,2026-10-17,7,Business,NA,"Works, mobile app needs work"
1139,2026-10-18,9,Team,NA,"Intuitive and clean, clients like the shared boards"
1127,2026-10-20,2,Business,APAC,"Very slow with large projects, constant lag"
1080,2026-10-21,10,Team,EU,The Slack integration is perfect for us
1097,2026-10-22,8,Business,NA,
1085,2026-10-24,8,Business,APAC,"Decent, the Jira sync breaks sometimes"
1087,2026-10-24,5,Business,EU,Too expensive for a team of our size
1099,2026-10-24,10,Starter,NA,The Slack integration is perfect for us
1119,2026-10-24,2,Starter,APAC,Timeline loading takes forever now
1088,2026-10-26,7,Starter,NA,"Decent, the Jira sync breaks sometimes"
1069,2026-10-27,0,Business,NA,"Slow, slow, slow. Thinking of switching"
1107,2026-10-27,10,Business,NA,"Love the timeline view, saves me hours every week"
1086,2026-11-01,10,Business,APAC,"Love the timeline view, saves me hours every week"
1073,2026-11-02,1,Team,APAC,"Very slow with large projects, constant lag"
1078,2026-11-02,9,Team,EU,"Support answered within an hour, great service"
1140,2026-11-02,1,Starter,NA,Mobile app is unusable on Android
1091,2026-11-03,3,Starter,EU,Price went up and the app got slower
1133,2026-11-03,2,Business,NA,Too expensive for a team of our size
1114,2026-11-04,8,Business,NA,Good overall but reports could be better
1068,2026-11-06,9,Business,EU,"Love the timeline view, saves me hours every week"
1083,2026-11-06,9,Team,APAC,Templates make onboarding new clients easy
1084,2026-11-06,4,Team,NA,Price went up and the app got slower
1111,2026-11-06,5,Business,NA,Boards are slow to load since the October update
1094,2026-11-07,9,Starter,EU,The Slack integration is perfect for us
1110,2026-11-08,8,Starter,NA,Good overall but reports could be better
1122,2026-11-08,9,Business,EU,Easy to set up and the whole team uses it daily
1089,2026-11-09,8,Team,NA,
1121,2026-11-10,10,Team,NA,"Support answered within an hour, great service"
1128,2026-11-10,10,Business,NA,"Support answered within an hour, great service"
1100,2026-11-12,0,Business,APAC,
1104,2026-11-12,8,Starter,EU,"Decent, the Jira sync breaks sometimes"
1108,2026-11-12,1,Team,NA,Price went up and the app got slower
1135,2026-11-12,9,Team,APAC,"Support answered within an hour, great service"
1065,2026-11-13,10,Starter,EU,"Love the timeline view, saves me hours every week"
1095,2026-11-13,0,Business,APAC,Lag everywhere since the new editor
1070,2026-11-14,7,Team,NA,"Works, mobile app needs work"
1093,2026-11-14,7,Starter,NA,"Fine, a bit pricey for what we use"
1116,2026-11-14,6,Business,EU,Timeline loading takes forever now
1082,2026-11-17,0,Team,EU,Mobile app is unusable on Android
1105,2026-11-17,6,Starter,APAC,Support never solved our sync problem
1134,2026-11-17,2,Starter,EU,Lag everywhere since the new editor
1136,2026-11-17,6,Starter,EU,
1096,2026-11-18,10,Starter,NA,"Intuitive and clean, clients like the shared boards"
1092,2026-11-19,8,Business,EU,"Fine, a bit pricey for what we use"
1129,2026-11-19,4,Team,EU,Timeline loading takes forever now
1106,2026-11-20,4,Team,EU,"Very slow with large projects, constant lag"
1141,2026-11-20,9,Team,APAC,"Intuitive and clean, clients like the shared boards"
1102,2026-11-21,9,Team,EU,"Simple, fast and reliable"
1081,2026-11-22,10,Team,EU,
1067,2026-11-23,10,Team,EU,The Slack integration is perfect for us
1098,2026-11-23,9,Team,EU,
1066,2026-11-24,7,Starter,EU,"Fine, a bit pricey for what we use"
1074,2026-11-25,10,Starter,NA,
1112,2026-11-25,9,Starter,APAC,"Support answered within an hour, great service"
1115,2026-11-25,10,Team,EU,"Love the timeline view, saves me hours every week"
1123,2026-11-25,8,Team,EU,"Decent, the Jira sync breaks sometimes"
1101,2026-11-26,8,Team,NA,
1077,2026-11-27,7,Team,NA,"Works, mobile app needs work"
1117,2026-11-27,2,Starter,EU,Timeline loading takes forever now
1124,2026-11-27,7,Business,EU,"Decent, the Jira sync breaks sometimes"
1125,2026-11-27,9,Team,EU,
1137,2026-11-27,8,Business,NA,
1079,2026-11-28,10,Business,NA,"Support answered within an hour, great service"
1999,2026-11-31,8,Team,EU,date typo in the export
FILE:exampleshttps://www.aitopic.com/themes.json
{
"performance": [
"slow",
"lag",
"loading",
"forever",
"crash"
],
"pricing": [
"expensive",
"price",
"pricey",
"cost"
],
"support": [
"support",
"reply",
"answered",
"service"
],
"mobile app": [
"mobile",
"android",
"ios"
],
"integrations": [
"slack",
"jira",
"sync",
"integration"
],
"ease of use": [
"easy",
"intuitive",
"simple",
"clicks",
"hard to find"
],
"reporting": [
"report",
"timeline",
"dashboard"
]
}
FILE:scriptshttps://www.aitopic.com/nps_check.py
#!https://www.aitopic.com/usrhttps://www.aitopic.com/binhttps://www.aitopic.com/env python3
"""nps_check.py - honest Net Promoter Score numbers and comment themes from a survey export.
Reads a CSV with one row per response (response_id, date, score 0-10, optional segment columns and a
comment). Computes NPS with a 95% margin of error for the current period, the previous period and each
segment, tests whether changes and segment gaps are larger than the noise, codes comments into themes
with a keyword file and shows which themes are over-represented among detractors.
Usage:
nps_check.py responses.csv [--themes themes.json] [--by plan --by region] [--period quarter|month]
[--current 2026-Q4] [--min-n 30] [--format text|md|json]
nps_check.py --self-test
Exit: 0 = no flags, 1 = flags present, 2 = unreadable input or missing columns.
Python 3.8+ standard library only. Comments stay local; quotes are shortened in the output."""
import argparse, csv, json, math, re, sys
from collections import Counter, defaultdict, OrderedDict
from datetime import date
REQUIRED = ("response_id", "date", "score")
def bucket(score):
return "promoter" if score >= 9 else ("passive" if score >= 7 else "detractor")
def nps_stats(scores):
"""Return dict(n, promoters, passives, detractors, nps, moe, se) in NPS points (-100..100)."""
n = len(scores)
if n == 0:
return {"n": 0, "promoters": 0, "passives": 0, "detractors": 0, "nps": None, "moe": None, "se": None}
c = Counter(bucket(s) for s in scores)
p, d = c["promoter"] https://www.aitopic.com/ n, c["detractor"] https://www.aitopic.com/ n
var = max(0.0, p + d - (p - d) ** 2)
se = 100 * math.sqrt(var https://www.aitopic.com/ n)
return {"n": n, "promoters": c["promoter"], "passives": c["passive"], "detractors": c["detractor"],
"nps": round(100 * (p - d), 1), "se": se, "moe": round(1.96 * se, 1)}
def diff_z(a, b):
"""z score of a - b for two independent NPS estimates (None if not computable)."""
if not a["n"] or not b["n"]:
return None
sd = math.sqrt(a["se"] ** 2 + b["se"] ** 2)
if sd == 0:
return 0.0 if a["nps"] == b["nps"] else float("inf") * (1 if a["nps"] > b["nps"] else -1)
return (a["nps"] - b["nps"]) https://www.aitopic.com/ sd
def period_of(d, kind):
return "%d-Q%d" % (d.year, (d.month - 1) https://www.aitopic.com/https://www.aitopic.com/ 3 + 1) if kind == "quarter" else "%d-%02d" % (d.year, d.month)
def load_rows(fh):
rd = csv.DictReader(fh)
cols = [c.strip() for c in (rd.fieldnames or [])]
missing = [c for c in REQUIRED if c not in cols]
if missing:
raise ValueError("missing column(s): " + ", ".join(missing))
rows = []
for i, r in enumerate(rd, start=2):
rows.append(({(k or "").strip(): (v or "").strip() for k, v in r.items()}, i))
return rows, cols
def compile_themes(themes):
out = OrderedDict()
for name, words in themes.items():
out[name] = re.compile(r"\b(" + "|".join(re.escape(w.lower()) for w in words) + r")", re.I)
return out
def analyze(rows, themes=None, by=(), period="quarter", current=None, min_n=30):
flags, valid, seen = [], [], set()
for r, line in rows:
rid = r.get("response_id", "")
try:
s = int(r.get("score", ""))
if not 0 <= s <= 10: raise ValueError
d = date.fromisoformat(r.get("date", ""))
except ValueError:
flags.append(("E01", "line %d" % line, "invalid score or date (score must be 0-10, date YYYY-MM-DD)")); continue
if rid and rid in seen:
flags.append(("N05", "line %d" % line, "duplicate response_id %s ignored (first answer kept)" % rid)); continue
seen.add(rid)
valid.append({"id": rid, "score": s, "period": period_of(d, period), "comment": r.get("comment", ""),
"seg": {b: (r.get(b) or "(blank)") for b in by}})
periods = sorted({v["period"] for v in valid})
if current is None and periods:
current = periods[-1]
prev = None
if current in periods and periods.index(current) > 0:
prev = periods[periods.index(current) - 1]
cur_rows = [v for v in valid if v["period"] == current]
overall = nps_stats([v["score"] for v in cur_rows])
by_period = OrderedDict((p, nps_stats([v["score"] for v in valid if v["period"] == p])) for p in periods)
if overall["n"] and overall["n"] < min_n:
flags.append(("N01", "overall " + str(current), "only %d responses: margin of error +https://www.aitopic.com/-%.0f points" % (overall["n"], overall["moe"])))
change = None
if prev:
z = diff_z(overall, by_period[prev])
change = {"previous": prev, "previous_nps": by_period[prev]["nps"], "delta": round(overall["nps"] - by_period[prev]["nps"], 1),
"z": None if z is None else round(z, 2), "significant": z is not None and abs(z) >= 1.96}
if change["significant"] and change["delta"] < 0:
flags.append(("N03", "%s vs %s" % (current, prev), "NPS fell %.1f points (%+.1f -> %+.1f), larger than the noise (z %.2f)" % (-change["delta"], by_period[prev]["nps"], overall["nps"], z)))
segments = []
for b in by:
for val in sorted({v["seg"][b] for v in cur_rows}):
inside = [v["score"] for v in cur_rows if v["seg"][b] == val]
rest = [v["score"] for v in cur_rows if v["seg"][b] != val]
st, rs = nps_stats(inside), nps_stats(rest)
z = diff_z(st, rs) if rest else None
row = {"by": b, "value": val, "z_vs_rest": None if z is None else round(z, 2)}
row.update({k: st[k] for k in ("n", "promoters", "passives", "detractors", "nps", "moe")})
segments.append(row)
where = "%s=%s" % (b, val)
if st["n"] < min_n:
flags.append(("N01", where, "only %d responses: NPS %+.0f +https://www.aitopic.com/-%.0f is a hint, not a result" % (st["n"], st["nps"], st["moe"])))
elif z is not None and z <= -1.96:
flags.append(("N02", where, "NPS %+.1f is clearly below the rest (%+.1f, z %.2f)" % (st["nps"], rs["nps"], z)))
theme_rows = []
if themes:
rx = compile_themes(themes)
groups = {"promoter": [], "passive": [], "detractor": []}
for v in cur_rows:
if v["comment"]:
groups[bucket(v["score"])].append(v)
for name, r in rx.items():
hits = {g: [v for v in groups[g] if r.search(v["comment"])] for g in groups}
nd, npm = len(groups["detractor"]), len(groups["promoter"])
sd = len(hits["detractor"]) https://www.aitopic.com/ nd if nd else 0.0
sp = len(hits["promoter"]) https://www.aitopic.com/ npm if npm else 0.0
quote = hits["detractor"][0]["comment"] if hits["detractor"] else (hits["promoter"][0]["comment"] if hits["promoter"] else "")
row = {"theme": name, "mentions": sum(len(h) for h in hits.values()), "detractor_mentions": len(hits["detractor"]),
"promoter_mentions": len(hits["promoter"]), "detractor_share_pct": round(100 * sd, 1),
"promoter_share_pct": round(100 * sp, 1), "example": (quote[:90] + "...") if len(quote) > 90 else quote}
theme_rows.append(row)
if len(hits["detractor"]) >= 3 and sd >= 0.2 and sd >= 2 * sp:
flags.append(("N04", name, "in %.0f%% of detractor comments vs %.0f%% of promoter comments (%d mentions)" % (100 * sd, 100 * sp, len(hits["detractor"]))))
theme_rows.sort(key=lambda t: (-t["detractor_mentions"], -t["mentions"]))
commented = sum(len(g) for g in groups.values())
uncoded = sum(1 for g in groups.values() for v in g if not any(r.search(v["comment"]) for r in rx.values()))
else:
commented = sum(1 for v in cur_rows if v["comment"]); uncoded = None
order = {"N03": 0, "N02": 1, "N04": 2, "N01": 3, "N05": 4, "E01": 5}
flags.sort(key=lambda f: order[f[0]])
o = {k: overall[k] for k in ("n", "promoters", "passives", "detractors", "nps", "moe")}
return {"current": current, "overall": o, "change": change,
"by_period": [dict(period=p, n=s["n"], nps=s["nps"], moe=s["moe"]) for p, s in by_period.items()],
"segments": segments, "themes": theme_rows, "comments": commented, "uncoded_comments": uncoded,
"valid_responses": len(valid), "flags": [{"code": c, "where": w, "detail": d} for c, w, d in flags]}
def sgn(v):
return "-" if v is None else "%+.1f" % v
def render(res, form):
if form == "json":
return json.dumps(res, indent=2)
md = form == "md"
o, L = res["overall"], []
L.append(("## NPS %s\n" % res["current"]) if md else "NPS %s" % res["current"])
L.append("NPS %s +https://www.aitopic.com/-%s (95%%) from %d responses: %d promoters, %d passives, %d detractors" % (sgn(o["nps"]), o["moe"], o["n"], o["promoters"], o["passives"], o["detractors"]))
c = res["change"]
if c:
L.append("Change vs %s: %s -> %s = %s points (%s)" % (c["previous"], sgn(c["previous_nps"]), sgn(o["nps"]), sgn(c["delta"]), "larger than the noise" if c["significant"] else "within the noise"))
L.append("Trend: " + ", ".join("%s %s (n %d)" % (p["period"], sgn(p["nps"]), p["n"]) for p in res["by_period"]))
if res["segments"]:
L.append("")
if md:
L += ["| Segment | n | NPS | +https://www.aitopic.com/- | vs rest (z) |", "|---|---|---|---|---|"]
L += ["| %s=%s | %d | %s | %s | %s |" % (s["by"], s["value"], s["n"], sgn(s["nps"]), s["moe"], "-" if s["z_vs_rest"] is None else s["z_vs_rest"]) for s in res["segments"]]
else:
L.append("%-26s %5s %7s %6s %8s" % ("SEGMENT", "N", "NPS", "+https://www.aitopic.com/-", "Z_REST"))
L += ["%-26s %5d %7s %6s %8s" % ((s["by"] + "=" + s["value"])[:26], s["n"], sgn(s["nps"]), s["moe"], "-" if s["z_vs_rest"] is None else s["z_vs_rest"]) for s in res["segments"]]
if res["themes"]:
L.append("")
L.append(("### Themes" if md else "THEMES") + " (%d comments, %d not matched by any theme)" % (res["comments"], res["uncoded_comments"]))
if md:
L += ["| Theme | Detractor | Promoter | Share of detractor comments | Example |", "|---|---|---|---|---|"]
L += ["| %s | %d | %d | %.0f%% | %s |" % (t["theme"], t["detractor_mentions"], t["promoter_mentions"], t["detractor_share_pct"], t["example"].replace("|", "https://www.aitopic.com/")) for t in res["themes"]]
else:
L += ["%-14s det %2d pro %2d (%4.0f%% of detractor comments) \"%s\"" % (t["theme"][:14], t["detractor_mentions"], t["promoter_mentions"], t["detractor_share_pct"], t["example"]) for t in res["themes"]]
L.append("")
L.append(("### Flags" if md else "FLAGS") + " (%d)" % len(res["flags"]))
L += [("- **%s** %s: %s" if md else "%s %s %s") % (f["code"], f["where"], f["detail"]) for f in res["flags"]] or ["none"]
return "\n".join(L) + "\n"
def self_test():
ok = [0, 0]
def check(name, cond):
ok[0] += 1; ok[1] += bool(cond)
print(("PASS " if cond else "FAIL ") + name)
check("buckets 0-6 https://www.aitopic.com/ 7-8 https://www.aitopic.com/ 9-10", [bucket(x) for x in (0, 6, 7, 8, 9, 10)] == ["detractor"] * 2 + ["passive"] * 2 + ["promoter"] * 2)
s = nps_stats([10] * 5 + [8] * 3 + [3] * 2)
check("NPS 50% - 20% = +30", s["nps"] == 30.0 and s["promoters"] == 5 and s["detractors"] == 2)
check("margin of error formula", abs(s["moe"] - round(1.96 * 100 * math.sqrt((0.5 + 0.2 - 0.09) https://www.aitopic.com/ 10), 1)) < 1e-9)
check("all promoters: NPS 100, moe 0", nps_stats([9, 10, 10])["nps"] == 100.0 and nps_stats([9, 10, 10])["moe"] == 0.0)
check("empty -> None", nps_stats([])["nps"] is None)
check("periods", period_of(date(2026, 11, 28), "quarter") == "2026-Q4" and period_of(date(2026, 2, 1), "month") == "2026-02")
def mk(rows):
return [({"response_id": str(i), "date": d, "score": str(sc), "plan": p, "comment": c}, i + 2) for i, (d, sc, p, c) in enumerate(rows)]
q3 = [("2026-08-01", 10, "Team", "love it, easy to use")] * 40 + [("2026-08-02", 8, "Team", "")] * 10 + [("2026-08-03", 4, "Team", "too expensive")] * 10
q4 = [("2026-11-01", 10, "Team", "easy and fast")] * 20 + [("2026-11-01", 8, "Team", "")] * 10 + \
[("2026-11-02", 3, "Enterprise", "very slow since the update")] * 20 + [("2026-11-02", 9, "Enterprise", "great support")] * 5 + \
[("2026-11-03", 5, "Team", "price is too high")] * 5
themes = {"performance": ["slow", "lag", "loading"], "pricing": ["expensive", "price"], "ease of use": ["easy", "intuitive"]}
res = analyze(mk(q3 + q4), themes=themes, by=["plan"], min_n=20)
codes = {(f["code"], f["where"]) for f in res["flags"]}
check("current period is the latest", res["current"] == "2026-Q4" and res["overall"]["n"] == 60)
check("Q3 NPS +50, Q4 NPS +0", res["by_period"][0]["nps"] == 50.0 and res["overall"]["nps"] == 0.0)
check("N03 significant drop", ("N03", "2026-Q4 vs 2026-Q3") in codes and res["change"]["significant"])
check("N02 Enterprise below the rest", ("N02", "plan=Enterprise") in codes)
check("no N02 for Team", not any(c == "N02" and w == "plan=Team" for c, w in codes))
check("N04 performance theme", ("N04", "performance") in codes)
check("ease of use is not a detractor theme", ("N04", "ease of use") not in codes)
check("themes sorted by detractor mentions", res["themes"][0]["theme"] == "performance")
small = analyze(mk(q4[:12]), by=["plan"], min_n=30)
check("N01 small sample overall and segment", sum(1 for f in small["flags"] if f["code"] == "N01") >= 2)
stable = analyze(mk([("2026-08-01", 10, "Team", "")] * 30 + [("2026-08-01", 3, "Team", "")] * 10 + [("2026-11-01", 10, "Team", "")] * 28 + [("2026-11-01", 3, "Team", "")] * 12), min_n=20)
check("small change within the noise: no N03", stable["change"]["delta"] == -10.0 and not stable["change"]["significant"] and not stable["flags"])
bad = analyze([({"response_id": "a", "date": "2026-11-01", "score": "11"}, 2), ({"response_id": "b", "date": "28.11.2026", "score": "5"}, 3),
({"response_id": "c", "date": "2026-11-01", "score": "9"}, 4), ({"response_id": "c", "date": "2026-11-02", "score": "0"}, 5)], min_n=1)
check("E01 invalid score and date", sum(1 for f in bad["flags"] if f["code"] == "E01") == 2)
check("N05 duplicate id, first answer kept", any(f["code"] == "N05" for f in bad["flags"]) and bad["overall"]["nps"] == 100.0)
import io
try:
load_rows(io.StringIO("id,score\n1,9\n")); check("missing columns raise", False)
except ValueError:
check("missing columns raise", True)
rows, cols = load_rows(io.StringIO("response_id,date,score,comment\n1,2026-11-01,9,\"great, fast\"\n"))
check("csv with quoted comma", rows[0][0]["comment"] == "great, fast")
check("json render parses", json.loads(render(res, "json"))["overall"]["nps"] == 0.0)
check("md render has segment table", "| Segment | n | NPS" in render(res, "md"))
check("text render shows change", "within the noise" in render(stable, "text") and "larger than the noise" in render(res, "text"))
print("%dhttps://www.aitopic.com/%d checks passed" % (ok[1], ok[0]))
return 0 if ok[0] == ok[1] else 1
def main(argv=None):
a = argparse.ArgumentParser(description="NPS with margins of error, trend, segments and comment themes.")
a.add_argument("csv", nargs="?")
a.add_argument("--themes", help="JSON file {\"theme\": [\"keyword\", ...]}")
a.add_argument("--by", action="append", default=[], help="segment column (repeatable)")
a.add_argument("--period", choices=["quarter", "month"], default="quarter")
a.add_argument("--current", help="period to report, e.g. 2026-Q4 or 2026-11 (default: latest)")
a.add_argument("--min-n", type=int, default=30, help="responses needed before a group counts as a result (default 30)")
a.add_argument("--format", choices=["text", "md", "json"], default="text")
a.add_argument("--self-test", action="store_true")
o = a.parse_args(argv)
if o.self_test:
return self_test()
if not o.csv:
a.print_usage(sys.stderr); return 2
try:
with open(o.csv, newline="", encoding="utf-8-sig") as fh:
rows, cols = load_rows(fh)
themes = json.load(open(o.themes, encoding="utf-8")) if o.themes else None
except (OSError, ValueError) as e:
print("error: %s" % e, file=sys.stderr); return 2
unknown = [b for b in o.by if b not in cols]
if unknown:
print("error: unknown segment column(s): %s" % ", ".join(unknown), file=sys.stderr); return 2
res = analyze(rows, themes, o.by, o.period, o.current, o.min_n)
if not res["overall"]["n"]:
print("error: no valid responses for period %s" % res["current"], file=sys.stderr); return 2
sys.stdout.write(render(res, o.format))
return 1 if res["flags"] else 0
if __name__ == "__main__":
sys.exit(main())
Comments & Questions (0)
No comments yet
Be the first to comment!