%\VignetteIndexEntry{KRONX: Clock of Regimes in R}
%\VignetteEngine{utils::Sweave}
%\VignetteEncoding{UTF-8}

\documentclass[11pt]{article}

\usepackage[margin=1in]{geometry}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage{amsmath,amssymb,booktabs,longtable,array,float}
\usepackage{hyperref}

\title{KRONX: Clock of Regimes in R}
\author{Oscar Linares}
\date{\today}

\begin{document}
\maketitle

\begin{abstract}
This vignette introduces the \texttt{KRONX} package for regime-switching
fragility analysis. The package extends a standard Hidden Markov Model workflow
by constructing an open operator chain
\[
A \to Q \to K \to N,
\]
where \(Q\) is a hazard-adjusted transition operator, \(K = Q - I\) is a
sub-generator, and \(N = -K^{-1}\) is the fundamental matrix of cumulative
expected residence times. The package provides a compact workflow for fitting
Gaussian and Student-\(t\) hidden Markov models, constructing the KRONX
operators, and computing a finite-horizon ruin bound.
\end{abstract}

\tableofcontents

<<setup, echo=FALSE, results=hide>>=
options(width = 80)
@

\section{Introduction}

The \texttt{KRONX} package implements the Clock of Regimes framework as an
open-system extension of a Hidden Markov Model. In a standard HMM, persistence
is encoded through one-step transition probabilities \(a_{ii}\). In KRONX, the
estimated transition structure is converted into a survival-style operator
system:
\[
A \to Q \to K \to N.
\]

Starting from a fitted transition matrix \(A\), the package assigns
state-specific hazards \(\epsilon_i\), constructs
\[
Q = \operatorname{diag}(1-\epsilon_i)A,
\]
then defines
\[
K = Q - I,
\qquad
N = -K^{-1}.
\]

The matrix \(N\) summarizes cumulative expected sojourn times before absorption
and provides the residence-time geometry underlying the KRONX interpretation.

\section{Package overview}

The package supports the following workflow:

\begin{enumerate}
\item read a price series or accept a numeric return vector,
\item fit Gaussian and Student-\(t\) HMMs,
\item reorder states by scale,
\item decode the latent state path,
\item construct \(Q\), \(K\), and \(N\),
\item compute quasi-stationary and residence weights,
\item compute a finite-horizon ruin bound.
\end{enumerate}

\subsection{Dependencies}

\begin{itemize}
\item Requires: R \(\ge 4.0.0\)
\item Imports: \texttt{stats}, \texttt{utils}
\item Suggests: \texttt{testthat} \(\ge 3.0.0\)
\item No compiled code
\end{itemize}

\subsection{Core operator chain}

\begin{table}[H]
\centering
\begin{tabular}{lll}
\toprule
\textbf{Symbol} & \textbf{Definition} & \textbf{Interpretation} \\
\midrule
\(Q\) & \(\operatorname{diag}(1-\varepsilon)A\) & Leaky transition operator \\
\(K\) & \(Q - I\) & Sub-generator \\
\(N\) & \(-K^{-1}\) & Fundamental matrix of cumulative sojourn times \\
\bottomrule
\end{tabular}
\caption{KRONX operator chain.}
\label{tab:operator_chain}
\end{table}

\section{Quick start}

For package documentation, the safest approach is a small self-contained
example.

<<quick-start, eval=TRUE>>=
set.seed(123)
x <- rnorm(120, mean = 0, sd = 0.01)

res <- KRONX::run_kronx(
  x = x,
  K = 2L,
  n_starts = 1L,
  max_iter = 10L,
  tol = 1e-4,
  tail_alpha = 0.05,
  ruin_horizon = 25L,
  verbose = FALSE,
  output_dir = NULL
)

res$ruin_bound
dim(res$A_t)
@

The object returned by \texttt{run\_kronx()} contains the fitted HMMs, the KRONX
operator chain, and summary risk quantities.

\section{Main functions}

The package exports:

<<exports, eval=FALSE>>=
getNamespaceExports("KRONX")
@

\subsection{\texttt{run\_kronx()}}

\texttt{run\_kronx()} is the main entry point. It accepts either a file path or
a numeric return vector.

<<run-kronx-signature, eval=FALSE>>=
KRONX::run_kronx(
  file = NULL,
  x = NULL,
  close_col = "close",
  K = 3L,
  n_starts = 5L,
  max_iter = 200L,
  tol = 1e-6,
  seed = 123L,
  epsilon_min = 0.01,
  c_hazard = 0.05,
  tail_alpha = 0.01,
  ruin_horizon = 250L,
  nu_grid = c(3:30, 40, 60, 100),
  verbose = TRUE,
  output_dir = "kronx_output"
)
@

Its workflow is:

\begin{enumerate}
\item ingest data or accept a supplied return vector,
\item fit Gaussian and Student-\(t\) HMMs,
\item decode the Student-\(t\) state path,
\item build \(\epsilon\), \(Q\), \(K\), and \(N\),
\item compute quasi-stationary weights, residence weights, and the ruin bound,
\item optionally write output files.
\end{enumerate}

\subsection{\texttt{fit\_hmm\_em()}}

\texttt{fit\_hmm\_em()} fits either a Gaussian or Student-\(t\) HMM by EM.

<<fit-hmm, eval=TRUE>>=
set.seed(123)
x <- rnorm(100, 0, 0.01)

fit <- KRONX::fit_hmm_em(
  x = x,
  K = 2L,
  model = "gaussian",
  n_starts = 1L,
  max_iter = 8L,
  tol = 1e-4,
  verbose = FALSE
)

fit$logLik
@

\subsection{\texttt{viterbi\_decode()}}

<<viterbi, eval=TRUE>>=
states <- KRONX::viterbi_decode(x, fit)
table(states)
@

\subsection{\texttt{read\_close\_series()} and \texttt{compute\_log\_returns()}}

These functions support data ingestion and return construction.

<<data-io, eval=FALSE>>=
px <- KRONX::read_close_series("my_prices.csv", close_col = "close")
ret <- KRONX::compute_log_returns(px)
summary(ret)
@

\section{Worked example}

\subsection{Constructing the operator chain}

<<operator-chain, eval=TRUE>>=
set.seed(123)
x <- rnorm(120, 0, 0.01)

t_fit <- KRONX::fit_hmm_em(
  x = x,
  K = 2L,
  model = "student",
  n_starts = 1L,
  max_iter = 8L,
  tol = 1e-4,
  nu_grid = c(3, 5, 10),
  verbose = FALSE
)

epsilon <- KRONX:::hazard_from_nu(
  nu = t_fit$params$nu,
  epsilon_min = 0.01,
  c_hazard = 0.05
)

Q <- KRONX:::build_Q(t_fit$A, epsilon)
K_mat <- KRONX:::build_K(Q)
N_mat <- KRONX:::fundamental_matrix(K_mat)

epsilon
Q
@

\subsection{Risk-bound components}

<<ruin-components, eval=TRUE>>=
loss_threshold <- stats::quantile(x, probs = 0.05)
q_state <- KRONX:::left_tail_state_probs(t_fit, loss_threshold)

pi_qs <- KRONX:::quasi_stationary_distribution(Q)
pi_res <- KRONX:::residence_weight_vector(N_mat, init = pi_qs)

bar_q <- sum(pi_res * q_state)
bar_lambda <- sum(pi_res * epsilon)
ruin_bound <- 1 - exp(-bar_lambda * bar_q * 25)

c(bar_q = bar_q, bar_lambda = bar_lambda, ruin_bound = ruin_bound)
@

\subsection{Optional file-based workflow}

For larger real-data workflows, use a CSV file with a close-price column.

<<file-workflow, eval=FALSE>>=
res_file <- KRONX::run_kronx(
  file = "IBKR_ES_2Y1h.csv",
  close_col = "close",
  verbose = FALSE,
  output_dir = NULL
)

res_file$ruin_bound
@

\section{Testing}

The package includes \texttt{testthat} tests covering:

\begin{itemize}
\item end-to-end workflow on toy data,
\item file-based ingestion checks,
\item input validation,
\item HMM fitting interface validation,
\item operator-chain structural properties.
\end{itemize}

Tests can be run with:

<<tests, eval=FALSE>>=
devtools::test()
testthat::test_package("KRONX")
@

\section{Conclusion}

The \texttt{KRONX} package provides a complete regime-switching fragility
workflow in pure R. It combines HMM estimation with an open operator framework
based on \(Q\), \(K\), and \(N\). For package purposes, this vignette focuses on
the computational workflow and a small reproducible example. Longer theoretical
and journal-style exposition is better maintained as a separate paper or
preprint.

\end{document}