Advanced Email Marketing Analytics: Python Implementation Guide

This appendix provides Python code examples for implementing some of the advanced concepts discussed in the article. These examples are intended for readers with programming experience and access to relevant data.

1. Calculating Engagement Time Velocity (ETV)

import pandas as pd

def calculate_etv(df):
    """
    Calculate Engagement Time Velocity from a DataFrame

    :param df: DataFrame with 'date' and 'engagement_time' columns
    :return: DataFrame with 'date' and 'etv' columns
    """
    df = df.sort_values('date')
    df['previous_engagement_time'] = df['engagement_time'].shift(1)
    df['etv'] = (df['engagement_time'] - df['previous_engagement_time']) / df['previous_engagement_time']
    return df[['date', 'etv']].dropna()

# Example usage
data = pd.DataFrame({
    'date': pd.date_range(start='2024-01-01', periods=10),
    'engagement_time': [10, 12, 15, 14, 18, 20, 22, 25, 28, 30]
})

etv_results = calculate_etv(data)
print(etv_results)

2. Predictive Churn Modeling

from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report

def train_churn_model(X, y):
    """
    Train a Random Forest model for churn prediction

    :param X: Feature matrix
    :param y: Target vector (churn labels)
    :return: Trained model and accuracy score
    """
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

    model = RandomForestClassifier(n_estimators=100, random_state=42)
    model.fit(X_train, y_train)

    y_pred = model.predict(X_test)
    accuracy = accuracy_score(y_test, y_pred)

    print("Model Accuracy:", accuracy)
    print("\nClassification Report:")
    print(classification_report(y_test, y_pred))

    return model, accuracy

# Example usage (assuming you have a DataFrame 'df' with features and a 'churn' column)
# X = df[['engagement_rate', 'avg_order_value', 'days_since_last_purchase']]
# y = df['churn']
# model, accuracy = train_churn_model(X, y)

3. Dynamic KPI Weighting

import numpy as np

def calculate_weighted_performance(kpi_values, weights):
    """
    Calculate weighted performance score

    :param kpi_values: List of KPI values
    :param weights: List of corresponding weights
    :return: Weighted performance score
    """
    return np.dot(kpi_values, weights)

def update_weights(current_weights, performance_scores, target_scores, learning_rate=0.01):
    """
    Update weights based on performance

    :param current_weights: Current weight values
    :param performance_scores: Actual performance scores
    :param target_scores: Target performance scores
    :param learning_rate: Rate of weight adjustment
    :return: Updated weights
    """
    error = np.array(target_scores) - np.array(performance_scores)
    weight_adjustments = learning_rate * error
    new_weights = current_weights + weight_adjustments
    return new_weights / np.sum(new_weights)  # Normalize to ensure weights sum to 1

# Example usage
kpi_values = [0.8, 0.6, 0.9, 0.7]  # Example KPI values
initial_weights = [0.25, 0.25, 0.25, 0.25]  # Equal initial weights
target_scores = [0.85, 0.7, 0.95, 0.8]  # Target scores for each KPI

current_performance = calculate_weighted_performance(kpi_values, initial_weights)
print("Initial Weighted Performance:", current_performance)

updated_weights = update_weights(initial_weights, kpi_values, target_scores)
print("Updated Weights:", updated_weights)

new_performance = calculate_weighted_performance(kpi_values, updated_weights)
print("New Weighted Performance:", new_performance)

4. AI-Driven Anomaly Detection

from sklearn.ensemble import IsolationForest
import numpy as np

def detect_anomalies(data, contamination=0.1):
    """
    Detect anomalies in KPI data using Isolation Forest

    :param data: 2D array-like, shape (n_samples, n_features)
    :param contamination: The proportion of outliers in the data set
    :return: Boolean array where True indicates an anomaly
    """
    clf = IsolationForest(contamination=contamination, random_state=42)
    anomalies = clf.fit_predict(data)
    return anomalies == -1  # -1 indicates an anomaly

# Example usage
np.random.seed(42)
normal_data = np.random.normal(size=(1000, 4))  # 4 KPIs
anomalies = np.random.uniform(low=-4, high=4, size=(50, 4))  # Anomalous data
all_data = np.vstack((normal_data, anomalies))

is_anomaly = detect_anomalies(all_data)
print("Number of detected anomalies:", sum(is_anomaly))
print("Anomaly indices:", np.where(is_anomaly)[0])

Organizations relying solely on basic email metrics often miss critical optimization opportunities in both campaign performance and audience engagement.

For comprehensive measurement frameworks, explore our guide to Essential KPIs for Email Marketing Dashboards, or dive into advanced optimization strategies in Email Marketing Expert KPIs: Dashboard Optimization.

Go up