# =============================================================================
# 01_quickstart.R — Minimal self-contained example for kronxNBC
#
# Demonstrates: fitting, predicting, extracting parameters, and plotting
# using synthetic three-regime financial data.
# =============================================================================

library(kronxNBC)

# ---- 1. Generate synthetic data ----------------------------------------------

set.seed(42L)
n  <- 300L
mk <- n / 3L

X <- rbind(
  # Calm: low volatility, near-Gaussian returns
  cbind(
    log_return         = rnorm(mk, 0.0002, 0.003),
    rolling_volatility = abs(rnorm(mk, 0.004,  0.001)),
    drawdown           = rnorm(mk, -0.002, 0.002),
    ruin_proxy         = rbeta(mk, 1, 20)
  ),
  # Steady: moderate drift and drawdowns
  cbind(
    log_return         = rnorm(mk, 0.0005, 0.005),
    rolling_volatility = abs(rnorm(mk, 0.008,  0.002)),
    drawdown           = rnorm(mk, -0.008, 0.004),
    ruin_proxy         = rbeta(mk, 2, 10)
  ),
  # Stress: fat-tailed returns (t_3), high volatility, deep drawdowns
  cbind(
    log_return         = rt(mk, df = 3L) * 0.012,
    rolling_volatility = abs(rnorm(mk, 0.022,  0.005)),
    drawdown           = rnorm(mk, -0.030, 0.010),
    ruin_proxy         = rbeta(mk, 5, 3)
  )
)

y <- factor(
  rep(c("Calm", "Steady", "Stress"), each = mk),
  levels = c("Calm", "Steady", "Stress")
)

# 80 / 20 random split
set.seed(7L)
tr_idx  <- sample(n, size = floor(0.8 * n))
x_train <- X[ tr_idx, ]
y_train <- y[ tr_idx ]
x_test  <- X[-tr_idx, ]
y_test  <- y[-tr_idx ]

# ---- 2. Fit the model --------------------------------------------------------

model <- student_t_naive_bayes(x_train, y_train)

# High-level overview
summary(model)

# Detailed parameter tables (mu, sd, nu for each feature x class)
print(model)

# ---- 3. Extract fitted parameters -------------------------------------------

# nu matrix (K x p): core theoretical output
cat("\nDegrees-of-freedom matrix (nu):\n")
print(model$params$nu)

# Full coefficient data frame
cat("\nCoefficient data frame:\n")
print(coef(model))

# Tables for a single feature
cat("\nParameter table for log_return:\n")
print(tables(model, which = "log_return"))

# ---- 4. Visualise class-conditional densities --------------------------------

# Conditional densities for all four features
plot(model,
     prob    = "conditional",
     arg.num = list(col = c("steelblue", "forestgreen", "firebrick"),
                    lty = c(1L, 2L, 4L)),
     lwd     = 2)

# ---- 5. Predict on held-out data --------------------------------------------

pred_class <- predict(model, newdata = x_test, type = "class")
pred_prob  <- predict(model, newdata = x_test, type = "prob")

cat(sprintf("\nOut-of-sample accuracy: %.1f%%\n",
            100 * mean(pred_class == y_test)))

cat("\nConfusion matrix:\n")
print(table(Actual = y_test, Predicted = pred_class))

cat("\nFirst 6 posterior probability vectors:\n")
print(round(head(pred_prob), 4))

# ---- 6. COR Stress Alert -----------------------------------------------------

stress_prob <- pred_prob[, "Stress"]
alert_flag  <- ifelse(stress_prob > 0.60, "Stress Alert", "No Alert")

cat("\nStress Alert summary (test period):\n")
print(table(alert_flag))
