API Reference¶
This section documents the public API of the dxpoint library.
Single-Channel Model Interface¶
- class dxpoint.models.MarketingReturnCurve(beta, alpha, half_saturation_k, theta=0.0, channel_name='Generic', posterior_samples=None, baseline=0.0, adstock_type='geometric', adstock_params=None, standard_errors=None, confidence_intervals=None, covariance_matrix=None, train_spend=None, train_return=None, calibration_experiments=None)[source]¶
Bases:
objectA marketing intelligence tool to determine inflection points of a media response curve.
Based on the Hill Function (Google Meridian methodology), this tool identifies the Minimal Marginal Cost Point (peak efficiency) and the Point of Diminishing Returns (profitability floor).
- add_experiment(spend, lift, se=None, ci=None, name=None)[source]¶
Convenience method to add a single incrementality experiment to this curve.
- adstock_spend(spend_timeline)[source]¶
Applies the model’s fitted adstock decay (geometric or Weibull) to a timeline of spends.
- attach_experiments(experiments)[source]¶
Associates one or more incrementality experiments with this channel curve.
- Parameters:
experiments – Dict or list of dicts with keys (‘spend’, ‘lift’, and optional ‘se’ / ‘ci’ / ‘name’).
- evaluate_fit(spend_array=None, return_array=None, verbose=False)[source]¶
Evaluates statistical goodness-of-fit metrics (R², Adj R², RMSE, MAE, MAPE, AIC, BIC).
- classmethod fit(spend_array, return_array, channel_name='Generic', method='auto', adstock_type='none', adstock_bounds=None, adstock_fixed_days=None, fit_baseline=False, confidence_level=0.95, priors=None, n_samples=2000, chains=4, burn_in=1000, calibration_experiments=None, epochs=5000, lr=0.05)[source]¶
Unified entry point for fitting saturation and adstock curves to historical media data.
Supported methods: - ‘auto’: Selects ‘bayesian’ if calibration_experiments/priors are given, else ‘frequentist’. - ‘frequentist’ (or ‘nls’): Non-Linear Least Squares with parameter standard errors and confidence intervals. - ‘gradient_descent’ (or ‘gradient’, ‘mle’): Gradient descent optimization via Tinygrad. - ‘bayesian’ (or ‘mcmc’): Metropolis-Hastings MCMC with posterior sampling and experimental calibration.
- classmethod fit_bayesian(spend_array, return_array, channel_name='Generic', priors=None, n_samples=2000, chains=4, burn_in=1000, adstock_type='none', adstock_bounds=None, adstock_fixed_days=None, calibration_experiments=None, fit_baseline=False)[source]¶
- classmethod fit_frequentist(spend_array, return_array, channel_name='Generic', adstock_type='none', adstock_bounds=None, adstock_fixed_days=None, fit_baseline=False, confidence_level=0.95)[source]¶
Fits a Hill Curve to historical data using Frequentist Non-Linear Least Squares (NLS).
- classmethod fit_gradient_descent(spend_array, return_array, channel_name='Generic', epochs=5000, lr=0.05, adstock_type='none', adstock_bounds=None, adstock_fixed_days=None, fit_baseline=False)[source]¶
Fits a Hill Curve to historical data using Gradient Descent (Tinygrad Adam).
- get_diminishing_returns_point(target_mroas=1.0, tol=1e-05, max_iter=100, warn_unreachable=True)[source]¶
- get_optimal_scaling_window(target_mroas=1.0)[source]¶
Returns the tuple (min_spend, max_spend) defining the optimal scaling zone.
- property max_efficiency_point¶
- property max_profit_point¶
- plot_response_curve(target_mroas=1.0, current_spend=None, show_intervals=True, scatter=None, show=True, include_baseline=False)[source]¶
- predict_incremental_return(spend, return_interval=False, confidence_level=0.95, use_samples=False, include_baseline=False)[source]¶
- predict_marginal_return(spend, return_interval=False, confidence_level=0.95, use_samples=False)[source]¶
- project_capacity(m_beta=None, m_k=None, tam_size=None, current_reach=None, target_reach=None, current_reach_penetration=None, target_reach_penetration=None, current_frequency=None, target_frequency=None, reach_elasticity=0.65, frequency_elasticity=0.5, spend_reach_elasticity=0.75, frequency_capacity_factor=0.15, m_beta_product=None, m_k_product=None, current_funnel=None, target_funnel=None, funnel_multipliers=None, vertical=None, vertical_multipliers=None, synergy_damping=0.85, channel_name=None)[source]¶
Projects scaling capacity and returns an augmented ProjectedReturnCurve.
Applies user-defined multipliers or derived Reach & Frequency / Funnel expansion multipliers using the damped synergy formulation.
- validate_experiment(experiment=None, spend_is_raw=True, verbose=False)[source]¶
Convenience alias for validating a single incrementality experiment.
- validate_experiments(experiments=None, spend_is_raw=True, verbose=False)[source]¶
Validates this response curve against one or more incrementality experiments.
- Parameters:
experiments – Single experiment dict or list of dicts. If None, uses attached experiments.
spend_is_raw – If True and model has theta > 0, converts raw test spend to effective adstocked spend via S_eff = S_raw / (1 - theta).
verbose – If True, prints a formatted validation report to stdout.
- Returns:
Detailed validation metrics including errors, Z-scores, CI coverage, chi2, and verdict.
- Return type:
dict
Multi-Channel Response Modeling¶
- dxpoint.multichannel.MultiChannelMMM¶
alias of
MultiChannelModel
- class dxpoint.multichannel.MultiChannelModel(channels, baseline=0.0, loss=0.0, posterior_samples=None, calibration_experiments=None)[source]¶
Bases:
objectMulti-channel joint response and saturation model.
- Jointly estimates:
Y_t = Baseline + sum_{m=1}^M Hill_m(Adstock_m(S_{m, 1:t})) + eps_t
- Key Capabilities:
Multi-channel partial pooling across channels & geos.
Joint simultaneous estimation of Carryover Adstock (theta), Hill Saturation (alpha, K), and Channel Return Coefficients (beta).
Prevents cross-channel double-counting and omitted variable bias.
Experimental calibration (lift studies, geo experiments) integration.
Historical contribution decomposition and channel efficiency analysis.
Direct integration with PortfolioAllocator for global budget optimization.
- add_experiment(channel, spend, lift, se=None, ci=None, name=None)[source]¶
Convenience method to associate an incrementality test with a specific channel.
- attach_experiments(experiments)[source]¶
Associates incrementality experiments in parallel across channels.
- Parameters:
experiments – Dict mapping {channel_name: [exps] | exp} or flat list of dicts with ‘channel’ key.
- decompose_historical_contributions(spend_data, return_array=None)[source]¶
Computes comprehensive historical attribution, share of spend vs return, and channel ROI.
- Returns:
‘contributions_df’: pd.DataFrame with time-series breakdown of Baseline and all channels.
- ’summary_table’: pd.DataFrame with Channel, Total Spend, Total Contribution,
Share of Spend (%), Share of Return (%), ROI, and current mROAS.
’total_predicted’: np.ndarray of total model predictions.
- Return type:
dict containing
- classmethod fit(spend_data, return_array, channel_names=None, method='auto', epochs=5000, lr=0.05, fit_baseline=True, adstock_types=None, adstock_bounds=None, adstock_fixed_days=None, n_samples=2000, chains=4, burn_in=1000, hierarchical=True, calibration_experiments=None)[source]¶
Unified entry point for fitting multi-channel marketing mix models.
- classmethod fit_bayesian(spend_data, return_array, channel_names=None, n_samples=2000, chains=4, burn_in=1000, fit_baseline=True, hierarchical=True, adstock_types=None, adstock_bounds=None, adstock_fixed_days=None, calibration_experiments=None)[source]¶
Fits a joint multi-channel model using Hierarchical Bayesian MCMC inference.
- classmethod fit_gradient_descent(spend_data, return_array, channel_names=None, epochs=5000, lr=0.05, fit_baseline=True, adstock_types=None, adstock_bounds=None, adstock_fixed_days=None)[source]¶
Fits a joint multi-channel model using Gradient Descent (MLE / Tinygrad Adam).
- classmethod fit_hierarchical_bayesian(spend_data, return_array, channel_names=None, n_samples=2000, chains=4, burn_in=1000, fit_baseline=True, hierarchical=True, adstock_types=None, adstock_bounds=None, adstock_fixed_days=None, calibration_experiments=None)¶
Fits a joint multi-channel model using Hierarchical Bayesian MCMC inference.
- predict_channel_contributions(spend_dict, use_samples=False)[source]¶
Decomposes response into individual channel incremental contributions and baseline.
Supports both single-period scalar spend queries and multi-period time-series arrays.
- predict_total_return(spend_dict, use_samples=False)[source]¶
Predicts total response (baseline + all channel responses) given a dictionary of channel spends.
Supports both single-period scalars and multi-period 1D numpy arrays.
- summary()[source]¶
Returns a dictionary summarizing all channel curves, baseline, and MCMC diagnostics.
- validate_experiments(experiments=None, spend_is_raw=True, verbose=False)[source]¶
Validates multi-channel curves against a collection of channel-specific incrementality experiments.
- Parameters:
experiments – List of experiment dicts, or dict keyed by channel name. If None, uses attached experiments.
spend_is_raw – If True, scales raw daily test spend by (1 - theta) to evaluate against effective adstock.
verbose – If True, prints a multi-channel validation summary to stdout.
- Returns:
Multi-channel validation summary with per-channel breakdown and global metrics.
- Return type:
dict
- dxpoint.multichannel.fit_multichannel_bayesian_mcmc(spend_data, return_array, channel_names=None, n_samples=2000, chains=4, burn_in=1000, fit_baseline=True, hierarchical=True, adstock_types=None, adstock_bounds=None, adstock_fixed_days=None, calibration_experiments=None)¶
Fits a Meridian-lite Hierarchical Bayesian Marketing Mix Model.
- Features:
Hierarchical shrinkage (partial pooling) across channels for capacity (beta), S-curve steepness (alpha), half-saturation (K), and carryover decay (theta).
Optional Geo-level hierarchical partial pooling when geo/regional data is provided.
Joint simultaneous MCMC estimation of carryover adstock, Hill saturation, baseline, and channel coefficients in transformed unconstrained parameter space.
Experimental lift calibration seamlessly integrated into the joint log-likelihood.
Convergence diagnostics including Gelman-Rubin R-hat and acceptance rates.
- dxpoint.multichannel.fit_multichannel_gradient(spend_data, return_array, channel_names=None, epochs=5000, lr=0.05, fit_baseline=True, adstock_types=None, adstock_bounds=None, adstock_fixed_days=None)[source]¶
Fits a joint Multi-Channel Marketing Mix Model using Gradient Descent (Tinygrad Adam).
- dxpoint.multichannel.fit_multichannel_hierarchical_bayesian(spend_data, return_array, channel_names=None, n_samples=2000, chains=4, burn_in=1000, fit_baseline=True, hierarchical=True, adstock_types=None, adstock_bounds=None, adstock_fixed_days=None, calibration_experiments=None)[source]¶
Fits a Meridian-lite Hierarchical Bayesian Marketing Mix Model.
- Features:
Hierarchical shrinkage (partial pooling) across channels for capacity (beta), S-curve steepness (alpha), half-saturation (K), and carryover decay (theta).
Optional Geo-level hierarchical partial pooling when geo/regional data is provided.
Joint simultaneous MCMC estimation of carryover adstock, Hill saturation, baseline, and channel coefficients in transformed unconstrained parameter space.
Experimental lift calibration seamlessly integrated into the joint log-likelihood.
Convergence diagnostics including Gelman-Rubin R-hat and acceptance rates.
Portfolio Optimization¶
- class dxpoint.portfolio.PortfolioAllocator(models)[source]¶
Bases:
objectOptimizes budget allocation across multiple MarketingReturnCurve models.
- add_experiment(channel, spend, lift, se=None, ci=None, name=None)[source]¶
Convenience method to associate an incrementality test with a specific portfolio channel.
- allocate_budget(total_budget, channel_bounds=None)[source]¶
Finds the optimal spend distribution to maximize total return.
- Parameters:
total_budget (float) – Total budget to allocate.
channel_bounds (dict, optional) – Dictionary of (min_spend, max_spend) bounds keyed by channel_name.
- Returns:
The optimal allocation, marginal ROAS, and expected return.
- Return type:
dict
- attach_experiments(experiments)[source]¶
Associates incrementality experiments in parallel across portfolio channels.
- Parameters:
experiments – Dict mapping {channel_name: [exps] | exp} or flat list of dicts with ‘channel’ key.
- get_calibration_summary()[source]¶
Returns a high-level summary of calibration alignment across all portfolio channels.
- validate_experiments(experiments=None, spend_is_raw=True, verbose=False)[source]¶
Validates all portfolio channels against associated or provided incrementality experiments in parallel.
- Parameters:
experiments – Optional dictionary or list of experiments. If None, uses experiments attached to channel curves.
spend_is_raw – If True, converts raw daily spend to effective adstock where theta > 0.
verbose – If True, prints a formatted validation report.
- Returns:
Multi-channel validation summary.
- Return type:
dict
Capacity Projection¶
- class dxpoint.capacity.CapacityMultipliers(m_beta, m_k, m_beta_rf=1.0, m_k_rf=1.0, m_beta_product=1.0, m_k_product=1.0, synergy_damping=0.85, rf_details=<factory>, product_details=<factory>)[source]¶
Bases:
objectContainer for distilled capacity and spend scaling multipliers.
- m_beta¶
Total combined capacity multiplier on beta (Beta_proj = m_beta * Beta_curr).
- m_k¶
Total combined spend dilation multiplier on K (K_proj = m_k * K_curr).
- m_beta_rf¶
Multiplier on beta derived from Reach & Frequency penetration.
- m_k_rf¶
Multiplier on K derived from Reach & Frequency penetration.
- m_beta_product¶
Multiplier on beta derived from Product/Funnel usage.
- m_k_product¶
Multiplier on K derived from Product/Funnel usage.
- synergy_damping¶
Damping factor rho applied when combining multiple drivers.
- rf_details¶
Dictionary containing granular R&F metrics and calculations.
- product_details¶
Dictionary containing granular product/funnel parameters.
- m_beta: float¶
- m_beta_product: float = 1.0¶
- m_beta_rf: float = 1.0¶
- m_k: float¶
- m_k_product: float = 1.0¶
- m_k_rf: float = 1.0¶
- product_details: Dict[str, Any]¶
- rf_details: Dict[str, Any]¶
- synergy_damping: float = 0.85¶
- class dxpoint.capacity.CapacityProjector(m_beta=None, m_k=None, tam_size=None, current_reach=None, target_reach=None, current_reach_penetration=None, target_reach_penetration=None, current_frequency=None, target_frequency=None, reach_elasticity=0.65, frequency_elasticity=0.5, spend_reach_elasticity=0.75, frequency_capacity_factor=0.15, m_beta_product=None, m_k_product=None, current_funnel=None, target_funnel=None, funnel_multipliers=None, vertical=None, vertical_multipliers=None, synergy_damping=0.85)[source]¶
Bases:
objectAuxiliary capacity prediction engine for MarketingReturnCurve models.
Calculates user-defined or analytically derived multipliers (M_beta, M_K) based on: 1. Reach & Frequency (R&F) penetration headroom and frequency normalization. 2. Product usage and funnel architecture transitions (e.g. lower-funnel only
vs full-funnel).
- Synthesizes multi-driver unlocks using a damped interaction formulation:
M = 1.0 + rho_synergy * ((M_rf - 1.0) + (M_prod - 1.0))
- compute_multipliers()[source]¶
Computes final combined multipliers using the user-requested damped formulation.
- Return type:
- class dxpoint.capacity.ProjectedReturnCurve(base_curve, multipliers, channel_name=None)[source]¶
Bases:
MarketingReturnCurveA MarketingReturnCurve augmented with capacity and spend expansion multipliers.
Maintains full functional compatibility with MarketingReturnCurve and PortfolioAllocator, while retaining references to the empirical base curve and providing strategic headroom analytics.
- evaluate_unlocked_headroom(target_mroas=1.0, current_spend=None, verbose=True)[source]¶
Evaluates the incremental spend capacity and return headroom unlocked by the projection.
- Parameters:
target_mroas (
float) – Hurdle rate for diminishing returns (stop scaling point).current_spend (
Optional[float]) – Optional current spend level to evaluate headroom against.verbose (
bool) – If True, prints a formatted executive summary.
- Return type:
Dict[str,Any]- Returns:
Dict with comparative metrics between the base curve and projected curve.
Validation & Calibration¶
- dxpoint.validation.format_multichannel_validation_report(report)[source]¶
Formats a multi-channel validation dictionary into a clean text summary.
- dxpoint.validation.format_validation_report(report)[source]¶
Formats a validation dictionary into a clean text summary.
- dxpoint.validation.normalize_experiments_list(experiments, default_channel='Generic')[source]¶
Normalizes various single-channel experiment input formats into a list of dicts.
- dxpoint.validation.normalize_multichannel_experiments(multichannel_model, experiments=None)[source]¶
Normalizes multi-channel experiments into a structured dict of {channel_name: list[exp]}.
- dxpoint.validation.validate_curve_experiments(model, experiments=None, spend_is_raw=True, verbose=False)[source]¶
Evaluates a fitted MarketingReturnCurve against one or more incrementality experiments.
- Parameters:
model – An instance of MarketingReturnCurve.
experiments –
A dictionary or list of dictionaries containing experimental results. If None, uses experiments attached to the model (model.calibration_experiments). Supported keys per experiment:
’spend’ (or ‘raw_spend’, ‘adstocked_spend’): Media spend level tested.
’lift’ (or ‘incremental_return’, ‘conversions’): Incremental response measured.
’se’ (or ‘std_error’): Standard error of the measured lift (optional).
’ci’ (or ‘confidence_interval’): (lower, upper) 95% confidence interval (optional).
’name’ (or ‘channel’, ‘test_name’): Descriptive label for the test (optional).
spend_is_raw – If True and the curve has theta > 0, converts raw daily test spend to steady-state effective adstocked spend (S_eff = S_raw / (1 - theta)).
verbose – If True, prints a formatted validation report to stdout.
- Returns:
- Detailed evaluation metrics including per-experiment errors, Z-scores,
confidence interval coverage, and aggregate goodness-of-fit statistics.
- Return type:
dict
- dxpoint.validation.validate_multichannel_experiments(multichannel_model, experiments=None, spend_is_raw=True, verbose=False)[source]¶
Evaluates a multi-channel model across experiments across different channels in parallel.
- Parameters:
multichannel_model – MultiChannelModel instance or PortfolioAllocator instance.
experiments – List of experiment dictionaries or dict keyed by channel name. If None, evaluates experiments attached across channels.
spend_is_raw – Whether spends are raw daily spend.
verbose – If True, prints a summary report.
- Returns:
Multi-channel validation summary with per-channel breakdown and global metrics.
- Return type:
dict
Evaluation & Diagnostics¶
- dxpoint.evaluation.evaluate_curve_fit(model, spend_array, return_array, verbose=False)[source]¶
Evaluates statistical goodness-of-fit metrics for a fitted MarketingReturnCurve.
Calculates R-squared, Adjusted R-squared, RMSE, MAE, MAPE, AIC, and BIC.
- Parameters:
model – Fitted MarketingReturnCurve instance.
spend_array – Array of spend observations.
return_array – Array of observed return / response values.
verbose – If True, prints a formatted table of metrics.
- Returns:
Statistical fit metrics.
- Return type:
dict
Fitting Engines¶
- dxpoint.fitting.gradient.fit_mle_gradient(spend_array, return_array, epochs=5000, lr=0.05, adstock_type='none', adstock_bounds=None, adstock_fixed_days=None, fit_baseline=False)[source]¶
Fits a Hill Curve to historical data using MLE (Adam optimizer), with optional adstock and baseline.
- dxpoint.fitting.gradient.tinygrad_geometric_adstock(spend, theta)[source]¶
Applies geometric adstock decay in Tinygrad (vectorized Toeplitz weights).
- dxpoint.fitting.bayesian.fit_bayesian_mcmc(spend_array, return_array, channel_name='Generic', priors=None, n_samples=2000, chains=4, burn_in=1000, adstock_type='none', adstock_bounds=None, adstock_fixed_days=None, calibration_experiments=None, fit_baseline=False)[source]¶
Fits a Hill Curve using Bayesian MCMC (Metropolis-Hastings in transformed space) with optional adstock, baseline, and experimental calibration.
Mathematical Core¶
- dxpoint.math.days_to_theta(days)[source]¶
Converts half-life in days/periods to geometric decay rate theta.
Formula: theta = 0.5 ** (1 / days)
- dxpoint.math.geometric_adstock(spend, theta)[source]¶
Applies geometric adstock decay to a spend array using a vectorized recursive filter.
Formula: S_t_adstocked = S_t + theta * S_{t-1_adstocked}
- dxpoint.math.get_inflection_point(alpha, K)[source]¶
Calculates the inflection point where marginal return peaks (f’’(x) = 0).
- dxpoint.math.hill_first_derivative(spend, beta, alpha, K)[source]¶
Calculates the first derivative of the Hill Function (Marginal ROAS).
- dxpoint.math.hill_function(spend, beta, alpha, K)[source]¶
Calculates the Hill Function value: f(x) = (beta * (x/K)^alpha) / (1 + (x/K)^alpha).
- dxpoint.math.weibull_adstock(spend, shape, scale, adstock_type='pdf', max_lag=None)[source]¶
Applies Weibull adstock transformation (PDF or CDF decay).
- Parameters:
spend (array-like) – 1D array of media spend over time.
shape (float) – Weibull shape parameter (k > 0). If k > 1, peak effect is delayed.
scale (float) – Weibull scale parameter (lambda > 0), controls decay duration.
adstock_type (str) – ‘pdf’ (peaked/delayed decay) or ‘cdf’ (cumulative retention).
max_lag (int, optional) – Maximum lag window. Defaults to full length of spend.
- Returns:
Adstocked effective spend array.
- Return type:
np.ndarray