InflationEvalTools

Types, functions, and simulation utilities for the evaluation of inflation measures.

Defaults

InflationEvalTools.LOCAL_RNGConstant
const LOCAL_RNG = StableRNG(0)

This constant is used to set the random number generator in each local process, using the StableRNG generator with initial seed zero. The seed will be altered in each iteration of the simulation process. This guarantees the reproducibility of the results per resampling realization by choosing the constant DEFAULT_SEED.

source

Resampling Methods

Resampling functions for CPI bases and related utilities.

InflationEvalTools.ResampleFunctionType
abstract type ResampleFunction <: Function end

Abstract type for resampling functions. Each function must at least extend the method

  • resamplefn(vmat::AbstractMatrix, rng)::Matrix

to resample a CountryStructure with the functions defined above.

Optionally, if you want to modify the specific behavior of each resampling function, you must extend the following methods:

  • function (resamplefn::ResampleFunction)(cs::CountryStructure, rng = Random.GLOBAL_RNG)
  • function (resamplefn::ResampleFunction)(base::VarCPIBase, rng = Random.GLOBAL_RNG)
source
InflationEvalTools.ResampleScrambleVarMonthsType
ResampleScrambleVarMonths <: ResampleFunction

Defines a resampling function to resample the time series by the same months of occurrence. The sampling is performed independently for each time series in the columns of a matrix.

source
InflationEvalTools.ResampleScrambleTrendedType
ResampleScrambleTrended <: ResampleFunction

Resampling function that uses IID bootstrap weighted by months of occurrence to recreate the trend of the data.

Fields

  • p::Float64: Probability parameter controlling the trend weighting in the resampling process.
source
InflationEvalTools.ResampleTrendedType
ResampleTrended{T<:AbstractFloat} <: ResampleFunction

Resampling function that uses IID bootstrap weighted by months of occurrence with individual parameters for each CPI base, to recreate the trend of the data.

Fields

  • p::Vector{T}: Individual probability parameters for each CPI base, controlling the trend weighting in the resampling process.
source
InflationEvalTools.ResampleExtendedSVMType
ResampleExtendedSVM <: ResampleFunction

Define a resampling function to resample the time series for the same months of occurrence. Sampling is performed independently for each time series in the columns of the matrix of monthly price changes.

Example

In this example, GTDATA23 is a CountryStructure and contains three VarCPIBase objects. For each CPI dataset, the resampling is performed with the same length as the vector used as a parameter in ResampleExtendedSVM().

resamplefn = ResampleExtendedSVM([150, 180, 50])
resamplefn(GTDATA23)
source
InflationEvalTools.ResampleIdentityType
ResampleIdentity()

An identity resampling function type. Calling an instance of ResampleIdentity on a VarCPIBase or CountryStructure returns the exact same object (no resampling performed). Use this when you want to disable resampling and work with the original observed datasets.

source
InflationEvalTools.get_param_functionFunction
get_param_function(::ResampleFunction)

Each resampling function must implement a function to obtain a CountryStructure with VarCPIBase objects that contain the average (or parametric) month-to-month variations that allow constructing the parametric inflation trajectory according to the resampling method given in ResampleFunction.

This function returns the function to obtain parametric data.

Example

# Obtain the resampling function
resamplefn = ResampleSBB(36)
...

# Obtain its function to get the parametric data
paramdatafn = get_param_function(resamplefn)
# Obtain CountryStructure of parametric data
paramdata = paramdatafn(gtdata)
source
get_param_function(resamplefn::ResampleIdentity)

Return a function that, when called with a VarCPIBase, returns the same VarCPIBase object (the actual data). This matches the get_param_function contract used by other resamplers, with the exception of returning actual data.

source
get_param_function(resamplefn::ResampleMixture)

Return a function that, when called with a CountryStructure, applies each resampling function's parameter function to its corresponding base. The returned function creates a new CountryStructure with the parameter data from each base.

source
InflationEvalTools.method_nameFunction
method_name(resamplefn::ResampleFunction)

Function to obtain the name of the resampling method.

source
method_name(resamplefn::TrendFunction)

Function to obtain the name of the trend function.

source
InflationEvalTools.method_tagFunction
method_tag(resamplefn::ResampleFunction)

Function to obtain a tag for the resampling method.

source
method_tag(trendfn::TrendFunction)

Function to obtain a tag for the trend function.

source

B-TIMA Extension

The B-TIMA extension procedure uses the following functions:

InflationEvalTools.CPIVarietyMatchDistributionType
CPIVarietyMatchDistribution(
    prior_dist, 
    actual_dist, 
    month; 
    weighing_function_type=:synthetic, 
    prior_variety_id=nothing, 
    prior_variety_name=nothing, 
    actual_variety_id=nothing, 
    actual_variety_name=nothing
)

Create a synthetic empirical distribution that matches an item (variety) between two adjacent CPI bases. The object stores the concatenated distribution of monthly price changes, sampling weights (according to the selected reweighing strategy), and metadata such as the month and optional ids/names.

Arguments

  • prior_dist, actual_dist: vectors of monthly price changes for the prior and actual variety samples.
  • month: integer month (1..12) the observations correspond to.

Keyword arguments

  • weighing_function_type: :synthetic (default), :prior, :actual, or a custom function accepting (prior_dist, actual_dist) and returning a scalar weighting function w(x) used to construct sampling weights.
  • optional prior_variety_id, prior_variety_name, actual_variety_id, actual_variety_name to store identifying metadata.

Example

# Suppose v_10 and v_23 are two vectors of monthly changes for the same item
# observed in two CPI bases and m is the month (1..12).
var = CPIVarietyMatchDistribution(v_10, v_23, m)
println(var)                     # short display
mean(var)                        # returns the computed expected value
std(var)                         # returns the weighted std dev
StatsBase.sample(var)            # draw one sample (uses stored weights)
StatsBase.sample(var, 10)        # draw 10 samples

# You can explicitly request prior-only or actual-only sampling:
var_prior = CPIVarietyMatchDistribution(v_10, v_23, m, :prior)
var_actual = CPIVarietyMatchDistribution(v_10, v_23, m, :actual)

See also: synthetic_reweighing, prior_reweighing, actual_reweighing.

source
InflationEvalTools.ResampleSyntheticType
ResampleSynthetic(
    base::VarCPIBase, 
    matching_structure::Matrix{CPIVarietyMatchDistribution}, 
    numperiods = periods(base)
)

Create a resampling function that implements the B-TIMA Extension Methodology for generating synthetic samples from matched CPI items between two adjacent CPI bases. Importantly, ResampleSynthetic is to be used only for VarCPIBase objects because the required matching structure is specific to the VarCPIBase.

Arguments

  • base: A VarCPIBase object that provides reference dimensions and dates
  • matching_structure: A 2D array of CPIVarietyMatchDistribution objects with shape (periods, items) containing the matching distributions for each item and month
  • numperiods: Optional number of periods to generate in the resampled series (defaults to the number of periods in base)

Example

# Create matching distributions for each item and month
matching_array = Array{CPIVarietyMatchDistribution}(undef, 12, nitems)
for j in 1:nitems, m in 1:12
    v_prior, v_actual = get_obs_month(prior_codes[j], actual_codes[j], m)
    # Use synthetic reweighing for items 1-99
    # prior-only for items 100-349
    # actual-only for remaining items
    weighing = j < 100 ? :synthetic : (j < 350 ? :prior : :actual)
    matching_array[m,j] = CPIVarietyMatchDistribution(v_prior, v_actual, m, weighing)
end

# Create resampler with 5 years of data
synth_resampler = ResampleSynthetic(base, matching_array, 12*5)

# Generate a synthetic sample
varbase_sample = synth_resampler(base)

# Get the population mean parameters
population_fn = get_param_function(synth_resampler)
population_base = population_fn(base)

See also: CPIVarietyMatchDistribution, synthetic_reweighing, prior_reweighing, actual_reweighing

source
InflationEvalTools.synthetic_reweighingFunction
synthetic_reweighing(prior_dist, actual_dist; a = 0.35, eps = 0.0001)

Create a reweighing function that assigns weights based on how close each value is to the mean of the actual distribution, using a normal density function. This is the default reweighing strategy used in CPIVarietyMatchDistribution.

Arguments

  • prior_dist: Vector of monthly price changes from the prior CPI base
  • actual_dist: Vector of monthly price changes from the actual CPI base
  • a: Scaling factor for the standard deviation (default: 0.35)
  • eps: Small value added to avoid zero variance (default: 0.0001)

Returns a function w(x) that computes weights proportional to the normal density of the absolute difference between x and the actual mean.

source
InflationEvalTools.prior_reweighingFunction
prior_reweighing(prior_dist, actual_dist)

Create a reweighing function that only samples from the prior distribution, assigning unit weights to values from the prior distribution and zero weights to values from the actual distribution.

Arguments

  • prior_dist: Vector of monthly price changes from the prior CPI base
  • actual_dist: Vector of monthly price changes from the actual CPI base (unused)

Returns a function w(x) that assigns 1 if x is in the prior distribution and 0 otherwise. Used when :prior is specified as the weighingfunctiontype in CPIVarietyMatchDistribution.

source
InflationEvalTools.actual_reweighingFunction
actual_reweighing(prior_dist, actual_dist)

Create a reweighing function that only samples from the actual distribution, assigning unit weights to values from the actual distribution and zero weights to values from the prior distribution.

Arguments

  • prior_dist: Vector of monthly price changes from the prior CPI base (unused)
  • actual_dist: Vector of monthly price changes from the actual CPI base

Returns a function w(x) that assigns 1 if x is in the actual distribution and 0 otherwise. Used when :actual is specified as the weighingfunctiontype in CPIVarietyMatchDistribution.

source
InflationEvalTools.ResampleMixtureType
ResampleMixture(resampling_functions::Vector{<:ResampleFunction})

Creates a resampling function that applies different resampling methods to each VarCPIBase object in a CountryStructure. The number of resampling functions provided must match the number of VarCPIBase objects in the CountryStructure.

Arguments

  • resampling_functions: A vector of ResampleFunction objects, where each element corresponds to the resampling function to be applied to the VarCPIBase object at the same index in a CountryStructure.

Example

# Create different resampling functions for each base
resample_identity = ResampleIdentity()
resample_synthetic = ResampleSynthetic(base, matching_array)

# Create a mixed resampler that applies each function to its corresponding base
mixed_resampler = ResampleMixture([resample_identity, resample_synthetic])

# Apply the mixed resampling to a CountryStructure with two bases
resampled_cs = mixed_resampler(cs)

# Get the population parameters using each sampler's param function
population_fn = get_param_function(mixed_resampler)
population_cs = population_fn(cs)
source

Trend Functions

Functions for trend application and modeling.

InflationEvalTools.TrendFunctionType
abstract type TrendFunction <: Function end

Abstract type to handle trend functions.

Usage

function (trendfn::TrendFunction)(cs::CountryStructure)

Applies the trend function to a CountryStructure and returns a new CountryStructure.

source
InflationEvalTools.ArrayTrendFunctionType
abstract type ArrayTrendFunction <: TrendFunction end

Type for trend function that stores the vector of values to apply to the month-to-month variations.

Usage

function (trendfn::ArrayTrendFunction)(base::VarCPIBase{T}, range::UnitRange) where T

Specifies how to apply the trend function to a VarCPIBase with the index range range.

source
InflationEvalTools.TrendRandomWalkType
TrendRandomWalk{T} <: ArrayTrendFunction

Type to represent a random walk trend function. Uses the precalibrated random walk vector in RWTREND.

Example:

# Create the random walk trend function
trendfn = TrendRandomWalk()
source
InflationEvalTools.TrendAnalyticalType
TrendAnalytical{T} <: ArrayTrendFunction

Type to represent a trend function defined by an anonymous function. Receives the data from a CountryStructure or a range of indices to precompute the trend vector using an anonymous function.

Examples:

To create a trend function from an anonymous function:

trendfn = TrendAnalytical(param_data, t -> 1 + sin(2π*t/12), "Sinusoidal trend")

or:

trendfn = TrendAnalytical(1:periods(param_data), t -> 1 + sin(2π*t/12), "Sinusoidal trend")
source
InflationEvalTools.TrendExponentialType
TrendExponential{T} <: ArrayTrendFunction

Concrete type to represent an exponential growth trend function.

Constructors

function TrendExponential(cs::CountryStructure, rate::Real = 0.02f0)
function TrendExponential(range::UnitRange, rate::Real = 0.02f0)

Examples:

# Create a trend function with 2% annual exponential growth
trendfn = TrendExponential(gtdata, 0.02)

Usage

function (trendfn::TrendExponential)(cs::CountryStructure)

Application of TrendExponential trend to the VarCPIBase objects that make up the CountryStructure.

trendfn = TrendExponential(gtdata, 0.02) 
trended_cs = trendfn(gtdata) 
source
InflationEvalTools.TrendIdentityType
TrendIdentity <: TrendFunction

Concrete type to represent a neutral trend function. That is, this trend function leaves the data unchanged.

Examples:

# Create an identity trend function. 
trendfn = TrendIdentity()

Usage

function (trendfn::TrendIdentity)(cs::CountryStructure)

Application of TrendIdentity trend to VarCPIBase. This method is redefined to leave the VarCPIBase unchanged.

trendfn = TrendIdentity() 
trended_cs = trendfn(gtdata) 
source
InflationEvalTools.TrendDynamicRWType
TrendDynamicRW{T, F<:Function} <: ArrayTrendFunction

Type to represent a dynamic random walk (or AR(1)) trend function. Generates an AR(1) process that satisfies a validation function.

Fields

  • trend::Vector{T}: The generated trend vector.
  • L::Int: Length of the process.
  • phi::T: Autocorrelation parameter.
  • sigma::T: Standard deviation of shocks.
  • f::F: Validation function to select realizations of the process.

Constructor

TrendDynamicRW(L::Int, phi::Real, sigma::Real, f::Function; rng=Random.GLOBAL_RNG)

Creates a TrendDynamicRW object by generating an AR(1) process with parameters L, phi, and sigma until the validation function f returns true.

source
InflationEvalTools.zeromean_validationFunction
zeromean_validation(y; atol = 0.1)

Validation function that returns true if the mean of the vector y is approximately zero, within the absolute tolerance atol. Vector y is typically the generated AR(1) process before exponentiation.

source
InflationEvalTools.create_TrendDynamicRW_arrayFunction
create_TrendDynamicRW_array(L::Int = 360, phi::Real = 1.0f0, sigma::Real = 0.05f0, f::Function = zeromean_validation, nfolds::Int = 10; rng = Random.GLOBAL_RNG)

Create a vector of TrendDynamicRW objects with the specified parameters.

Arguments

  • L::Int: Length of the trend process (default 360).
  • phi::Real: Autoregressive coefficient (default 1.0).
  • sigma::Real: Standard deviation of the shocks (default 0.05).
  • f::Function: Validation function (default zeromean_validation).
  • nfolds::Int: Number of trend functions to generate (default 10).
  • rng: Random number generator (default Random.GLOBAL_RNG).

Returns a Vector{TrendDynamicRW}.

source

Parametric Base Methods

Methods to obtain bases of population monthly price changes.

InflationEvalTools.param_scramblevar_fnFunction
param_scramblevar_fn(base::VarCPIBase)

Obtains the matrix of population monthly price changes for the B-TIMA bootstrap resampling methodology by the same calendar months. Returns a VarCPIBase type base with the average month-to-month variations of the same months of occurrence (also called population monthly price changes).

source
InflationEvalTools.ParamTotalCPIRebaseFunction
ParamTotalCPIRebase()

Helper function to obtain the configuration of the inflation parameter given by the synthetic base change CPI inflation function, and the default resampling method and trend function.

source
InflationEvalTools.ParamTotalCPIFunction
ParamTotalCPI()

Helper function to obtain the configuration of the inflation parameter given by the CPI inflation function, and the default resampling method and trend function.

source
InflationEvalTools.ParamWeightedMeanFunction
ParamWeightedMean()

Helper function to obtain the configuration of the inflation parameter given by the interannual weighted mean and the default resampling method.

source
InflationEvalTools.ParamTotalCPILegacyRebaseFunction
ParamTotalCPILegacyRebase()

Helper function to obtain the configuration of the inflation parameter given by the synthetic base change CPI inflation function, and the default resampling method and trend function.

source

Simulation Configuration

Types and utilities for simulation and evaluation period configuration.

InflationEvalTools.AbstractConfigType
abstract type AbstractConfig{F <: InflationFunction, R <:ResampleFunction, T <:TrendFunction} end

AbstractConfig is an abstract type to represent simulation variants that generally use an inflation function InflationFunction, a resampling function ResampleFunction, and a trend function TrendFunction. It contains the general scheme of the simulation.

source
InflationEvalTools.SimConfigType
SimConfig{F, R, T} <:AbstractConfig{F, R, T}

Concrete type that contains a base configuration to generate simulations using all data as the training set. Receives an inflation function InflationFunction, a resampling function ResampleFunction, a trend function TrendFunction, an evaluation inflation function [paramfn], and the desired number of simulations [nsim].

Example

Considering the following instances of inflation, resampling, trend, and evaluation inflation functions:

julia> percEq = InflationPercentileEq(80);

julia> resamplefn = ResampleSBB(36);

julia> trendfn = TrendRandomWalk();

julia> paramfn = InflationWeightedMean();

We generate a SimConfig configuration with 1000 simulations, with default evaluation periods:

  • CompletePeriod(),
  • GT_EVAL_B00,
  • GT_EVAL_T0010 and
  • GT_EVAL_B10
julia> config = SimConfig(percEq, resamplefn, trendfn, paramfn, 1000, Date(2019,12))
SimConfig{InflationPercentileEq, ResampleSBB, TrendRandomWalk{Float32}}
|─> Inflation function            : Percentil equiponderado 80.0
|─> Resampling function           : Block bootstrap estacionario con bloque esperado 36
|─> Trend function                : Tendencia de caminata aleatoria
|─> Parametric inflation method   : Media ponderada interanual
|─> Number of simulations         : 1000
|─> End of training set           : Dec-19
|─> Evaluation periods            : Complete period, gt_b00:Dec-01-Dec-10, gt_t0010:Jan-11-Nov-11 y gt_b10:Dec-11-Dec-20

To generate a configuration with specific periods, you can provide the collection of periods of interest:

julia> config2 = SimConfig(percEq, resamplefn, trendfn, paramfn, 1000, Date(2019,12),
       (CompletePeriod(), EvalPeriod(Date(2008,1), Date(2009,12), "fincrisis")))
SimConfig{InflationPercentileEq, ResampleSBB, TrendRandomWalk{Float32}}
|─> Inflation function            : Percentil equiponderado 80.0
|─> Resampling function           : Block bootstrap estacionario con bloque esperado 36
|─> Trend function                : Tendencia de caminata aleatoria
|─> Parametric inflation method   : Media ponderada interanual
|─> Number of simulations         : 1000
|─> End of training set           : Dec-19
|─> Evaluation periods            : Complete period y fincrisis:Jan-08-Dec-09
source
InflationEvalTools.SimDynamicConfigType
SimDynamicConfig{F, R, T}

Configuration type for simulations using the dynamic random walk trend (TrendDynamicRW). This configuration is similar to SimConfig but does not include a trendfn field, as it is implicitly designed for the dynamic trend.

It contains:

  • inflfn: Inflation function
  • resamplefn: Resampling function
  • trendfns: Vector of trend functions.
  • paramfn: Parametric inflation function (for population trend)
  • nsim: Number of simulations per fold
  • nfolds: Number of folds (trend instantiations)
  • traindate: End date of training set
  • evalperiod: Evaluation period

Example

config = SimDynamicConfig(inflfn, resamplefn, trend_functions, paramfn, 1000, 10, Date(2019,12), CompletePeriod())
source
InflationEvalTools.CompletePeriodType
CompletePeriod <: AbstractEvalPeriod

Type to represent the complete evaluation period, corresponding to the inflation periods of the data CountryStructure. The default tag for the complete period is empty (""), so that the evaluation metrics in the results generated in compute_lowlevel_sim do not have a prefix, as it is the main evaluation period. This period can be provided to a SimConfig configuration to evaluate over the entire range of simulated inflation dates.

Example

We create an instance of this type to represent the evaluation over the complete period of the inflation trajectories generated in the simulations.

julia> comp = CompletePeriod()
Complete period

See also: EvalPeriod, GT_EVAL_B00, GT_EVAL_B10, GT_EVAL_T0010

source
InflationEvalTools.EvalPeriodType
EvalPeriod <: AbstractEvalPeriod

Type to represent an evaluation period given by the dates startdate and finaldate. A label must be included in the tag field to attach to the results generated in compute_lowlevel_sim. This period can be provided to a SimConfig configuration to evaluate over a specific date range.

Example

We create an evaluation period called b2010 when generating the results.

julia> b2010 = EvalPeriod(Date(2011,1), Date(2019,12), "b2010")
b2010:Jan-11-Dec-19

See also: GT_EVAL_B00, GT_EVAL_B10, GT_EVAL_T0010

source
InflationEvalTools.PeriodVectorType
PeriodVector <: AbstractEvalPeriod

Type to represent a collection of evaluation periods, each given by a tuple of start and end dates. The tag field is used to label the set of periods for identification in results.

Example

Create a PeriodVector with two evaluation periods and a tag:

julia> pv = PeriodVector([(Date(2011,1), Date(2012,12)), (Date(2015,1), Date(2016,12))], "multi")
PeriodVector([(2011-01-01, 2012-12-31), (2015-01-01, 2016-12-31)], "multi")

See also: EvalPeriod, eval_periods

source
InflationEvalTools.eval_periodsFunction
eval_periods(cs::CountryStructure, period::EvalPeriod) -> BitVector
eval_periods(cs::CountryStructure, ::CompletePeriod) -> UnitRange

Returns a mask or a range of indices of the periods included in EvalPeriod or CompletePeriod to apply slicing to the inflation trajectories and the parameter before obtaining the evaluation metrics.

See also: EvalPeriod, CompletePeriod, period_tag.

source
InflationEvalTools.GT_EVAL_B00Constant
const GT_EVAL_B00 = EvalPeriod(Date(2001, 12), Date(2010, 12), "gt_b00")

Default period for evaluation in the decade of the 2000s, including the year 2010.

source
InflationEvalTools.GT_EVAL_B10Constant
const GT_EVAL_B10 = EvalPeriod(Date(2011, 12), Date(2021, 12), "gt_b10")

Default period for evaluation in the decade of the 2010s, including the year 2021.

source
InflationEvalTools.GT_EVAL_T0010Constant
const GT_EVAL_T0010 = EvalPeriod(Date(2011, 1), Date(2011, 11), "gt_t0010")

Default period for evaluation in the transition from the 2000s to the 2010s.

source

Trajectory Generation

Functions for generating inflation trajectories.

InflationEvalTools.gentrajinflFunction
function gentrajinfl(
        inflfn::F, resamplefn::R, trendfn::T,
        csdata::CountryStructure;
        numreplications = 100,
        rndseed = DEFAULT_SEED,
        showprogress = true
    ) where {F <: InflationFunction, R <: ResampleFunction, T <: TrendFunction}

Computes numreplications inflation trajectories using the inflation function inflfn::InflationFunction, the resampling function resamplefn::TrendFunction and the specified trend function trendfn::TrendFunction. The data in the given CountryStructure csdata are used.

Unlike the pargentrajinfl function, this function does not perform the computation in a distributed manner.

To achieve reproducibility between different runs of the function, and thus generate inflation trajectories with different methodologies using the same resamplings, the generation seed is set according to the iteration number in the simulation. To control the start of the trajectory generation, the rndseed offset parameter is used, whose default value is the seed DEFAULT_SEED.

source
InflationEvalTools.pargentrajinflFunction
pargentrajinfl(inflfn::F, resamplefn::R, trendfn::T, csdata::CountryStructure; 
    numreplications = 100, 
    rndseed = DEFAULT_SEED, 
    showprogress = true)

Computes numreplications inflation trajectories using the inflation function inflfn::InflationFunction, the resampling function resamplefn::ResampleFunction and the specified trend function trendfn::TrendFunction. The data in the given CountryStructure csdata are used.

Unlike the gentrajinfl function, this function implements distributed computation in processes using @distributed. This requires that the package has been loaded in all compute processes. For example:

using Distributed
addprocs(4, exeflags="--project")
@everywhere using InflationEvalTools

To achieve reproducibility between different runs of the function, and thus generate inflation trajectories with different methodologies using the same resamplings, the generation seed is set according to the iteration number in the simulation. To control the start of the trajectory generation, the rndseed offset parameter is used, whose default value is the seed DEFAULT_SEED.

source

Evaluation & Metrics

Functions for simulation evaluation and metrics.

InflationEvalTools.compute_lowlevel_simFunction
compute_lowlevel_sim(
    data::CountryStructure, config::SimConfig;
    rndseed = DEFAULT_SEED,
    shortmetrics = false,
    showprogress = false,
    verbose = true,
) -> (Dict, Array{<:AbstractFloat, 3})

Generate the parametric (population) trajectory, simulated inflation trajectories and evaluation metrics using a SimConfig.

Returns a tuple (metrics, traj_infl) where metrics is a dictionary of evaluation measures and traj_infl is a 3‑D array with dimensions (T, 1, K) (T = time steps, K = number of bootstrap realizations).

Arguments

  • data::CountryStructure: country dataset container used for resampling and trend estimation.
  • config::SimConfig: configuration with inflfn, resamplefn, trendfn, paramfn, nsim and evaluation periods.

Keyword arguments

  • rndseed: integer seed for the random generator (default = DEFAULT_SEED).
  • shortmetrics: when true compute a reduced set of metrics (faster / lower memory footprint). Default false.
  • showprogress: show progress bar during simulation generation (default false).
  • verbose: show information messages during the process (default true).

See also eval_metrics for details on the metric names stored in metrics.

source
compute_lowlevel_sim(
    data::CountryStructure, config::SimDynamicConfig;
    rndseed = DEFAULT_SEED,
    shortmetrics = false,
    showprogress = false,
) -> (Dict, Array{<:AbstractFloat, 3})

Generate the parametric (population) trajectory, simulated inflation trajectories and evaluation metrics using a SimDynamicConfig.

This function iterates length(config.trendfns) times. In each fold, it uses config.trendfns[i] to get the trend function for that fold. It generates config.nsim simulations per fold. The results are merged:

  • Metrics are collected into vectors (one value per fold).
  • Trajectories are concatenated along the third dimension (total simulations = nsim * nfolds).

Arguments

  • data::CountryStructure: country dataset container.
  • config::SimDynamicConfig: configuration.

Keyword arguments

  • rndseed: integer seed for the random generator of the simulation trajectories (default = DEFAULT_SEED).
  • shortmetrics: when true compute a reduced set of metrics.
  • showprogress: show progress bar.
source
InflationEvalTools.compute_assessment_simFunction
compute_assessment_sim(
    data::CountryStructure, config::SimConfig;
    rndseed = DEFAULT_SEED,
    savetrajectories = false,
    shortmetrics = false,
    showprogress = false,
    verbose = true,
) -> Dict

Run the low‑level simulation (compute_lowlevel_sim), collect evaluation metrics and return a results dictionary that merges the SimConfig parameters with the computed metrics.

Returns a dictionary results that always contains the metrics and config fields. If savetrajectories=true the returned dictionary includes the key :trajinfl containing the simulated trajectories array.

Keyword arguments

  • savetrajectories: when true add trajectories to the results dictionary (in the key :trajinfl). Default false.
  • shortmetrics: compute a reduced metrics set when true (default false).
  • showprogress: show progress during trajectory generation (default false).
  • verbose: show information messages during the process (default true).

Example

julia> results = compute_assessment_sim(gtdata, config)
source
compute_assessment_sim(
    data::CountryStructure, config::SimDynamicConfig;
    rndseed = DEFAULT_SEED,
    savetrajectories = false,
    shortmetrics = false,
    showprogress = false
) -> Dict

Run the low‑level simulation (compute_lowlevel_sim) for dynamic configuration.

source
InflationEvalTools.run_assessment_batchFunction
run_assessment_batch(
    data::CountryStructure, dict_list_params, savepath::AbstractString;
    rndseed = DEFAULT_SEED,
    savetrajectories = false,
    shortmetrics = false,
    showprogress = true,
    recompute = false,
)

Generate a batch of simulation assessments from a list (or iterable) of parameter dictionaries. Each element in dict_list_params is converted to a SimConfig or a SimDynamicConfig with dict2config and evaluated with compute_assessment_sim. Results are saved to savepath using DrWatson.savename so they can later be read by collect_results.

  • Recomputation of existing result files is skipped by default. To force recomputation, set recompute=true.

Arguments

  • dict_list_params: iterable of parameter dictionaries (usually created by expanding vectors of parameter values).
  • savepath: directory where per‑run result files will be written.

Keyword arguments

  • savetrajectories: save trajectories within each result file (default false).
  • shortmetrics: compute reduced metrics when true (default false).
  • showprogress: show progress indicator during generation (default true).
  • recompute: when true, recompute existing result files even if they exist on disk (default false).

Example

config_dict = Dict(
    :inflfn => InflationPercentileWeighted.(50:80),
    :resamplefn => resamplefn,
    :trendfn => trendfn,
    :paramfn => paramfn,
    :traindate => Date(2019, 12),
    :evalperiods => (CompletePeriod(),),
    :nsim => 1000) |> dict_list

run_assessment_batch(gtdata_eval, config_dict, savepath)

After the batch completes, use collect_results(savepath) to assemble a DataFrame with the stored metrics.

source
InflationEvalTools.eval_metricsFunction
eval_metrics(tray_infl, tray_infl_pob; shortmetrics=false, prefix="") -> Dict

Compute evaluation metrics for inflation trajectories.

This function calculates various statistical metrics to evaluate the performance of simulated inflation trajectories (tray_infl) against a parametric population trajectory (tray_infl_pob).

Arguments

  • tray_infl: Array of simulated inflation trajectories (3D array: periods x 1 x simulations).
  • tray_infl_pob: Vector or 1-column matrix of the parametric population inflation trajectory.
  • shortmetrics: Boolean. If true, returns a reduced dictionary with key metrics (MSE, RMSE, MAE, ME, AbsME, Huber, Correlation) and their standard errors. Default is true.
  • prefix: String. Optional prefix for the keys in the output dictionary.

Returns

A dictionary containing the computed metrics.

If shortmetrics=true, the dictionary includes:

  • mse, mse_std_error: Mean Squared Error and its standard error.
  • rmse, rmse_std_error: Root Mean Squared Error and its standard error.
  • mae, mae_std_error: Mean Absolute Error and its standard error.
  • me, me_std_error: Mean Error (Bias) and its standard error.
  • absme, absme_std_error: Absolute Mean Error and its standard error.
  • huber, huber_std_error: Huber Loss and its standard error.
  • corr: Average correlation between simulations and population trajectory.

If shortmetrics=false, the dictionary additionally includes:

  • std_mse_dist: Standard deviation of the MSE distribution.
  • std_sqerr_dist: Standard deviation of the squared error distribution.
  • mse_bias: Squared bias component of MSE decomposition.
  • mse_var: Variance component of MSE decomposition.
  • mse_cov: Covariance component of MSE decomposition.
  • T: Number of periods.
  • B: Number of simulations.
source
eval_metrics(tray_infl, tray_infl_pob; shortmetrics=false, prefix="") -> Dict

Compute evaluation metrics for inflation trajectories.

# Arguments
  • tray_infl: Array of simulated inflation trajectories (3D array: periods x 1 x simulations).
  • tray_infl_pob: Array of the parametric population inflation trajectory (3D array: periods x 1 x batches).
  • shortmetrics: Boolean. If true, returns a reduced dictionary with key metrics (MSE, RMSE, MAE, ME, AbsME, Huber, Correlation) and their standard errors. Default is true.
  • prefix: String. Optional prefix for the keys in the output dictionary.

Returns

A dictionary containing the computed metrics.

See also: eval_metrics.

source
InflationEvalTools.combination_metricsFunction
combination_metrics(tray_infl, tray_infl_param, w; kwargs...)

Metrics for linear combination measures. The trajectories in tray_infl are combined with the weights w and the evaluation metrics are computed using the parametric trajectory tray_infl_param.

Optional arguments (kwargs...) are passed to the function eval_metrics.

source
InflationEvalTools.eval_mse_onlineFunction
eval_mse_online(config::SimConfig, csdata::CountryStructure; 
    K = 1000, 
    rndseed = DEFAULT_SEED) -> mse

Function to obtain mean squared error evaluation using SimConfig evaluation configuration. The evaluation data must be provided in csdata, with which the comparison parametric trajectory is to be computed. Returns the MSE as a scalar.

This function can be used to optimize the parameters of different inflation measures and is more memory efficient than pargentrajinfl.

source
eval_mse_online(
    inflfn::InflationFunction,
    resamplefn::ResampleFunction, 
    trendfn::TrendFunction,
    csdata::CountryStructure, 
    tray_infl_param::Vector{<:AbstractFloat}; 
    K = 1000, rndseed = DEFAULT_SEED) -> mse

Function to obtain mean squared error (MSE) evaluation using the specified configuration. The parametric trajectory tray_infl_param is required to avoid repeatedly computing it in this function. Returns the MSE as a scalar.

source
InflationEvalTools.eval_absme_onlineFunction
eval_absme_online(config::SimConfig, csdata::CountryStructure; 
    K = 1000, 
    rndseed = DEFAULT_SEED) -> absme

Function to obtain evaluation of the mean absolute error value using SimConfig evaluation configuration. The evaluation data must be provided in csdata, with which the comparison parametric trajectory is to be computed. Returns the absolute value metric as a scalar.

This function can be used to optimize the parameters of different inflation measures and is more memory efficient than pargentrajinfl.

source
eval_absme_online(
    inflfn::InflationFunction,
    resamplefn::ResampleFunction, 
    trendfn::TrendFunction,
    csdata::CountryStructure, 
    tray_infl_param::Vector{<:AbstractFloat}; 
    K = 1000, rndseed = DEFAULT_SEED) -> absme

Function to obtain evaluation of the mean absolute error value (ABSME) using the specified configuration. The parametric trajectory tray_infl_param is required to avoid repeatedly computing it in this function. Returns the ABSME as a scalar.

source
InflationEvalTools.eval_corr_onlineFunction
eval_corr_online(config::SimConfig, csdata::CountryStructure;
    K = 1000, 
    rndseed = DEFAULT_SEED) -> corr

Function to obtain mean correlation (corr) evaluation using SimConfig evaluation configuration. The evaluation data must be provided in csdata, with which the comparison parametric trajectory is to be computed. Returns the mean correlation (corr) as a scalar.

This function can be used to optimize the parameters of different inflation measures and is more memory efficient than pargentrajinfl.

source
eval_corr_online(
    inflfn::InflationFunction,
    resamplefn::ResampleFunction, 
    trendfn::TrendFunction,
    csdata::CountryStructure, 
    tray_infl_param::Vector{<:AbstractFloat};
    K = 1000, rndseed = DEFAULT_SEED) -> corr

Function to obtain mean correlation (corr) evaluation using the specified configuration. The parametric trajectory tray_infl_param is required to avoid repeatedly computing it in this function. Returns the mean correlation (corr) as a scalar.

source

Combination Methods

Optimal combination of estimators and related utilities.

InflationEvalTools.combination_weightsFunction
combination_weights(tray_infl, tray_infl_param) -> Vector{<:AbstractFloat}

Obtains the optimal weights from the analytical solution to the problem of minimizing the mean squared error of the linear combination of inflation estimators in tray_infl using the parametric inflation trajectory tray_infl_param.

Returns a vector with the weights associated with each estimator in the columns of tray_infl.

See also: ridge_combination_weights, lasso_combination_weights, share_combination_weights, elastic_combination_weights.

source
InflationEvalTools.average_matsFunction
average_mats(tray_infl, tray_infl_param) -> (Matrix{<:AbstractFloat}, Vector{<:AbstractFloat})

Obtains the matrices XᵀX and Xᵀπ for the mean squared error minimization problem.

source
InflationEvalTools.ridge_combination_weightsFunction
ridge_combination_weights(tray_infl, tray_infl_param, lambda; 
    penalize_all = true) -> Vector{<:AbstractFloat}

Obtains optimal Ridge weights through the analytical solution to the problem of minimizing the mean squared error of the linear combination of inflation estimators in tray_infl using the parametric inflation trajectory tray_infl_param, regularized with the L2 norm of the weights, weighted by the parameter lambda.

Returns a vector with the weights associated with each estimator in the columns of tray_infl.

Optional parameters:

  • penalize_all (Bool): indicates whether to apply regularization to all weights. If false, regularization is applied from the second to the last component of the weights vector. Default is true.

See also: combination_weights, lasso_combination_weights, share_combination_weights, elastic_combination_weights.

source
InflationEvalTools.lasso_combination_weightsFunction
lasso_combination_weights(tray_infl, tray_infl_param, lambda; 
    max_iterations::Int = 1000, 
    alpha = F(0.005), 
    tol = F(1e-4), 
    show_status = true, 
    return_cost = false, 
    penalize_all = true) -> Vector{<:AbstractFloat}

Obtiene ponderadores óptimos de LASSO a través de una aproximación iterativa al problema de minimización del error cuadrático medio de la combinación lineal de estimadores de inflación en tray_infl utilizando la trayectoria de inflación paramétrica tray_infl_param, regularizada con la norma L1 de los ponderadores, ponderada por el parámetro lambda.

Los parámetros opcionales son:

  • max_iterations::Int = 1000: número máximo de iteraciones.
  • alpha::AbstractFloat = 0.001: parámetro de aproximación o avance del algoritmo de gradiente próximo.
  • tol::AbstractFloat = 1e-4: desviación absoluta de la función de costo. Si la función de costo varía en términos absolutos menos que tol de una iteración a otra, el algoritmo de gradiente se detiene.
  • show_status::Bool = true: mostrar estado del algoritmo iterativo.
  • return_cost::Bool = false: indica si devuelve el vector de historia de la función de costo de entrenamiento.
  • penalize_all::Bool = true: indica si aplicar la regularización a todos los ponderadores. Si es falso, se aplica la regularización a partir del segundo al último componente del vector de ponderaciones.

Devuelve un vector con los ponderadores asociados a cada estimador en las columnas de tray_infl.

Ver también: combination_weights, ridge_combination_weights, share_combination_weights, elastic_combination_weights.

source
InflationEvalTools.share_combination_weightsFunction
function share_combination_weights(tray_infl::AbstractArray{F, 3}, tray_infl_param; 
    restrict_all::Bool = true, 
    show_status::Bool = false) where F -> Vector{F}

Obtiene ponderadores no negativos, cuya suma es igual a 1. Estos ponderadores se pueden interpretar como participaciones en la combinación lineal.

Los parámetros opcionales son:

  • show_status::Bool = false: mostrar estado del proceso de optimización con Ipopt y JuMP.
  • restrict_all::Bool = true: indica si aplicar la restricción de la suma de ponderadores a todas las entradas del vector de ponderaciones. Si es false, se aplica la restricción a partir de la segunda entrada. Esto es para que si el primer ponderador corresponde a un término constante, este no sea restringido.
source
InflationEvalTools.elastic_combination_weightsFunction
elastic_combination_weights(tray_infl, tray_infl_param, lambda, gamma; 
    max_iterations::Int = 1000, 
    alpha = 0.001, 
    tol = 1e-4, 
    show_status = true, 
    return_cost = false, 
    penalize_all = true) -> Vector{<:AbstractFloat}

Obtiene ponderadores óptimos de Elastic Net a través de una aproximación iterativa al problema de minimización del error cuadrático medio de la combinación lineal de estimadores de inflación en tray_infl utilizando la trayectoria de inflación paramétrica tray_infl_param, regularizada con la norma L1 y L2 de los ponderadores, ponderada por el parámetro lambda. El porcentaje de regularización de la norma L1 se controla con el parámetro gamma.

Los parámetros opcionales son:

  • max_iterations::Int = 1000: número máximo de iteraciones.
  • alpha::AbstractFloat = 0.001: parámetro de aproximación o avance del algoritmo de gradiente próximo.
  • tol::AbstractFloat = 1e-4: desviación absoluta de la función de costo. Si la función de costo varía en términos absolutos menos que tol de una iteración a otra, el algoritmo de gradiente se detiene.
  • show_status::Bool = true: mostrar estado del algoritmo iterativo.
  • return_cost::Bool = false: indica si devuelve el vector de historia de la función de costo de entrenamiento.
  • penalize_all::Bool = true: indica si aplicar la regularización a todos los ponderadores. Si es falso, se aplica la regularización a partir del segundo al último componente del vector de ponderaciones.

Devuelve un vector con los ponderadores asociados a cada estimador en las columnas de tray_infl.

Ver también: combination_weights, ridge_combination_weights, share_combination_weights, lasso_combination_weights.

source
InflationEvalTools.metric_combination_weightsFunction
metric_combination_weights(tray_infl::AbstractArray{F, 3}, tray_infl_param; 
    metric::Symbol = :corr, 
    w_start = nothing, 
    x_abstol::AbstractFloat = 1f-2, 
    f_abstol::AbstractFloat = 1f-4, 
    max_iterations::Int = 1000) where F

Obtains optimal combination weights for the metric metric through an iterative approximation to the optimization problem of that metric for the linear combination of inflation estimators in tray_infl using the parametric inflation trajectory tray_infl_param.

Optional parameters:

  • metric::Symbol = :corr: metric to optimize. If it is linear correlation, the metric is maximized. The rest of the metrics are minimized. See also eval_metrics.
  • w_start = nothing: initial search weights. Typically, a vector of floating point values.
  • x_abstol::AbstractFloat = 1f-2: maximum absolute deviation of the weights.
  • f_abstol::AbstractFloat = 1f-4: maximum absolute deviation in the cost function.
  • sum_abstol::AbstractFloat = 1f-2: maximum permissible absolute deviation in the sum of weights, with respect to one.
  • max_iterations::Int = 1000: maximum number of iterations.
  • penalty::Function = w -> zero(F): penalty function applied to weights.

Returns a vector with the weights associated with each estimator in the columns of tray_infl.

See also: combination_weights, ridge_combination_weights, share_combination_weights, elastic_combination_weights.

source
InflationEvalTools.absme_combination_weightsFunction
absme_combination_weights(tray_infl::AbstractArray{F, 3}, tray_infl_param; 
    restrict_all::Bool = true, 
    show_status::Bool = false) where F -> Vector{F}

Obtains non-negative weights, whose sum is equal to 1, for the linear combination problem that minimizes the mean absolute error value. These weights can be interpreted as shares in the linear combination.

Optional parameters:

  • show_status::Bool = false: show the status of the optimization process with Ipopt and JuMP.
  • restrict_all::Bool = true: indicates whether to apply the sum-to-one constraint to all entries of the weights vector. If false, the constraint is applied from the second entry. This is so that if the first weight corresponds to a constant term, it is not constrained.
source
InflationEvalTools.share_combination_weights_rmseFunction
share_combination_weights_rmse(tray_infl::AbstractArray{F,3}, tray_infl_param::AbstractArray{F,3}, λ::AbstractFloat = 0.0) -> Vector{F}

Compute a vector of non-negative weights β that sum to 1 by minimizing a nonlinear loss function based on the average root mean squared error (RMSE).

Arguments:

  • tray_infl::AbstractArray{F,3}: Simulated inflation trajectories.
  • tray_infl_param::AbstractArray{F,3}: Parametric inflation trajectories.
  • λ::AbstractFloat = 0.0: Regularization parameter to penalize small weights.

See also: share_combination_weights_absme

source
InflationEvalTools.share_combination_weights_absmeFunction
share_combination_weights_absme(tray_infl::AbstractArray{F,3}, tray_infl_param::AbstractArray{F,3}, λ::AbstractFloat = 0.0) -> Vector{F}

Compute a vector of non-negative weights β that sum to 1 by minimizing a nonlinear loss function based on the absolute average mean error.

Arguments:

  • tray_infl::AbstractArray{F,3}: Simulated inflation trajectories.
  • tray_infl_param::AbstractArray{F,3}: Parametric inflation trajectories.
  • λ::AbstractFloat = 0.0: Regularization parameter to penalize small weights.

See also: share_combination_weights_rmse

source