Profiles CSV/JSON exports for data-quality problems (with the fix per column), checks SQL for correctness traps and slow patterns, and builds a paste-ready summary report. Use when someone shares a data export or a query and asks what it says, whether it can be trusted, or how to fix it; also for cohort, funnel and dashboard work.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Data Analyst?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/borghei-data-analyst)
---
name: data-analyst
description: >
Profiles CSV/JSON exports for data-quality problems (with the fix per column),
checks SQL for correctness traps and slow patterns, and builds a paste-ready
summary report. Use when someone shares a data export or a query and asks what
it says, whether it can be trusted, or how to fix it; also for cohort, funnel
and dashboard work.
license: MIT + Commons Clause
metadata:
version: 2.0.0
author: borghei
category: data-analytics
domain: data-analysis
updated: 2026-12-03
tags: [analytics, sql, visualization, statistics, reporting]
---
# Data Analyst
The agent operates as a senior data analyst, writing production SQL, designing visualizations, running statistical tests, and translating findings into actionable business recommendations.
## Clarify First
Before the analysis, settle the inputs below. When one is missing or vague and would change the result, ask about it; when it wouldn't, use a sensible default and say which one you used.
- **Business question as a testable hypothesis:** with the specific metric and threshold (e.g., ">= 5% lift in 7-day retention") (frames the whole analysis and the headline).
- **Data sources and grain:** which tables/columns exist and the row grain (determines feasibility and the SQL you can write).
- **Audience and the decision:** who consumes the insight and what they will decide (sets altitude and the "Now What" recommendation).
- **Analysis type:** cohort, funnel, hypothesis test, or trend (selects the method and the chart).
Ask about the two or three inputs that matter most for this request, not the whole list. If the user wants a result straight away, produce it and state your assumptions at the top.
## Workflow
1. **Frame the business question** -- Restate it as a testable hypothesis with a metric and threshold (e.g., "Did campaign X lift 7-day retention by >= 5%?").
2. **Profile before you analyse** -- Run `data_profiler.py` on every new export. Exit 1 means something changes the numbers (duplicate keys, unparseable dates or amounts, placeholder nulls, label variants): fix it or state it as a caveat before any figure leaves your hands.
3. **Check the SQL** -- Run `query_optimizer.py` on any query you write or are handed. The high-severity rules are correctness bugs (`= NULL`, `NOT IN` over a nullable subquery, comma joins without a condition, unbounded `DELETE`), not style.
4. **Analyse** -- Cohorts for retention, funnels for conversion, a breakdown for mix. `report_generator.py` gives the key figures, rates, breakdown and monthly trend in markdown.
5. **Test any claimed difference** -- A gap between groups is not a finding until it is tested. Use the `statistical-analyst` skill (`run_test.py`) and report the effect with its interval.
6. **Deliver the insight** -- What / So What / Now What. Lead with the headline, support with one table or chart, close with a recommendation and its expected impact.
## SQL Patterns
**Monthly aggregation with growth:**
```sql
WITH monthly AS (
SELECT
date_trunc('month', created_at) AS month,
COUNT(*) AS total_orders,
COUNT(DISTINCT customer_id) AS unique_customers,
SUM(amount) AS revenue
FROM orders
WHERE created_at >= '2024-01-01'
GROUP BY 1
),
growth AS (
SELECT month, revenue,
LAG(revenue) OVER (ORDER BY month) AS prev_revenue
FROM monthly
)
SELECT month, revenue,
ROUND((revenue - prev_revenue) / prev_revenue * 100, 1) AS growth_pct
FROM growth
ORDER BY month;
```
**Cohort retention:**
```sql
WITH first_orders AS (
SELECT customer_id,
date_trunc('month', MIN(created_at)) AS cohort_month
FROM orders GROUP BY 1
),
cohort_data AS (
SELECT f.cohort_month,
date_trunc('month', o.created_at) AS order_month,
COUNT(DISTINCT o.customer_id) AS customers
FROM orders o
JOIN first_orders f ON o.customer_id = f.customer_id
GROUP BY 1, 2
)
SELECT cohort_month, order_month,
EXTRACT(MONTH FROM AGE(order_month, cohort_month)) AS months_since,
customers
FROM cohort_data ORDER BY 1, 2;
```
**Window functions (running total + previous order):**
```sql
SELECT customer_id, order_date, amount,
SUM(amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS running_total,
LAG(amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS prev_amount
FROM orders;
```
## Chart Selection Matrix
| Data question | Best chart | Alternative |
|---------------|-----------|-------------|
| Trend over time | Line | Area |
| Part of whole | Donut | Stacked bar |
| Comparison | Bar | Column |
| Distribution | Histogram | Box plot |
| Correlation | Scatter | Heatmap |
| Geographic | Choropleth | Bubble map |
**Design rules:** Start Y-axis at zero for bar charts. Use <= 7 colors. Label axes. Include benchmarks or targets for context. Avoid 3D charts and pie charts with > 5 slices.
## Dashboard Layout
```
+------------------------------------------------------------+
| KPI CARDS: Revenue | Customers | Conversion | NPS |
+------------------------------------------------------------+
| TREND (line chart) | BREAKDOWN (bar chart) |
+-------------------------------+-----------------------------+
| COMPARISON vs target/LY | DETAIL TABLE (top N) |
+-------------------------------+-----------------------------+
```
## Key Business Metrics
| Category | Metric | Formula |
|----------|--------|---------|
| Acquisition | CAC | Total S&M spend / New customers |
| Acquisition | Conversion rate | Conversions / Visitors |
| Engagement | DAU/MAU ratio | Daily active / Monthly active |
| Retention | Churn rate | Lost customers / Total at period start |
| Revenue | MRR | SUM(active subscription amounts) |
| Revenue | LTV | ARPU x Gross margin x Avg lifetime |
## Insight Delivery Template
```markdown
## [Headline: action-oriented finding]
**What:** One-sentence description of the observation.
**So What:** Why this matters to the business (revenue, retention, cost).
**Now What:** Recommended action with expected impact.
**Evidence:** [Chart or table supporting the finding]
**Confidence:** High / Medium / Low
```
## Analysis Framework
```markdown
# Analysis: [Topic]
## Business Question -- What are we trying to answer?
## Hypothesis -- What do we expect to find?
## Data Sources -- [Source]: [Description]
## Methodology -- Numbered steps
## Findings -- Finding 1, Finding 2 (with supporting data)
## Recommendations -- [Action]: [Expected impact]
## Limitations -- Known caveats
## Next Steps -- Follow-up actions
```
## Scripts
All three read the user's file, use the Python standard library only, and share one column-typing module (`scripts/profile_core.py`), so a 0/1 flag is a rate, an ID is never summed and only continuous measures are tested for extreme values.
```bash
python3 scripts/data_profiler.py assets/flawed_orders.csv
python3 scripts/data_profiler.py --file assets/sound_orders.csv --top 10 --format json
python3 scripts/query_optimizer.py assets/flawed_query.sql
python3 scripts/query_optimizer.py --sql "SELECT * FROM orders WHERE status = NULL" --format json
python3 scripts/report_generator.py assets/sound_orders.csv --group-by plan
python3 scripts/report_generator.py assets/sound_orders.csv --metric amount --date-col order_date --title "H1 orders" --format json
python3 scripts/report_generator.py assets/sound_orders.csv --group-by plan --test-json plan_test.json --test-on is_paid --test-groups free,pro
```
| Tool | What it does | Key flags |
|------|--------------|-----------|
| `data_profiler.py` | Types every column (empty, constant, binary, numeric, date, id, categorical, text) and runs only the checks that fit: duplicate keys and rows, unparseable or impossible dates, mixed date formats, non-numeric and currency-formatted numbers, placeholder nulls (`N/A`, `-`), sentinel codes (999, -1), case/space label variants, mixed yes/no encodings, constant columns, extreme values (Tukey 3 x IQR, measures only). Each finding quotes values with line numbers and gives the fix. | `<file>` or `--file`, `--top`, `--format text\|json` (`--json` alias) |
| `query_optimizer.py` | Masks comments and strings, then checks each statement: unbounded UPDATE/DELETE, `= NULL`, `NOT IN (SELECT ...)`, cartesian and implicit joins, functions on filtered columns, leading-wildcard LIKE, `SELECT *`, DISTINCT over a JOIN, division without `NULLIF`, deep nesting, OR chains, UNION vs UNION ALL. Prints a rewritten query with the mechanical fixes applied. | `<file>`, `--file`, `--sql`, `-` for stdin, `--format text\|json` |
| `report_generator.py` | Markdown report: data caveats first, then key figures, rates for 0/1 flags, breakdown by a group column, monthly trend, and highlights computed from the figures. Group differences are described, never called significant; `--test-json` writes a `statistical-analyst` `run_test.py` input (two_proportion for a 0/1 flag, welch_t for a number) so the difference can be tested. | `<file>`, `--group-by`, `--metric`, `--date-col`, `--title`, `--test-json <out.json> --test-on <col> --test-groups a,b`, `--format text\|markdown\|json` |
Samples in `assets/`: `sound_orders.csv` / `flawed_orders.csv` / `malformed_orders.csv` for the profiler and report, `sound_query.sql` / `flawed_query.sql` / `malformed_query.sql` for the query checker. `assets/contract.json` declares the expected exit code of each.
### Exit codes
| Code | data_profiler.py | query_optimizer.py | report_generator.py |
|------|------------------|--------------------|---------------------|
| 0 | no issue to fix (notes may remain) | no high/medium finding | report built on clean data |
| 1 | issues to fix | findings | report built, but data issues change its numbers |
| 2 | file missing, empty, not UTF-8, not a table, header only | no SQL statement, unbalanced parentheses | unusable file, unknown or wrong-type column |
Errors print one `BLOCKED: <reason>` line on stderr, never a traceback.
### Real output
```text
$ python3 scripts/data_profiler.py assets/flawed_orders.csv
FIX 10 issue(s) (4 high, 6 medium) + 2 note(s)
Read 122 rows x 11 columns from assets/flawed_orders.csv (CSV, delimiter ','). Rows are cited by file line (header = line 1).
...
2. [high] signup_date: INVALID_DATE
Problem: cast 'signup_date' to date: 3 row(s) fail parsing, e.g. '31/02/2024' (line 9), '2024-13-05' (line 21), 'yesterday' (line 35)
Evidence: 3 row(s), 2.5%; e.g. '31/02/2024' at line 9; '2024-13-05' at line 21; 'yesterday' at line 35
Rule: every value must be a real calendar date
Fix: Correct those cells at the source (an impossible date such as 31 February needs the real date) or set them to NULL, then cast with one explicit format: pandas pd.to_datetime(df['signup_date'], format='%Y-%m-%d', errors='coerce').
```
The `is_paid` 0/1 column in the same file is reported as `42 of 122 true (34.4%)`, not as outliers.
## Troubleshooting
| Problem | Likely cause | Resolution |
|---------|-------------|------------|
| A column you expected to be numeric is typed `text` | More than 20% of its values do not parse as numbers | Run the profiler: NON_NUMERIC and FORMATTED_NUMBERS list the cells; clean them and re-run |
| A count looks too high | Duplicate keys or exact duplicate rows | DUPLICATE_KEY / DUPLICATE_ROWS give the lines; deduplicate before counting |
| An ID column was not recognised | Its name has no `id`/`uuid` and its values repeat | Repeating IDs are typed `id (foreign key)` only when the name says so; otherwise they show as categorical or text, which is harmless for profiling |
| Dates like 03/04/2024 | Day and month are both <= 12 | The profiler reads them with the column's dominant format and reports how many were ambiguous |
| `query_optimizer.py` misses an issue | It reads SQL text and has no access to the schema or plan | Run `EXPLAIN ANALYZE` on the real database for plan-level problems |
| Report shows a big gap between groups | Small groups or chance | Test it with `statistical-analyst` before reporting it |
## Success Criteria
- Every analysis follows the Frame-Query-Explore-Analyze-Visualize-Deliver workflow before presenting findings.
- SQL passes `query_optimizer.py` (exit 0) before it feeds a production dashboard.
- `data_profiler.py` runs on every new export before analysis, and every remaining issue is stated as a caveat.
- Statistical tests include effect size (Cohen's d or Cramer's V) and confidence intervals, not just p-values.
- Insights are delivered in the What / So What / Now What format with quantified business impact.
- Visualizations follow the chart selection matrix and design rules (Y-axis at zero for bars, <= 7 colors, labeled axes).
- Every group difference in a report is tested before it is called real.
## Scope & Limitations
**In scope:** profiling exports for data quality, SQL review, summary reports, cohort and funnel analysis, chart choice, insight delivery.
**Out of scope:** significance tests (use `statistical-analyst`), predictive modelling (`data-scientist`), recurring dashboards and KPI systems (`business-intelligence`), pipelines and warehouse modelling (`analytics-engineer`).
**Limitations:** the tools read local CSV/TSV/JSON/JSONL files into memory (very large files need sampling first) and never connect to a database. `query_optimizer.py` is static analysis: it does not know table sizes, indexes or the dialect, so its findings are what to check, and `EXPLAIN` decides. Thresholds marked *heuristic* in the output (missing-value bands, 15 distinct values for a measure) are this skill's defaults, not published standards.
## Integration Points
- **Analytics Engineer** (`data-analytics/analytics-engineer`): Provides the clean mart models that analysts query; data quality issues found during analysis feed back to the analytics engineer.
- **Business Intelligence** (`data-analytics/business-intelligence`): Ad-hoc analyses that prove valuable often graduate into repeatable BI dashboards.
- **Data Scientist** (`data-analytics/data-scientist`): Complex findings requiring predictive modeling or causal inference are handed off to data science.
- **Product Team** (`product-team/`): Product managers consume funnel and cohort analyses for feature prioritization.
- **Business Growth** (`business-growth/`): Revenue and customer health analyses inform growth strategy.