name: “competitive-teardown”
description: “Analyzes competitor products and companies by synthesizing data from pricing pages, app store reviews, job postings, SEO signals, and social media into structured competitive intelligence. Produces feature comparison matrices scored across 12 dimensions, SWOT analyses, positioning maps, UX audits, pricing model breakdowns, action item roadmaps, and stakeholder presentation templates. Use when conducting competitor analysis, comparing products against competitors, researching the competitive landscape, building battle cards for sales, preparing for a product strategy or roadmap session, responding to a competitor’s new feature or pricing change, or performing a quarterly competitive review.”
Competitive Teardown
Tier: POWERFUL
Category: Product Team
Domain: Competitive Intelligence, Product Strategy, Market Analysis
When to Use
- Before a product strategy or roadmap session
- When a competitor launches a major feature or pricing change
- Quarterly competitive review
- Before a sales pitch where you need battle card data
- When entering a new market segment
Teardown Workflow
Follow these steps in sequence to produce a complete teardown:
- Define competitors — List 2–4 competitors to analyze. Confirm which is the primary focus.
- Collect data — Use
references/data-collection-guide.md to gather raw signals from at least 3 sources per competitor (website, reviews, job postings, SEO, social).
Validation checkpoint: Before proceeding, confirm you have pricing data, at least 20 reviews, and job posting counts for each competitor.
- Score using rubric — Apply the 12-dimension rubric below to produce a numeric scorecard for each competitor and your own product.
Validation checkpoint: Every dimension should have a score and at least one supporting evidence note.
- Generate outputs — Populate the templates in
references/analysis-templates.md (Feature Matrix, Pricing Analysis, SWOT, Positioning Map, UX Audit).
- Build action plan — Translate findings into the Action Items template (quick wins / medium-term / strategic).
- Package for stakeholders — Assemble the Stakeholder Presentation using outputs from steps 3–5.
Data Collection Guide
Full executable scripts for each source are in references/data-collection-guide.md. Summaries of what to capture are below.
1. Website Analysis
Key things to capture:
- Pricing tiers and price points
- Feature lists per tier
- Primary CTA and messaging
- Case studies / customer logos (signals ICP)
- Integration logos
- Trust signals (certifications, compliance badges)
2. App Store Reviews
Review sentiment categories:
- Praise → what users love (defend / strengthen these)
- Feature requests → unmet needs (opportunity gaps)
- Bugs → quality signals
- UX complaints → friction points you can beat them on
Sample App Store query (iTunes Search API):
GET https://itunes.apple.com/search?term=<competitor_name>&entity=software&limit=1
# Extract trackId, then:
GET https://itunes.apple.com/rss/customerreviews/id=<trackId>/sortBy=mostRecent/json?l=en&limit=50
Parse entry[].content.label for review text and entry[].im:rating.label for star rating.
3. Job Postings (Team Size & Tech Stack Signals)
Signals from job postings:
- Engineering volume → scaling vs. consolidating
- Specific tech mentions → stack (React/Vue, Postgres/Mongo, AWS/GCP)
- Sales/CS ratio → product-led vs. sales-led motion
- Data/ML roles → upcoming AI features
- Compliance roles → regulatory expansion
4. SEO Analysis
SEO signals to capture:
- Top 20 organic keywords (intent: informational / navigational / commercial)
- Domain Authority / backlink count
- Blog publishing cadence and topics
- Which pages rank (product pages vs. blog vs. docs)
Capture recent mentions via Twitter/X API v2, Reddit, or LinkedIn. Look for recurring praise, complaints, and feature requests. See references/data-collection-guide.md for API query examples.
Scoring Rubric (12 Dimensions, 1-5)
| # | Dimension | 1 (Weak) | 3 (Average) | 5 (Best-in-class) |
|---|
| 1 | Features | Core only, many gaps | Solid coverage | Comprehensive + unique |
| 2 | Pricing | Confusing / overpriced | Market-rate, clear | Transparent, flexible, fair |
| 3 | UX | Confusing, high friction | Functional | Delightful, minimal friction |
| 4 | Performance | Slow, unreliable | Acceptable | Fast, high uptime |
| 5 | Docs | Sparse, outdated | Decent coverage | Comprehensive, searchable |
| 6 | Support | Email only, slow | Chat + email | 24/7, great response |
| 7 | Integrations | 0-5 integrations | 6-25 | 26+ or deep ecosystem |
| 8 | Security | No mentions | SOC2 claimed | SOC2 Type II, ISO 27001 |
| 9 | Scalability | No enterprise tier | Mid-market ready | Enterprise-grade |
| 10 | Brand | Generic, unmemorable | Decent positioning | Strong, differentiated |
| 11 | Community | None | Forum / Slack | Active, vibrant community |
| 12 | Innovation | No recent releases | Quarterly | Frequent, meaningful |
Example completed row (Competitor: Acme Corp, Dimension 3 – UX):
| Dimension | Acme Corp Score | Evidence |
|---|
| UX | 2 | App Store reviews cite “confusing navigation” (38 mentions); onboarding requires 7 steps before TTFV; no onboarding wizard; CC required at signup. |
Apply this pattern to all 12 dimensions for each competitor.
Templates
Full template markdown is in references/analysis-templates.md. Abbreviated reference below.
Feature Comparison Matrix
Rows: core features, pricing tiers, platform capabilities (web, iOS, Android, API).
Columns: your product + up to 3 competitors.
Score each cell 1–5. Sum to get total out of 60.
Score legend: 5=Best-in-class, 4=Strong, 3=Average, 2=Below average, 1=Weak/Missing
Pricing Analysis
Capture per competitor: model type (per-seat / usage-based / flat rate / freemium), entry/mid/enterprise price points, free trial length.
Summarize: price leader, value leader, premium positioning, your position, and 2–3 pricing opportunity bullets.
SWOT Analysis
For each competitor: 3–5 bullets per quadrant (Strengths, Weaknesses, Opportunities for us, Threats to us). Anchor every bullet to a data signal (review quote, job posting count, pricing page, etc.).
Positioning Map
2x2 axes (e.g., Simple ↔ Complex / Low Value ↔ High Value). Place each competitor and your product. Bubble size = market share or funding. See references/analysis-templates.md for ASCII and editable versions.
UX Audit Checklist
Onboarding: TTFV (minutes), steps to activation, CC-required, onboarding wizard quality.
Key workflows: steps, friction points, comparative score (yours vs. theirs).
Mobile: iOS/Android ratings, feature parity, top complaint and praise.
Navigation: global search, keyboard shortcuts, in-app help.
Action Items
| Horizon | Effort | Examples |
|---|
| Quick wins (0–4 wks) | Low | Add review badges, publish comparison landing page |
| Medium-term (1–3 mo) | Moderate | Launch free tier, improve onboarding TTFV, add top-requested integration |
| Strategic (3–12 mo) | High | Enter new market, build API v2, achieve SOC2 Type II |
Stakeholder Presentation (7 slides)
- Executive Summary — Threat level (LOW/MEDIUM/HIGH/CRITICAL), top strength, top opportunity, recommended action
- Market Position — 2x2 positioning map
- Feature Scorecard — 12-dimension radar or table, total scores
- Pricing Analysis — Comparison table + key insight
- UX Highlights — What they do better (3 bullets) vs. where we win (3 bullets)
- Voice of Customer — Top 3 review complaints (quoted or paraphrased)
- Our Action Plan — Quick wins, medium-term, strategic priorities; Appendix with raw data
- Product Strategist (
product-team/product-strategist/) — Competitive insights feed OKR and strategy planning
- Landing Page Generator (
product-team/landing-page-generator/) — Competitive positioning informs landing page messaging
Competitive Analysis Templates
1. SWOT Analysis Template
Company/Product: [Competitor Name]
Date: [Analysis Date] | Analyst: [Name] | Version: [1.0]
Strengths (Internal Advantages)
| # |
Strength |
Evidence |
Impact |
| 1 |
[e.g., Strong brand recognition] |
[Source/data point] |
High/Med/Low |
| 2 |
|
|
|
| 3 |
|
|
|
Weaknesses (Internal Limitations)
| # |
Weakness |
Evidence |
Exploitability |
| 1 |
[e.g., Limited API capabilities] |
[Source/data point] |
High/Med/Low |
| 2 |
|
|
|
| 3 |
|
|
|
Opportunities (External Favorable)
| # |
Opportunity |
Timeframe |
Our Advantage |
| 1 |
[e.g., Competitor slow to adopt AI] |
Short/Med/Long |
[How we capitalize] |
| 2 |
|
|
|
| 3 |
|
|
|
Threats (External Unfavorable)
| # |
Threat |
Likelihood |
Mitigation |
| 1 |
[e.g., Competitor acquired by larger company] |
High/Med/Low |
[Our response plan] |
| 2 |
|
|
|
| 3 |
|
|
|
2. Porter's Five Forces (Product Application)
Market: [Your Product Category]
Force 1: Competitive Rivalry (Intensity: High/Med/Low)
- Number of direct competitors: ___
- Market growth rate: ___% annually
- Product differentiation level: High/Med/Low
- Switching costs for customers: High/Med/Low
- Exit barriers: High/Med/Low
- Assessment: [Summary of competitive rivalry intensity]
Force 2: Threat of New Entrants (Intensity: High/Med/Low)
- Capital requirements: High/Med/Low
- Technology barriers: High/Med/Low
- Network effects strength: Strong/Moderate/Weak
- Regulatory barriers: High/Med/Low
- Brand loyalty in market: Strong/Moderate/Weak
- Assessment: [Summary of new entrant threat]
Force 3: Threat of Substitutes (Intensity: High/Med/Low)
- Alternative solutions: [List substitutes]
- Price-performance of substitutes: Better/Same/Worse
- Switching costs to substitutes: High/Med/Low
- Customer propensity to switch: High/Med/Low
- Assessment: [Summary of substitute threat]
Force 4: Bargaining Power of Buyers (Power: High/Med/Low)
- Buyer concentration: Concentrated/Fragmented
- Price sensitivity: High/Med/Low
- Information availability: Full/Partial/Limited
- Switching costs: High/Med/Low
- Volume of purchases: High/Med/Low
- Assessment: [Summary of buyer power]
Force 5: Bargaining Power of Suppliers (Power: High/Med/Low)
- Key technology dependencies: [List]
- Cloud provider lock-in: High/Med/Low
- Talent market tightness: Tight/Balanced/Loose
- Data source dependencies: Critical/Important/Optional
- Assessment: [Summary of supplier power]
Overall Industry Attractiveness: [Score 1-10]
3. Competitive Positioning Map
Axis Definitions
- X-Axis: [e.g., Ease of Use] (Low to High)
- Y-Axis: [e.g., Feature Completeness] (Low to High)
Competitor Positions
| Competitor |
X Score (1-10) |
Y Score (1-10) |
Quadrant |
| Your Product |
___ |
___ |
___ |
| Competitor A |
___ |
___ |
___ |
| Competitor B |
___ |
___ |
___ |
| Competitor C |
___ |
___ |
___ |
| Competitor D |
___ |
___ |
___ |
Quadrant Definitions
- Top-Right (Leaders): High on both axes - market leaders
- Top-Left (Feature-Rich): High features, lower ease of use - complex tools
- Bottom-Right (Simple): Easy to use, fewer features - niche players
- Bottom-Left (Laggards): Low on both axes - disruption candidates
Positioning Insights
- White space opportunities: [Areas with no competitor presence]
- Crowded areas: [Where competition is fiercest]
- Our trajectory: [Direction we're moving on the map]
4. Win/Loss Analysis Template
Deal: [Opportunity Name]
Date: [Close Date] | Result: Won / Lost | Competitor: [Name]
Deal Context
- Deal Size: $___
- Sales Cycle: ___ days
- Segment: SMB / Mid-Market / Enterprise
- Industry: ___
- Decision Makers: [Roles involved]
- Evaluation Criteria: [What mattered most to buyer]
Competitive Comparison (Buyer Perspective)
| Factor |
Us (Score 1-5) |
Competitor (Score 1-5) |
Decisive? |
| Product Fit |
|
|
Yes/No |
| Pricing |
|
|
Yes/No |
| Ease of Use |
|
|
Yes/No |
| Support Quality |
|
|
Yes/No |
| Integration |
|
|
Yes/No |
| Brand/Trust |
|
|
Yes/No |
| Implementation |
|
|
Yes/No |
Win/Loss Factors
- Primary reason for outcome: [Single most important factor]
- Secondary factors: [Supporting reasons]
- Buyer quotes: ["Direct quotes from debrief"]
Action Items
| # |
Action |
Owner |
Due Date |
| 1 |
[e.g., Improve onboarding flow] |
[Name] |
[Date] |
| 2 |
|
|
|
5. Battle Card Template
Competitor: [Name]
Last Updated: [Date] | Confidence: High/Med/Low
Quick Facts
- Founded: ___
- Funding: $___
- Employees: ___
- Customers: ___
- HQ: ___
Elevator Pitch (Their Positioning)
[How the competitor describes themselves in one sentence]
Our Positioning Against Them
[How we differentiate - our one-liner against this competitor]
Where They Win
| Strength |
Our Counter |
| [e.g., Lower price point] |
[e.g., Emphasize TCO including implementation costs] |
| [e.g., Larger integration marketplace] |
[e.g., Highlight quality over quantity, key integrations] |
|
|
Where We Win
| Our Strength |
Evidence |
| [e.g., Superior onboarding experience] |
[Metric or customer quote] |
| [e.g., Better enterprise security] |
[Certification or feature] |
|
|
Landmines to Set
Questions to ask prospects that expose competitor weaknesses:
- "Have you evaluated how [specific capability] scales beyond [threshold]?"
- "What's their approach to [area where competitor is weak]?"
- "Can you share their uptime SLA and historical performance?"
Objection Handling
| Objection |
Response |
| "[Competitor] is cheaper" |
[Value-based response] |
| "[Competitor] has more features" |
[Quality/relevance response] |
| "We already use [Competitor]" |
[Migration/coexistence story] |
Trap Questions They Set
Questions competitors ask about us, and how to respond:
- Q: "[Our known weakness]?" A: [Honest, redirect response]
- Q: "[Feature gap]?" A: [Roadmap or alternative approach]
Recent Intel
- [Date]: [Notable change - pricing, feature, hire, funding]
- [Date]: [Notable change]
Competitive Analysis Frameworks
This reference provides practical frameworks for evaluating competitors and positioning decisions.
Porter's Five Forces
Assess the competitive intensity of your market:
- Threat of new entrants
- Barriers to entry (capital, regulation, network effects)
- Speed of competitor replication
- Bargaining power of suppliers
- Dependency on core infrastructure vendors
- Concentration of key technical providers
- Bargaining power of buyers
- Customer switching costs
- Procurement complexity and contract leverage
- Threat of substitutes
- Adjacent alternatives solving the same job
- DIY and internal build options
- Rivalry among existing competitors
- Number and similarity of competitors
- Price competition and differentiation pressure
Five Forces Template
| Force |
Current Pressure (Low/Med/High) |
Evidence |
Strategic Response |
| New Entrants |
|
|
|
| Supplier Power |
|
|
|
| Buyer Power |
|
|
|
| Substitutes |
|
|
|
| Rivalry |
|
|
|
SWOT Analysis
Use SWOT to map internal and external context quickly.
SWOT Template
| Strengths (Internal) |
Weaknesses (Internal) |
| What we do better than alternatives |
Where competitors outperform us |
| Unique capabilities or assets |
Known product or go-to-market gaps |
| Opportunities (External) |
Threats (External) |
| Market trends we can exploit |
Competitor moves or macro risks |
| Unserved segments and use cases |
Regulatory, platform, or pricing pressure |
SWOT Quality Checklist
- Base every point on evidence, not assumptions.
- Separate observations from conclusions.
- Prioritize top 3 items per quadrant.
Feature Comparison Matrix
Compare products on meaningful buying criteria, not vanity features.
Feature Matrix Template
| Dimension |
Weight |
Your Product |
Competitor A |
Competitor B |
Notes |
| Core workflow coverage |
25% |
|
|
|
|
| Ease of implementation |
15% |
|
|
|
|
| Performance / reliability |
15% |
|
|
|
|
| Integrations / ecosystem |
15% |
|
|
|
|
| Security / compliance |
15% |
|
|
|
|
| Pricing / TCO |
15% |
|
|
|
|
Scoring scale recommendation: 1-5 (weak to strong).
Competitive Positioning Map
Create a 2-axis map showing market whitespace and crowding.
Positioning Map Steps
- Select two high-signal dimensions customers care about.
- Place each competitor based on evidence (pricing pages, reviews, demos).
- Mark clusters where products are undifferentiated.
- Identify white space where demand exists but options are weak.
Example axes:
- X-axis: Ease of use
- Y-axis: Enterprise readiness
Blue Ocean Strategy Canvas
Use a strategy canvas to decide where to raise, reduce, eliminate, or create factors.
ERRC Grid (Eliminate-Reduce-Raise-Create)
| Eliminate |
Reduce |
Raise |
Create |
| Commodity table-stakes not valued by target users |
Costly features with weak adoption |
Differentiators tied to target job-to-be-done |
New value dimensions competitors ignore |
Strategy Canvas Checklist
- Compare value curves between your product and top competitors.
- Ensure target segment is explicit.
- Tie every strategic choice to measurable outcome.
Competitive Scoring Rubric
Overview
This rubric provides a standardized framework for evaluating competitors across key dimensions. Consistent scoring enables meaningful comparisons and tracks competitive position changes over time.
Scoring Scale (1-10)
| Score |
Label |
Definition |
| 1-2 |
Poor |
Significant gaps, major usability issues, or missing capability |
| 3-4 |
Below Average |
Basic functionality with notable limitations |
| 5-6 |
Average |
Meets market expectations, no standout qualities |
| 7-8 |
Above Average |
Strong execution with clear advantages |
| 9-10 |
Exceptional |
Industry-leading, sets the standard for others |
Dimension Categories
1. User Experience (UX) - Weight: 20%
- Onboarding: Time to first value, setup complexity, guided flows
- Navigation: Information architecture, discoverability, consistency
- Visual Design: Modern aesthetics, brand coherence, accessibility
- Performance: Page load times, responsiveness, offline capability
- Mobile Experience: Native app quality, responsive design, feature parity
2. Feature Completeness - Weight: 25%
- Core Features: Coverage of essential use cases
- Advanced Features: Power user capabilities, automation, customization
- Workflow Support: End-to-end process coverage without workarounds
- API & Extensibility: API coverage, webhook support, SDK quality
- Innovation: Unique capabilities not found in competitors
3. Pricing & Value - Weight: 15%
- Transparency: Clear pricing without hidden costs
- Flexibility: Plan options matching different customer sizes
- Value-to-Cost Ratio: Feature access relative to price point
- Free Tier / Trial: Quality of free offering for evaluation
- Contract Terms: Lock-in requirements, cancellation ease
4. Integrations - Weight: 10%
- Native Integrations: Number and quality of built-in connectors
- Marketplace: Third-party app ecosystem breadth
- API Quality: Documentation, reliability, rate limits
- Data Import/Export: Migration ease, format support
- Workflow Automation: Zapier, Make, native automation support
5. Support & Documentation - Weight: 10%
- Documentation Quality: Completeness, searchability, freshness
- Support Channels: Chat, email, phone, community availability
- Response Time: SLA adherence, resolution speed
- Self-Service: Knowledge base, video tutorials, community forums
- Onboarding Support: Dedicated CSM, implementation assistance
6. Performance & Reliability - Weight: 10%
- Uptime: Historical availability, SLA commitments
- Speed: Application responsiveness under normal load
- Scalability: Performance at high volume, enterprise readiness
- Data Handling: Large dataset support, bulk operations
- Global Performance: CDN, regional deployments, latency
7. Security & Compliance - Weight: 10%
- Authentication: SSO, MFA, RBAC granularity
- Data Protection: Encryption at rest and in transit, data residency
- Certifications: SOC 2, ISO 27001, GDPR, HIPAA compliance
- Audit Trail: Activity logging, access monitoring
- Privacy Controls: Data retention policies, right to deletion
Weighting Guidelines
Default weights above suit most B2B SaaS evaluations. Adjust based on:
- Enterprise buyers: Increase Security (15%), Support (15%), reduce Pricing (10%)
- Developer tools: Increase Integrations (20%), Features (30%), reduce UX (10%)
- SMB products: Increase Pricing (25%), UX (25%), reduce Security (5%)
- Regulated industries: Increase Security (25%), reduce Features (15%)
Calibration Process
- Anchor scoring - Score your own product first to establish baseline
- Multiple scorers - Have 2-3 team members score independently
- Discuss outliers - Reconcile scores that differ by more than 2 points
- Document evidence - Record specific examples justifying each score
- Normalize quarterly - Re-calibrate as market expectations evolve
Bias Mitigation
- Avoid halo effect - Score each dimension independently, not influenced by overall impression
- Use evidence, not feelings - Every score must link to observable data points
- Include competitor strengths - Resist tendency to under-score competitors
- Rotate scorers - Different team members bring fresh perspectives
- Blind scoring - When possible, evaluate features without knowing which competitor
- Customer validation - Compare internal scores against user review sentiment
Composite Score Calculation
Weighted Score = SUM(Dimension Score x Dimension Weight)
Example:
UX(8) x 0.20 = 1.60
Features(7) x 0.25 = 1.75
Pricing(6) x 0.15 = 0.90
Integrations(8) x 0.10 = 0.80
Support(7) x 0.10 = 0.70
Performance(9) x 0.10 = 0.90
Security(8) x 0.10 = 0.80
---
Total = 7.45 / 10
Output Format
Present results as a comparison matrix with color coding:
- Green (8-10): Competitive advantage
- Yellow (5-7): Market parity
- Red (1-4): Competitive gap
#!/usr/bin/env python3
"""Competitive Matrix Builder — Analyze and score competitors across feature dimensions.
Generates weighted competitive matrices, gap analysis, and positioning insights
from structured competitor data.
Usage:
python competitive_matrix_builder.py competitors.json --format json
python competitive_matrix_builder.py competitors.json --format text
python competitive_matrix_builder.py competitors.json --format text --weights pricing=2,ux=1.5
"""
import argparse
import json
import sys
from typing import Dict, List, Any, Optional
from datetime import datetime
from statistics import mean, stdev
def load_competitors(path: str) -> Dict[str, Any]:
"""Load competitor data from JSON file."""
with open(path, "r") as f:
return json.load(f)
def normalize_score(value: float, min_val: float = 1.0, max_val: float = 10.0) -> float:
"""Normalize a score to 0-100 scale."""
return max(0.0, min(100.0, ((value - min_val) / (max_val - min_val)) * 100))
def calculate_weighted_scores(
competitors: List[Dict[str, Any]],
dimensions: List[str],
weights: Optional[Dict[str, float]] = None
) -> List[Dict[str, Any]]:
"""Calculate weighted scores for each competitor across dimensions."""
if weights is None:
weights = {d: 1.0 for d in dimensions}
results = []
for comp in competitors:
scores = comp.get("scores", {})
weighted_total = 0.0
weight_sum = 0.0
dimension_results = {}
for dim in dimensions:
raw = scores.get(dim, 0)
w = weights.get(dim, 1.0)
normalized = normalize_score(raw)
weighted = normalized * w
weighted_total += weighted
weight_sum += w
dimension_results[dim] = {
"raw": raw,
"normalized": round(normalized, 1),
"weight": w,
"weighted": round(weighted, 1)
}
overall = round(weighted_total / weight_sum, 1) if weight_sum > 0 else 0
results.append({
"name": comp["name"],
"overall_score": overall,
"dimensions": dimension_results,
"tier": classify_tier(overall),
"pricing": comp.get("pricing", {}),
"strengths": comp.get("strengths", []),
"weaknesses": comp.get("weaknesses", [])
})
results.sort(key=lambda x: x["overall_score"], reverse=True)
return results
def classify_tier(score: float) -> str:
"""Classify competitor into tier based on overall score."""
if score >= 80:
return "Leader"
elif score >= 60:
return "Strong Competitor"
elif score >= 40:
return "Viable Alternative"
elif score >= 20:
return "Niche Player"
else:
return "Weak"
def gap_analysis(
your_scores: Dict[str, float],
competitor_scores: List[Dict[str, Any]],
dimensions: List[str]
) -> Dict[str, Any]:
"""Identify gaps between your product and competitors."""
gaps = {}
for dim in dimensions:
your_val = your_scores.get(dim, 0)
comp_vals = [c["dimensions"][dim]["raw"] for c in competitor_scores if dim in c.get("dimensions", {})]
if not comp_vals:
continue
avg_comp = mean(comp_vals)
best_comp = max(comp_vals)
gap_to_avg = round(your_val - avg_comp, 1)
gap_to_best = round(your_val - best_comp, 1)
gaps[dim] = {
"your_score": your_val,
"competitor_avg": round(avg_comp, 1),
"competitor_best": best_comp,
"gap_to_avg": gap_to_avg,
"gap_to_best": gap_to_best,
"status": "ahead" if gap_to_avg > 0.5 else ("behind" if gap_to_avg < -0.5 else "parity"),
"priority": "high" if gap_to_best < -2 else ("medium" if gap_to_best < -1 else "low")
}
return {
"gaps": gaps,
"biggest_opportunities": sorted(
[{"dimension": k, **v} for k, v in gaps.items() if v["status"] == "behind"],
key=lambda x: x["gap_to_best"]
)[:5],
"competitive_advantages": sorted(
[{"dimension": k, **v} for k, v in gaps.items() if v["status"] == "ahead"],
key=lambda x: -x["gap_to_avg"]
)[:5]
}
def positioning_analysis(scored: List[Dict[str, Any]]) -> Dict[str, Any]:
"""Generate positioning insights from scored competitors."""
scores = [c["overall_score"] for c in scored]
return {
"market_leaders": [c["name"] for c in scored if c["tier"] == "Leader"],
"your_rank": next((i + 1 for i, c in enumerate(scored) if c.get("is_you")), None),
"total_competitors": len(scored),
"score_distribution": {
"mean": round(mean(scores), 1) if scores else 0,
"stdev": round(stdev(scores), 1) if len(scores) > 1 else 0,
"min": round(min(scores), 1) if scores else 0,
"max": round(max(scores), 1) if scores else 0
},
"tier_distribution": {
tier: len([c for c in scored if c["tier"] == tier])
for tier in ["Leader", "Strong Competitor", "Viable Alternative", "Niche Player", "Weak"]
}
}
def format_text(result: Dict[str, Any]) -> str:
"""Format results as human-readable text."""
lines = []
lines.append("=" * 70)
lines.append("COMPETITIVE MATRIX ANALYSIS")
lines.append(f"Generated: {result['generated_at']}")
lines.append("=" * 70)
# Ranking table
lines.append("\n## COMPETITIVE RANKING\n")
lines.append(f"{'Rank':<6}{'Competitor':<25}{'Score':<10}{'Tier':<20}")
lines.append("-" * 61)
for i, c in enumerate(result["scored_competitors"], 1):
marker = " ← YOU" if c.get("is_you") else ""
lines.append(f"{i:<6}{c['name']:<25}{c['overall_score']:<10}{c['tier']:<20}{marker}")
# Dimension breakdown
lines.append("\n## DIMENSION BREAKDOWN\n")
dims = result["dimensions"]
header = f"{'Dimension':<20}" + "".join(f"{c['name'][:12]:<14}" for c in result["scored_competitors"])
lines.append(header)
lines.append("-" * len(header))
for dim in dims:
row = f"{dim:<20}"
for c in result["scored_competitors"]:
val = c["dimensions"].get(dim, {}).get("raw", "N/A")
row += f"{val:<14}"
lines.append(row)
# Gap analysis
if result.get("gap_analysis"):
ga = result["gap_analysis"]
if ga["biggest_opportunities"]:
lines.append("\n## BIGGEST OPPORTUNITIES (where you're behind)\n")
for opp in ga["biggest_opportunities"]:
lines.append(f" • {opp['dimension']}: You={opp['your_score']}, "
f"Best={opp['competitor_best']}, Gap={opp['gap_to_best']} "
f"[{opp['priority'].upper()} priority]")
if ga["competitive_advantages"]:
lines.append("\n## COMPETITIVE ADVANTAGES (where you lead)\n")
for adv in ga["competitive_advantages"]:
lines.append(f" • {adv['dimension']}: You={adv['your_score']}, "
f"Avg={adv['competitor_avg']}, Lead=+{adv['gap_to_avg']}")
# Positioning
pos = result.get("positioning", {})
if pos:
lines.append("\n## MARKET POSITIONING\n")
lines.append(f" Market Leaders: {', '.join(pos.get('market_leaders', ['None']))}")
if pos.get("your_rank"):
lines.append(f" Your Rank: #{pos['your_rank']} of {pos['total_competitors']}")
dist = pos.get("score_distribution", {})
lines.append(f" Score Range: {dist.get('min', 0)} - {dist.get('max', 0)} "
f"(avg: {dist.get('mean', 0)}, stdev: {dist.get('stdev', 0)})")
lines.append("\n" + "=" * 70)
return "\n".join(lines)
def build_matrix(data: Dict[str, Any], weight_overrides: Optional[Dict[str, float]] = None) -> Dict[str, Any]:
"""Main entry: build competitive matrix from input data."""
competitors = data.get("competitors", [])
dimensions = data.get("dimensions", [])
your_product = data.get("your_product", {})
if not competitors:
return {"error": "No competitors provided"}
if not dimensions:
# Auto-detect from first competitor's scores
dimensions = list(competitors[0].get("scores", {}).keys())
weights = data.get("weights", {})
if weight_overrides:
weights.update(weight_overrides)
# Include your product in scoring if provided
all_entries = list(competitors)
if your_product:
your_product["is_you"] = True
all_entries.insert(0, your_product)
scored = calculate_weighted_scores(all_entries, dimensions, weights)
# Mark your product
for s in scored:
if any(c.get("is_you") and c["name"] == s["name"] for c in all_entries):
s["is_you"] = True
result = {
"generated_at": datetime.now().isoformat(),
"dimensions": dimensions,
"weights": weights if weights else {d: 1.0 for d in dimensions},
"scored_competitors": scored,
"positioning": positioning_analysis(scored)
}
if your_product:
result["gap_analysis"] = gap_analysis(
your_product.get("scores", {}), scored, dimensions
)
return result
def parse_weights(weight_str: str) -> Dict[str, float]:
"""Parse weight string like 'pricing=2,ux=1.5' into dict."""
weights = {}
for pair in weight_str.split(","):
if "=" in pair:
k, v = pair.split("=", 1)
weights[k.strip()] = float(v.strip())
return weights
def main():
parser = argparse.ArgumentParser(
description="Build competitive matrix with scoring and gap analysis"
)
parser.add_argument("input", help="Path to competitors JSON file")
parser.add_argument("--format", choices=["json", "text"], default="text",
help="Output format (default: text)")
parser.add_argument("--weights", type=str, default=None,
help="Weight overrides: 'dim1=2.0,dim2=1.5'")
parser.add_argument("--output", type=str, default=None,
help="Output file path (default: stdout)")
args = parser.parse_args()
data = load_competitors(args.input)
weight_overrides = parse_weights(args.weights) if args.weights else None
result = build_matrix(data, weight_overrides)
if args.format == "json":
output = json.dumps(result, indent=2)
else:
output = format_text(result)
if args.output:
with open(args.output, "w") as f:
f.write(output)
print(f"Output written to {args.output}")
else:
print(output)
if __name__ == "__main__":
main()