Instructions HOW_TO_USE.md assets/expected_output.json assets/sample_input.json references/platform-benchmarks.md scripts/analyze_performance.py scripts/calculate_metrics.py
name: “social-media-analyzer”
description: Social media campaign analysis and performance tracking. Calculates engagement rates, ROI, and benchmarks across platforms. Use for analyzing social media performance, calculating engagement rate, measuring campaign ROI, comparing platform metrics, or benchmarking against industry standards.
triggers:
analyze social media
calculate engagement rate
social media ROI
campaign performance
compare platforms
benchmark engagement
Instagram analytics
Facebook metrics
TikTok performance
LinkedIn engagement
Campaign performance analysis with engagement metrics, ROI calculations, and platform benchmarks.
Table of Contents
Analysis Workflow
Analyze social media campaign performance:
Validate input data completeness (reach > 0, dates valid)
Calculate engagement metrics per post
Aggregate campaign-level metrics
Calculate ROI if ad spend provided
Compare against platform benchmarks
Identify top and bottom performers
Generate recommendations
Validation: Engagement rate < 100%, ROI matches spend data
Field Required Description platform Yes instagram, facebook, twitter, linkedin, tiktok posts[] Yes Array of post data posts[].likes Yes Like/reaction count posts[].comments Yes Comment count posts[].reach Yes Unique users reached posts[].impressions No Total views posts[].shares No Share/retweet count posts[].saves No Save/bookmark count posts[].clicks No Link clicks total_spend No Ad spend (for ROI)
Data Validation Checks
Before analysis, verify:
Engagement Metrics
Engagement Rate Calculation
Engagement Rate = (Likes + Comments + Shares + Saves) / Reach × 100
Metric Definitions
Metric Formula Interpretation Engagement Rate Engagements / Reach × 100 Audience interaction level CTR Clicks / Impressions × 100 Content click appeal Reach Rate Reach / Followers × 100 Content distribution Virality Rate Shares / Impressions × 100 Share-worthiness Save Rate Saves / Reach × 100 Content value
Rating Engagement Rate Action Excellent > 6% Scale and replicate Good 3-6% Optimize and expand Average 1-3% Test improvements Poor < 1% Analyze and pivot
ROI Calculation
Calculate return on ad spend:
Sum total engagements across posts
Calculate cost per engagement (CPE)
Calculate cost per click (CPC) if clicks available
Estimate engagement value using benchmark rates
Calculate ROI percentage
Validation: ROI = (Value - Spend) / Spend × 100
Metric Formula Cost Per Engagement (CPE) Total Spend / Total Engagements Cost Per Click (CPC) Total Spend / Total Clicks Cost Per Thousand (CPM) (Spend / Impressions) × 1000 Return on Ad Spend (ROAS) Revenue / Ad Spend
Engagement Value Estimates
Action Value Rationale Like $0.50 Brand awareness Comment $2.00 Active engagement Share $5.00 Amplification Save $3.00 Intent signal Click $1.50 Traffic value
ROI Interpretation
ROI % Rating Recommendation > 500% Excellent Scale budget significantly 200-500% Good Increase budget moderately 100-200% Acceptable Optimize before scaling 0-100% Break-even Review targeting and creative < 0% Negative Pause and restructure
Platform Average Good Excellent Instagram 1.22% 3-6% >6% Facebook 0.07% 0.5-1% >1% Twitter/X 0.05% 0.1-0.5% >0.5% LinkedIn 2.0% 3-5% >5% TikTok 5.96% 8-15% >15%
Platform Average Good Excellent Instagram 0.22% 0.5-1% >1% Facebook 0.90% 1.5-2.5% >2.5% LinkedIn 0.44% 1-2% >2% TikTok 0.30% 0.5-1% >1%
Platform Average Good Facebook $0.97 <$0.50 Instagram $1.20 <$0.70 LinkedIn $5.26 <$3.00 TikTok $1.00 <$0.50
See references/platform-benchmarks.md for complete benchmark data.
Calculate Metrics
python scripts/calculate_metrics.py assets/sample_input.json
Calculates engagement rate, CTR, reach rate for each post and campaign totals.
python scripts/analyze_performance.py assets/sample_input.json
Generates full performance analysis with ROI, benchmarks, and recommendations.
Output includes:
Campaign-level metrics
Post-by-post breakdown
Benchmark comparisons
Top performers ranked
Actionable recommendations
Examples
See assets/sample_input.json:
{
"platform" : "instagram" ,
"total_spend" : 500 ,
"posts" : [
{
"post_id" : "post_001" ,
"content_type" : "image" ,
"likes" : 342 ,
"comments" : 28 ,
"shares" : 15 ,
"saves" : 45 ,
"reach" : 5200 ,
"impressions" : 8500 ,
"clicks" : 120
}
]
}
Sample Output
See assets/expected_output.json:
{
"campaign_metrics" : {
"total_engagements" : 1521 ,
"avg_engagement_rate" : 8.36 ,
"ctr" : 1.55
},
"roi_metrics" : {
"total_spend" : 500.0 ,
"cost_per_engagement" : 0.33 ,
"roi_percentage" : 660.5
},
"insights" : {
"overall_health" : "excellent" ,
"benchmark_comparison" : {
"engagement_status" : "excellent" ,
"engagement_benchmark" : "1.22%" ,
"engagement_actual" : "8.36%"
}
}
}
Interpretation
The sample campaign shows:
Engagement rate 8.36% vs 1.22% benchmark = Excellent (6.8x above average)
CTR 1.55% vs 0.22% benchmark = Excellent (7x above average)
ROI 660% = Outstanding return on $500 spend
Recommendation: Scale budget, replicate successful elements
Reference Documentation
references/platform-benchmarks.md contains:
Engagement rate benchmarks by platform and industry
CTR benchmarks for organic and paid content
Cost benchmarks (CPC, CPM, CPE)
Content type performance by platform
Optimal posting times and frequency
ROI calculation formulas
Proactive Triggers
Engagement rate below platform average → Content isn’t resonating. Analyze top performers for patterns.
Follower growth stalled → Content distribution or frequency issue. Audit posting patterns.
High impressions, low engagement → Reach without resonance. Content quality issue.
Competitor outperforming significantly → Content gap. Analyze their successful posts.
Output Artifacts
When you ask for… You get… ”Social media audit” Performance analysis across platforms with benchmarks ”What’s performing?” Top content analysis with patterns and recommendations ”Competitor social analysis” Competitive social media comparison with gaps
Communication
All output passes quality verification:
Self-verify: source attribution, assumption audit, confidence scoring
Output format: Bottom Line → What (with confidence) → Why → How to Act
Results only. Every finding tagged: 🟢 verified, 🟡 medium, 🔴 assumed.
social-content : For creating social posts. Use this skill for analyzing performance.
campaign-analytics : For cross-channel analytics including social.
content-strategy : For planning social content themes.
marketing-context : Provides audience context for better analysis.
How to Use This Skill
Hey Claude—I just added the "social-media-analyzer" skill. Can you analyze this campaign's performance and give me actionable insights?
Example Invocations
Example 1:
Hey Claude—I just added the "social-media-analyzer" skill. Can you analyze this Instagram campaign data and tell me which posts performed best?
Example 2:
Hey Claude—I just added the "social-media-analyzer" skill. Can you calculate the ROI on this Facebook ad campaign with $1,200 spend?
Example 3:
Hey Claude—I just added the "social-media-analyzer" skill. Can you compare our engagement rates across Instagram, Facebook, and LinkedIn?
What to Provide
Social media campaign data (likes, comments, shares, reach, impressions)
Platform name (Instagram, Facebook, Twitter, LinkedIn, TikTok)
Ad spend amount (for ROI calculations)
Time period of the campaign
Post details (type, content, posting time - optional but helpful)
What You'll Get
Campaign Performance Metrics : Engagement rate, CTR, reach, impressions
ROI Analysis : Cost per engagement, cost per click, return on investment
Benchmark Comparison : How your campaign compares to industry standards
Top Performing Posts : Which content resonated most with your audience
Actionable Recommendations : Specific steps to improve future campaigns
Visual Report : Charts and graphs (Excel/PDF format)
Tips for Best Results
Include complete data : More metrics = more accurate insights
Specify platform : Different platforms have different benchmark standards
Provide context : Mention campaign goals, target audience, or special events
Compare time periods : Ask for month-over-month or campaign-to-campaign comparisons
Request specific analysis : Focus on engagement, ROI, or specific metrics you care about
{
"campaign_metrics" : {
"platform" : "instagram" ,
"total_posts" : 3 ,
"total_engagements" : 1521 ,
"total_reach" : 18200 ,
"total_impressions" : 27700 ,
"total_clicks" : 430 ,
"avg_engagement_rate" : 8.36 ,
"ctr" : 1.55
},
"roi_metrics" : {
"total_spend" : 500.0 ,
"cost_per_engagement" : 0.33 ,
"cost_per_click" : 1.16 ,
"estimated_value" : 3802.5 ,
"roi_percentage" : 660.5
},
"top_posts" : [
{
"post_id" : "post_002" ,
"content_type" : "video" ,
"engagement_rate" : 8.18 ,
"likes" : 587 ,
"reach" : 8900
},
{
"post_id" : "post_001" ,
"content_type" : "image" ,
"engagement_rate" : 8.27 ,
"likes" : 342 ,
"reach" : 5200
},
{
"post_id" : "post_003" ,
"content_type" : "carousel" ,
"engagement_rate" : 8.85 ,
"likes" : 298 ,
"reach" : 4100
}
],
"insights" : {
"overall_health" : "excellent" ,
"benchmark_comparison" : {
"engagement_status" : "excellent" ,
"engagement_benchmark" : "1.22%" ,
"engagement_actual" : "8.36%" ,
"ctr_status" : "excellent" ,
"ctr_benchmark" : "0.22%" ,
"ctr_actual" : "1.55%"
},
"recommendations" : [
"Excellent ROI (660.5%)! Consider: (1) Scaling this campaign with increased budget, (2) Replicating successful elements to other campaigns, (3) Testing similar audiences"
],
"key_strengths" : [
"Strong audience engagement" ,
"Excellent return on investment" ,
"High click-through rate"
]
}
}
{
"platform" : "instagram" ,
"total_spend" : 500 ,
"posts" : [
{
"post_id" : "post_001" ,
"content_type" : "image" ,
"likes" : 342 ,
"comments" : 28 ,
"shares" : 15 ,
"saves" : 45 ,
"reach" : 5200 ,
"impressions" : 8500 ,
"clicks" : 120 ,
"posted_at" : "2025-10-15T14:30:00Z"
},
{
"post_id" : "post_002" ,
"content_type" : "video" ,
"likes" : 587 ,
"comments" : 42 ,
"shares" : 31 ,
"saves" : 68 ,
"reach" : 8900 ,
"impressions" : 12400 ,
"clicks" : 215 ,
"posted_at" : "2025-10-16T18:45:00Z"
},
{
"post_id" : "post_003" ,
"content_type" : "carousel" ,
"likes" : 298 ,
"comments" : 19 ,
"shares" : 12 ,
"saves" : 34 ,
"reach" : 4100 ,
"impressions" : 6800 ,
"clicks" : 95 ,
"posted_at" : "2025-10-18T12:15:00Z"
}
]
}
Social Media Platform Benchmarks
Industry benchmarks for engagement rates, CTR, and ROI by platform.
Table of Contents
Engagement Rate Benchmarks
By Platform (2024-2025)
Platform
Average ER
Good ER
Excellent ER
Instagram
1.22%
3-6%
>6%
Facebook
0.07%
0.5-1%
>1%
Twitter/X
0.05%
0.1-0.5%
>0.5%
LinkedIn
2.0%
3-5%
>5%
TikTok
5.96%
8-15%
>15%
Engagement Rate Formula
Engagement Rate = (Likes + Comments + Shares + Saves) / Reach × 100 Alternative (by followers):
Engagement Rate = (Likes + Comments + Shares) / Followers × 100 By Industry
Industry
Instagram
Facebook
LinkedIn
Retail
1.0%
0.08%
1.8%
Technology
0.9%
0.06%
2.5%
Healthcare
1.5%
0.12%
2.2%
Finance
0.8%
0.05%
2.8%
Food & Beverage
1.8%
0.15%
1.5%
Travel
1.4%
0.10%
1.9%
B2B Services
0.7%
0.04%
3.2%
Click-Through Rate Benchmarks
Organic CTR by Platform
Platform
Average CTR
Good CTR
Excellent CTR
Instagram
0.22%
0.5-1%
>1%
Facebook
0.90%
1.5-2.5%
>2.5%
Twitter/X
0.86%
1.5-2%
>2%
LinkedIn
0.44%
1-2%
>2%
TikTok
0.30%
0.5-1%
>1%
Paid Ad CTR by Platform
Platform
Average CTR
Good CTR
Excellent CTR
Facebook Ads
0.90%
1.5-2%
>2%
Instagram Ads
0.58%
1-1.5%
>1.5%
LinkedIn Ads
0.44%
0.8-1.2%
>1.2%
Twitter Ads
1.55%
2-3%
>3%
TikTok Ads
0.84%
1.5-2%
>2%
Cost Benchmarks
Cost Per Click (CPC)
Platform
Average CPC
Low CPC
Industry Range
Facebook
$0.97
<$0.50
$0.50-$2.00
Instagram
$1.20
<$0.70
$0.70-$3.00
LinkedIn
$5.26
<$3.00
$3.00-$8.00
Twitter
$0.38
<$0.25
$0.25-$1.00
TikTok
$1.00
<$0.50
$0.50-$2.00
Cost Per Thousand Impressions (CPM)
Platform
Average CPM
Low CPM
Industry Range
Facebook
$7.19
<$5.00
$5.00-$15.00
Instagram
$7.91
<$5.00
$5.00-$15.00
LinkedIn
$33.80
<$20.00
$20.00-$50.00
Twitter
$6.46
<$4.00
$4.00-$12.00
TikTok
$10.00
<$6.00
$6.00-$15.00
Cost Per Engagement (CPE)
Platform
Average CPE
Good CPE
Facebook
$0.12
<$0.08
Instagram
$0.15
<$0.10
LinkedIn
$0.80
<$0.50
Twitter
$0.08
<$0.05
TikTok
$0.10
<$0.06
Content Type Performance
Instagram
Content Type
Avg Engagement
Best Use Case
Reels
1.95%
Discovery, viral potential
Carousels
1.92%
Education, storytelling
Single Image
1.18%
Product showcase
Stories
0.5% swipe-up
Time-sensitive, behind-scenes
Facebook
Content Type
Avg Engagement
Best Use Case
Video
0.26%
Brand awareness
Photo
0.12%
Quick updates
Link
0.05%
Traffic driving
Status
0.04%
Community engagement
LinkedIn
Content Type
Avg Engagement
Best Use Case
Document/PDF
3.5%
Thought leadership
Native Video
2.8%
Personal brand
Image
2.0%
Announcements
Text Only
1.8%
Professional insights
Link
1.2%
Content sharing
TikTok
Content Type
Avg Engagement
Best Use Case
Trending Sound
8-12%
Discovery, virality
Tutorial
6-10%
Education, value
Behind-Scenes
5-8%
Authenticity
Product Demo
4-7%
Conversion
Posting Time Optimization
Best Posting Times by Platform
Instagram:
Best days: Tuesday, Wednesday, Thursday
Best times: 11 AM, 2 PM, 7 PM (local time)
Worst: Sunday mornings
Facebook:
Best days: Wednesday, Thursday, Friday
Best times: 9 AM, 1 PM, 4 PM
Worst: Weekends before noon
LinkedIn:
Best days: Tuesday, Wednesday, Thursday
Best times: 7-8 AM, 12 PM, 5-6 PM
Worst: Weekends
Twitter/X:
Best days: Wednesday, Thursday
Best times: 8 AM, 12 PM, 5 PM
Worst: Late night (after 10 PM)
TikTok:
Best days: Tuesday, Thursday, Friday
Best times: 7 PM, 8 PM, 9 PM
Worst: Early mornings
Posting Frequency
Platform
Minimum
Optimal
Maximum
Instagram
3/week
1-2/day
3/day
Facebook
3/week
1/day
2/day
LinkedIn
2/week
1/day
2/day
Twitter
1/day
3-5/day
10/day
TikTok
3/week
1-3/day
5/day
ROI Calculation
Standard ROI Formula
ROI = ((Revenue - Cost) / Cost) × 100 Social Media ROI Components
Metric
Formula
Cost Per Click (CPC)
Total Spend / Total Clicks
Cost Per Engagement (CPE)
Total Spend / Total Engagements
Cost Per Thousand (CPM)
(Total Spend / Impressions) × 1000
Return on Ad Spend (ROAS)
Revenue / Ad Spend
Customer Acquisition Cost (CAC)
Total Spend / New Customers
Engagement Value Estimation
Action
Estimated Value
Like
$0.50
Comment
$2.00
Share
$5.00
Save
$3.00
Click
$1.50
Follow
$10.00
Total Engagement Value:
Value = (Likes × $0.50) + (Comments × $2.00) + (Shares × $5.00) + (Saves × $3.00) + (Clicks × $1.50) """
Performance analysis and recommendation module.
Provides insights and optimization recommendations.
"""
from typing import Dict, List, Any
class PerformanceAnalyzer :
"""Analyze campaign performance and generate recommendations."""
# Industry benchmark ranges
BENCHMARKS = {
'facebook' : { 'engagement_rate' : 0.09 , 'ctr' : 0.90 },
'instagram' : { 'engagement_rate' : 1.22 , 'ctr' : 0.22 },
'twitter' : { 'engagement_rate' : 0.045 , 'ctr' : 1.64 },
'linkedin' : { 'engagement_rate' : 0.54 , 'ctr' : 0.39 },
'tiktok' : { 'engagement_rate' : 5.96 , 'ctr' : 1.00 }
}
def __init__ (self, campaign_metrics: Dict[ str , Any], roi_metrics: Dict[ str , Any]):
"""
Initialize with calculated metrics.
Args:
campaign_metrics: Dictionary of campaign performance metrics
roi_metrics: Dictionary of ROI and cost metrics
"""
self .campaign_metrics = campaign_metrics
self .roi_metrics = roi_metrics
self .platform = campaign_metrics.get( 'platform' , 'unknown' ).lower()
def benchmark_performance (self) -> Dict[ str , str ]:
"""Compare metrics against industry benchmarks."""
benchmarks = self . BENCHMARKS .get( self .platform, {})
if not benchmarks:
return { 'status' : 'no_benchmark_available' }
engagement_rate = self .campaign_metrics.get( 'avg_engagement_rate' , 0 )
ctr = self .campaign_metrics.get( 'ctr' , 0 )
benchmark_engagement = benchmarks.get( 'engagement_rate' , 0 )
benchmark_ctr = benchmarks.get( 'ctr' , 0 )
engagement_status = 'excellent' if engagement_rate >= benchmark_engagement * 1.5 else \
'good' if engagement_rate >= benchmark_engagement else \
'below_average'
ctr_status = 'excellent' if ctr >= benchmark_ctr * 1.5 else \
'good' if ctr >= benchmark_ctr else \
'below_average'
return {
'engagement_status' : engagement_status,
'engagement_benchmark' : f " { benchmark_engagement } %" ,
'engagement_actual' : f " { engagement_rate :.2f } %" ,
'ctr_status' : ctr_status,
'ctr_benchmark' : f " { benchmark_ctr } %" ,
'ctr_actual' : f " { ctr :.2f } %"
}
def generate_recommendations (self) -> List[ str ]:
"""Generate actionable recommendations based on performance."""
recommendations = []
# Analyze engagement rate
engagement_rate = self .campaign_metrics.get( 'avg_engagement_rate' , 0 )
if engagement_rate < 1.0 :
recommendations.append(
"Low engagement rate detected. Consider: (1) Posting during peak audience activity times, "
"(2) Using more interactive content formats (polls, questions), "
"(3) Improving visual quality of posts"
)
# Analyze CTR
ctr = self .campaign_metrics.get( 'ctr' , 0 )
if ctr < 0.5 :
recommendations.append(
"Click-through rate is below average. Try: (1) Stronger call-to-action statements, "
"(2) More compelling headlines, (3) Better alignment between content and audience interests"
)
# Analyze cost efficiency
cpc = self .roi_metrics.get( 'cost_per_click' , 0 )
if cpc > 1.00 :
recommendations.append(
f "Cost per click ($ { cpc :.2f } ) is high. Optimize by: (1) Refining audience targeting, "
"(2) Testing different ad creatives, (3) Adjusting bidding strategy"
)
# Analyze ROI
roi = self .roi_metrics.get( 'roi_percentage' , 0 )
if roi < 100 :
recommendations.append(
f "ROI ( { roi :.1f } %) needs improvement. Focus on: (1) Conversion rate optimization, "
"(2) Reducing cost per acquisition, (3) Better audience segmentation"
)
elif roi > 200 :
recommendations.append(
f "Excellent ROI ( { roi :.1f } %)! Consider: (1) Scaling this campaign with increased budget, "
"(2) Replicating successful elements to other campaigns, (3) Testing similar audiences"
)
# Post frequency analysis
total_posts = self .campaign_metrics.get( 'total_posts' , 0 )
if total_posts < 10 :
recommendations.append(
"Limited post volume may affect insights accuracy. Consider increasing posting frequency "
"to gather more performance data"
)
# Default positive recommendation if performing well
if not recommendations:
recommendations.append(
"Campaign is performing well across all metrics. Continue current strategy while "
"testing minor variations to optimize further"
)
return recommendations
def generate_insights (self) -> Dict[ str , Any]:
"""Generate comprehensive performance insights."""
benchmark_results = self .benchmark_performance()
recommendations = self .generate_recommendations()
# Determine overall campaign health
engagement_status = benchmark_results.get( 'engagement_status' , 'unknown' )
ctr_status = benchmark_results.get( 'ctr_status' , 'unknown' )
if engagement_status == 'excellent' and ctr_status == 'excellent' :
overall_health = 'excellent'
elif engagement_status in [ 'good' , 'excellent' ] and ctr_status in [ 'good' , 'excellent' ]:
overall_health = 'good'
else :
overall_health = 'needs_improvement'
return {
'overall_health' : overall_health,
'benchmark_comparison' : benchmark_results,
'recommendations' : recommendations,
'key_strengths' : self ._identify_strengths(),
'areas_for_improvement' : self ._identify_weaknesses()
}
def _identify_strengths (self) -> List[ str ]:
"""Identify campaign strengths."""
strengths = []
engagement_rate = self .campaign_metrics.get( 'avg_engagement_rate' , 0 )
if engagement_rate > 1.0 :
strengths.append( "Strong audience engagement" )
roi = self .roi_metrics.get( 'roi_percentage' , 0 )
if roi > 150 :
strengths.append( "Excellent return on investment" )
ctr = self .campaign_metrics.get( 'ctr' , 0 )
if ctr > 1.0 :
strengths.append( "High click-through rate" )
return strengths if strengths else [ "Campaign shows baseline performance" ]
def _identify_weaknesses (self) -> List[ str ]:
"""Identify areas needing improvement."""
weaknesses = []
engagement_rate = self .campaign_metrics.get( 'avg_engagement_rate' , 0 )
if engagement_rate < 0.5 :
weaknesses.append( "Low engagement rate - content may not resonate with audience" )
roi = self .roi_metrics.get( 'roi_percentage' , 0 )
if roi < 50 :
weaknesses.append( "ROI below target - need to improve conversion or reduce costs" )
cpc = self .roi_metrics.get( 'cost_per_click' , 0 )
if cpc > 2.00 :
weaknesses.append( "High cost per click - targeting or bidding needs optimization" )
return weaknesses if weaknesses else [ "No critical weaknesses identified" ]
"""
Social media metrics calculation module.
Provides functions to calculate engagement, reach, and ROI metrics.
"""
from typing import Dict, List, Any, Optional
from datetime import datetime
class SocialMediaMetricsCalculator :
"""Calculate social media performance metrics."""
def __init__ (self, campaign_data: Dict[ str , Any]):
"""
Initialize with campaign data.
Args:
campaign_data: Dictionary containing platform, posts, and cost data
"""
self .platform = campaign_data.get( 'platform' , 'unknown' )
self .posts = campaign_data.get( 'posts' , [])
self .total_spend = campaign_data.get( 'total_spend' , 0 )
self .metrics = {}
def safe_divide (self, numerator: float , denominator: float , default: float = 0.0 ) -> float :
"""Safely divide two numbers, returning default if denominator is zero."""
if denominator == 0 :
return default
return numerator / denominator
def calculate_engagement_rate (self, post: Dict[ str , Any]) -> float :
"""
Calculate engagement rate for a post.
Args:
post: Dictionary with likes, comments, shares, and reach
Returns:
Engagement rate as percentage
"""
likes = post.get( 'likes' , 0 )
comments = post.get( 'comments' , 0 )
shares = post.get( 'shares' , 0 )
saves = post.get( 'saves' , 0 )
reach = post.get( 'reach' , 0 )
total_engagements = likes + comments + shares + saves
engagement_rate = self .safe_divide(total_engagements, reach) * 100
return round (engagement_rate, 2 )
def calculate_ctr (self, clicks: int , impressions: int ) -> float :
"""
Calculate click-through rate.
Args:
clicks: Number of clicks
impressions: Number of impressions
Returns:
CTR as percentage
"""
ctr = self .safe_divide(clicks, impressions) * 100
return round (ctr, 2 )
def calculate_campaign_metrics (self) -> Dict[ str , Any]:
"""Calculate overall campaign metrics."""
total_likes = sum (post.get( 'likes' , 0 ) for post in self .posts)
total_comments = sum (post.get( 'comments' , 0 ) for post in self .posts)
total_shares = sum (post.get( 'shares' , 0 ) for post in self .posts)
total_reach = sum (post.get( 'reach' , 0 ) for post in self .posts)
total_impressions = sum (post.get( 'impressions' , 0 ) for post in self .posts)
total_clicks = sum (post.get( 'clicks' , 0 ) for post in self .posts)
total_engagements = total_likes + total_comments + total_shares
return {
'platform' : self .platform,
'total_posts' : len ( self .posts),
'total_engagements' : total_engagements,
'total_reach' : total_reach,
'total_impressions' : total_impressions,
'total_clicks' : total_clicks,
'avg_engagement_rate' : self .safe_divide(total_engagements, total_reach) * 100 ,
'ctr' : self .calculate_ctr(total_clicks, total_impressions)
}
def calculate_roi_metrics (self) -> Dict[ str , float ]:
"""Calculate ROI and cost efficiency metrics."""
campaign_metrics = self .calculate_campaign_metrics()
total_engagements = campaign_metrics[ 'total_engagements' ]
total_clicks = campaign_metrics[ 'total_clicks' ]
cost_per_engagement = self .safe_divide( self .total_spend, total_engagements)
cost_per_click = self .safe_divide( self .total_spend, total_clicks)
# Assuming average value per engagement (can be customized)
avg_value_per_engagement = 2.50 # Example: $2.50 value per engagement
total_value = total_engagements * avg_value_per_engagement
roi_percentage = self .safe_divide(total_value - self .total_spend, self .total_spend) * 100
return {
'total_spend' : round ( self .total_spend, 2 ),
'cost_per_engagement' : round (cost_per_engagement, 2 ),
'cost_per_click' : round (cost_per_click, 2 ),
'estimated_value' : round (total_value, 2 ),
'roi_percentage' : round (roi_percentage, 2 )
}
def identify_top_posts (self, metric: str = 'engagement_rate' , limit: int = 5 ) -> List[Dict[ str , Any]]:
"""
Identify top performing posts.
Args:
metric: Metric to sort by (engagement_rate, likes, shares, etc.)
limit: Number of top posts to return
Returns:
List of top performing posts with metrics
"""
posts_with_metrics = []
for post in self .posts:
post_copy = post.copy()
post_copy[ 'engagement_rate' ] = self .calculate_engagement_rate(post)
posts_with_metrics.append(post_copy)
# Sort by specified metric
if metric == 'engagement_rate' :
sorted_posts = sorted (posts_with_metrics,
key =lambda x: x[ 'engagement_rate' ],
reverse = True )
else :
sorted_posts = sorted (posts_with_metrics,
key =lambda x: x.get(metric, 0 ),
reverse = True )
return sorted_posts[:limit]
def analyze_all (self) -> Dict[ str , Any]:
"""Run complete analysis."""
return {
'campaign_metrics' : self .calculate_campaign_metrics(),
'roi_metrics' : self .calculate_roi_metrics(),
'top_posts' : self .identify_top_posts()
}