Spaces:
Running
Running
| """ | |
| Utility functions for the Media Planning Simulator | |
| """ | |
| def calculate_cpm(budget: float, impressions: int) -> float: | |
| """Calculate CPM (Cost Per Mille)""" | |
| if impressions == 0: | |
| return 0 | |
| return (budget / impressions) * 1000 | |
| def calculate_ctr(clicks: int, impressions: int) -> float: | |
| """Calculate CTR (Click-Through Rate)""" | |
| if impressions == 0: | |
| return 0 | |
| return (clicks / impressions) * 100 | |
| def calculate_cpc(spend: float, clicks: int) -> float: | |
| """Calculate CPC (Cost Per Click)""" | |
| if clicks == 0: | |
| return 0 | |
| return spend / clicks | |
| def calculate_conversion_rate(conversions: int, clicks: int) -> float: | |
| """Calculate Conversion Rate""" | |
| if clicks == 0: | |
| return 0 | |
| return (conversions / clicks) * 100 | |
| def calculate_roi(revenue: float, investment: float) -> float: | |
| """Calculate ROI (Return on Investment)""" | |
| if investment == 0: | |
| return 0 | |
| return ((revenue - investment) / investment) * 100 | |
| def calculate_roas(revenue: float, ad_spend: float) -> float: | |
| """Calculate ROAS (Return on Ad Spend)""" | |
| if ad_spend == 0: | |
| return 0 | |
| return revenue / ad_spend | |
| def calculate_clv( | |
| avg_purchase_value: float, | |
| purchase_frequency: float, | |
| customer_lifespan: float, | |
| acquisition_cost: float | |
| ) -> float: | |
| """Calculate CLV (Customer Lifetime Value)""" | |
| return (avg_purchase_value * purchase_frequency * customer_lifespan) - acquisition_cost | |
| def format_currency_eur(value: float) -> str: | |
| """Format value as Euro currency""" | |
| return f"€{value:,.2f}" | |
| def format_percentage_value(value: float, decimals: int = 2) -> str: | |
| """Format value as percentage string""" | |
| return f"{value:.{decimals}f}%" | |
| def create_summary_dataframe(metrics: dict) -> pd.DataFrame: | |
| """Create a summary DataFrame from metrics dictionary""" | |
| summary_items = [ | |
| ("Impression Totali", metrics.get("total_impressions", 0)), | |
| ("Click Totali", metrics.get("total_clicks", 0)), | |
| ("Conversioni Totali", metrics.get("total_conversions", 0)), | |
| ("Ricavi Totali (€)", metrics.get("total_revenue", 0)), | |
| ("Spesa Pubblicitaria (€)", metrics.get("total_ad_spend", 0)), | |
| ("Margine Netto (€)", metrics.get("net_margin", 0)), | |
| ("ROI (%)", metrics.get("roi", 0)), | |
| ("ROAS", metrics.get("roas", 0)), | |
| ("CPA (€)", metrics.get("cpa", 0)), | |
| ("CLV (€)", metrics.get("clv", 0)), | |
| ] | |
| return pd.DataFrame(summary_items, columns=["Metrica", "Valore"]) |