import numpy as np
from scipy.stats import chi2

def independence_test(violations):
    """
    Réalise le test d'indépendance de Christoffersen pour le backtesting de la VaR.
    """
    violations = np.array(violations)
    n00, n01, n10, n11 = 0, 0, 0, 0

    for t in range(1, len(violations)):
        if violations[t-1] == 0 and violations[t] == 0: n00 += 1
        elif violations[t-1] == 0 and violations[t] == 1: n01 += 1
        elif violations[t-1] == 1 and violations[t] == 0: n10 += 1
        elif violations[t-1] == 1 and violations[t] == 1: n11 += 1

    # Probabilités conditionnelles
    pi0 = n01 / (n00 + n01) if (n00 + n01) > 0 else 0
    pi1 = n11 / (n10 + n11) if (n10 + n11) > 0 else 0
    pi = (n01 + n11) / (n00 + n01 + n10 + n11) if (n00 + n01 + n10 + n11) > 0 else 0

    # Log-likelihood Ratio (LR ind)
    term_null = (1 - pi)**(n00 + n10) * pi**(n01 + n11)
    term_alt = (1 - pi0)**n00 * pi0**n01 * (1 - pi1)**n10 * pi1**n11
    
    lr_ind = -2 * np.log(term_null / term_alt) if term_alt > 0 else 0
    p_value = 1 - chi2.cdf(lr_ind, df=1)

    return lr_ind, p_value