Skip to content

Commit

Permalink
Merge pull request #145 from d100fuegos/drcm-inf-sub-opt-2024
Browse files Browse the repository at this point in the history
SubOpt_2024
  • Loading branch information
djgabrielm authored Nov 13, 2023
2 parents bacf433 + 4777a5f commit c327079
Show file tree
Hide file tree
Showing 45 changed files with 4,127 additions and 3 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ plots
# Extra data project structure #
################################################################################
data/**/*.xls*
data/**/*.png

################################################################################
# Julia #
Expand Down
70 changes: 70 additions & 0 deletions scripts/TOOLS/INFLFNS/rank.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# Funcion para ordenar las medidas de inflacion en un orden establecido
function rank(inflfn::InflationFunction)
if inflfn isa InflationPercentileEq
return 1
elseif inflfn isa InflationPercentileWeighted
return 2
elseif inflfn isa InflationTrimmedMeanEq
return 3
elseif inflfn isa InflationTrimmedMeanWeighted
return 4
elseif inflfn isa InflationDynamicExclusion
return 5
elseif inflfn isa InflationFixedExclusionCPI
return 6
elseif inflfn isa InflationCoreMai
if inflfn.method isa MaiFP
return 7
elseif inflfn.method isa MaiF
return 8
else
return 9
end
elseif inflfn isa Splice
return rank(inflfn.f[1])
end
end

function inflfn_tag(inflfn)
if inflfn == InflationPercentileEq
return "PerEq"
elseif inflfn == InflationPercentileWeighted
return "PerW"
elseif inflfn == InflationTrimmedMeanEq
return "MTEq"
elseif inflfn == InflationTrimmedMeanWeighted
return "MTW"
elseif inflfn == InflationDynamicExclusion
return "DynEx"
elseif inflfn <: InflationFixedExclusionCPI{T} where T
return "FxExc"
elseif inflfn == InflationCoreMai{Float32, Float64, MaiFP{Vector{Float64}}}
return "MaiFP"
elseif inflfn == InflationCoreMai{Float32, Float64, MaiF{Vector{Float64}}}
return "MaiF"
elseif inflfn == InflationCoreMai{Float32, Float64, MaiG{Vector{Float64}}}
return "MaiG"
end
end

function inflfn_name(inflfn)
if inflfn == InflationPercentileEq
return "Percentil Equiponderado"
elseif inflfn == InflationPercentileWeighted
return "Percentil Ponderado"
elseif inflfn == InflationTrimmedMeanEq
return "Media Truncada Equiponderada"
elseif inflfn == InflationTrimmedMeanWeighted
return "Media Truncada Ponderada"
elseif inflfn == InflationDynamicExclusion
return "Exclusion Dinámica"
elseif inflfn <: InflationFixedExclusionCPI{T} where T
return "Exclusion Fija"
elseif inflfn == InflationCoreMai{Float32, Float64, MaiFP{Vector{Float64}}}
return "Mai FP"
elseif inflfn == InflationCoreMai{Float32, Float64, MaiF{Vector{Float64}}}
return "Mai F"
elseif inflfn == InflationCoreMai{Float32, Float64, MaiG{Vector{Float64}}}
return "Mai G"
end
end
2 changes: 1 addition & 1 deletion scripts/TOOLS/OPTIM/mai-optim-functions.jl
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ function optimizemai(n, method, resamplefn, trendfn, dataeval, tray_infl_param;
"q" => argmin_fn(optres),
string(metric) => min_fn(optres),
"K" => K,
"optres" => optres
#"optres" => optres
)

# Guardar los resultados
Expand Down
2 changes: 1 addition & 1 deletion scripts/TOOLS/OPTIM/optim.jl
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ function optimize_config(config, data;
merge!(results, tostringdict(config))

# Guardar los resultados de evaluación para collect_results
filename = savename(results, "jld2", allowedtypes=(Symbol,Real, String, Date), digits=4)
filename = DrWatson.savename(results, "jld2", allowedtypes=(Symbol,Real, String, Date), digits=4)
isnothing(savepath) || wsave(joinpath(savepath, filename), tostringdict(results))

return results
Expand Down
5 changes: 5 additions & 0 deletions scripts/update_optim_combination_2024/2000/0.0_load_data.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
using DrWatson
@quickactivate "HEMI"

include(scriptsdir("load_data.jl"))
using HEMI
104 changes: 104 additions & 0 deletions scripts/update_optim_combination_2024/2000/1.0_optim.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
using DrWatson
@quickactivate "HEMI"

include(scriptsdir("TOOLS","OPTIM","optim.jl"))

########################################################
################ BASE 2000 #############################
########################################################

savepath = datadir("optim_comb_2024","2000","individual")

##
#Datos a Utilizar
gtdata_eval = GTDATA[Date(2010,12)]

##Configuración

D = dict_list(
Dict(
:infltypefn => [
InflationPercentileEq,
InflationPercentileWeighted,
InflationTrimmedMeanEq,
InflationTrimmedMeanWeighted,
InflationDynamicExclusion,
],
:resamplefn => ResampleScrambleVarMonths(),
:trendfn => TrendRandomWalk(),
:paramfn => InflationTotalRebaseCPI(36,3),
:nsim => 10_000,
:traindate => Date(2010, 12)
)
)

M = [:mse, :absme, :corr]

## Asignación de Valores Iniciales
X0 = [
[
0.72,
0.69,
[58.0, 83.0],
[21.0, 95.0],
[0.31, 1.68]
]
,
[
0.71,
0.69,
[35.0, 93.0],
[34.0, 93.0],
[1.00, 3.42]

]
,
[
0.77,
0.80,
[55.0, 92.0],
[46.0, 98.0],
[0.46, 4.97]

]
]

## Optimización

DF = DataFrame()

for i in 1:length(M)
for j in 1:length(D)
save_path = joinpath(savepath,string(M[i]))
optres = optimize_config(D[j], gtdata_eval; measure=M[i], savepath = save_path, x0 = X0[i][j])
merge!(optres, tostringdict(D[j]))
optres["minimizer"]= Ref(optres["minimizer"])
global DF = vcat(DF,DataFrame(optres))
end
end

## Resultados
using PrettyTables
pretty_table(DF[:,[:measure,:metric,:minimizer, :optimal]])

# ┌──────────────────────────────┬────────┬───────────────────────────────────────────┬────────────┐
# │ measure │ metric │ minimizer │ optimal │
# │ String │ Symbol │ String │ Float64 │
# ├──────────────────────────────┼────────┼───────────────────────────────────────────┼────────────┤
# │ InflationPercentileEq │ mse │ 0.71991086 │ 0.200018 │
# │ InflationPercentileWeighted │ mse │ 0.6969478 │ 0.404245 │
# │ InflationTrimmedMeanEq │ mse │ [53.104444980621324, 86.56443614959717] │ 0.172042 │
# │ InflationTrimmedMeanWeighted │ mse │ [33.23044020980596, 92.21051075756554] │ 0.309032 │
# │ InflationDynamicExclusion │ mse │ [0.29588394165039045, 1.4893161773681638] │ 0.306363 │
# │ InflationPercentileEq │ absme │ 0.71239126 │ 0.305044 │
# │ InflationPercentileWeighted │ absme │ 0.68823665 │ 0.132583 │
# │ InflationTrimmedMeanEq │ absme │ [42.72982835769655, 91.0218214035034] │ 0.00789602 │
# │ InflationTrimmedMeanWeighted │ absme │ [45.59877253142186, 87.04819001266733] │ 7.62834e-5 │
# │ InflationDynamicExclusion │ absme │ [1.1207321733236313, 3.4683535182476044] │ 3.07523e-5 │
# │ InflationPercentileEq │ corr │ 0.79305905 │ 0.975212 │
# │ InflationPercentileWeighted │ corr │ 0.77419573 │ 0.938846 │
# │ InflationTrimmedMeanEq │ corr │ [53.6291259765625, 89.752685546875] │ 0.978878 │
# │ InflationTrimmedMeanWeighted │ corr │ [50.38429222106934, 91.86738662719728] │ 0.952717 │
# │ InflationDynamicExclusion │ corr │ [0.31163650512695307, 1.2446017456054674] │ 0.950955 │
# └──────────────────────────────┴────────┴───────────────────────────────────────────┴────────────┘

Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
using DrWatson
@quickactivate "HEMI"

include(scriptsdir("load_data.jl"))
using HEMI
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
# Script con optimización y evaluación, con datos y configuración de simulación hasta 2019

## carga de paquetes
using DrWatson
@quickactivate "HEMI"

# Cargar el módulo de Distributed para computación paralela
using Distributed
# Agregar procesos trabajadores
nprocs() < 5 && addprocs(4, exeflags="--project")

# Cargar los paquetes utilizados en todos los procesos
@everywhere using HEMI
using CSV, DataFrames, Chain
#using Plots

##

## Definición de instancias principales
trendfn = TrendRandomWalk()
resamplefn = ResampleScrambleVarMonths()
paramfn = InflationTotalRebaseCPI(36,3)

# Para optimización Base 2000
ff00 = Date(2010,12)
# Para optimización Base 2010
ff10 = Date(2020,12)

################# Optimización Base 2000 ###################################

# Creación de vector de de gastos básicos ordenados por volatilidad.

estd = std(gt00.v |> capitalize |> varinteran, dims=1)

df = DataFrame(num = collect(1:length(vec(estd))), Desv = vec(estd))

sort!(df, :Desv, rev=true)

vec_v = df[!,:num]

# Creación de vectores de exclusión
# Se crean 218 vectores para la exploración inicial y se almacenan en v_exc
v_exc = []
for i in 1:length(vec_v)
exc = vec_v[1:i]
append!(v_exc, [exc])
end

# Diccionarios para exploración inicial (primero 100 vectores de exclusión)
FxEx_00 = Dict(
:inflfn => InflationFixedExclusionCPI.(v_exc[1:30]),
:resamplefn => resamplefn,
:trendfn => trendfn,
:paramfn => paramfn,
:nsim => 10_000,
:traindate => ff00,
:evalperiods => GT_EVAL_B00,
) |> dict_list

savepath = datadir("optim_comb_2024","2000_2010","Fx-Exc","mse","B00")

## Lote de simulación con los primeros 100 vectores de exclusión

run_batch(GTDATA, FxEx_00, savepath; savetrajectories=false)

## Recolección de resultados
Exc_0019 = collect_results(savepath)

## Análisis de exploración preliminar
# obtener longitud del vector de exclusión de cada simulación
exclusiones = getindex.(map(x -> length.(x), Exc_0019[!,:params]),1)
Exc_0019[!,:exclusiones] = exclusiones

# Ordenamiento por cantidad de exclusiones
Exc_0019 = sort(Exc_0019, :exclusiones)

# DF ordenado por MSE
sort_0019 = sort(Exc_0019, :gt_b00_mse)

## Exctracción de vector de exclusión y MSE
exc00 = collect(sort_0019[1,:params])[1]

# [35, 30, 190, 36, 37, 40, 31, 104, 162, 32, 33, 159, 193, 161]


################# Optimización Base 2010 ###################################

# Vector óptimo base 2000 encontrado en la primera sección
#exc00 = [35, 30, 190, 36, 37, 40, 31, 104, 162, 32, 33, 159, 193, 161]

## Creación de vector de de gastos básicos ordenados por volatilidad, con información a Diciembre de 2019

est_10 = std(GTDATA[Date(2019,12)][2].v |> capitalize |> varinteran, dims=1)

df = DataFrame(num = collect(1:279), Desv = vec(est_10))

sorted_std = sort(df, "Desv", rev=true)

vec_v = sorted_std[!,:num]

# Creación de vectores de exclusión
# Se crearán 100 vectores para la exploración inicial
v_exc = []
tot = []
total = []
for i in 1:length(vec_v)
exc = vec_v[1:i]
global v_exc = append!(v_exc, [exc])
global tot = (exc00, v_exc[i])
global total = append!(total, [tot])
end
total

# Diccionarios para exploración inicial (primero 100 vectores de exclusión)
FxEx_10 = Dict(
:inflfn => InflationFixedExclusionCPI.(total[1:60]),
:resamplefn => resamplefn,
:trendfn => trendfn,
:paramfn => paramfn,
:nsim => 10_000,
:traindate => ff10
) |> dict_list

savepath = datadir("optim_comb_2024","2000_2010","Fx-Exc","mse","B10")

## Lote de simulación con los primeros 100 vectores de exclusión

run_batch(GTDATA, FxEx_10, savepath; savetrajectories = false)

## Recolección de resultados
Exc_1018 = collect_results(savepath)

## Análisis de exploración preliminar
# obtener longitud del vector de exclusión de cada simulación
exclusiones = getindex.(map(x -> length.(x), Exc_1018[!,:params]),1)
Exc_1018[!,:exclusiones] = exclusiones

# Ordenamiento por cantidad de exclusiones
Exc_1018 = sort(Exc_1018, :exclusiones)

# DF ordenado por MSE
sort_1019 = sort(Exc_1018, :mse)

## Exctracción de vector de exclusión y MSE
Exc = collect(sort_1019[1,:params])

#[35, 30, 190, 36, 37, 40, 31, 104, 162, 32, 33, 159, 193, 161]
#[29, 31, 116, 39, 46, 40, 30, 35, 186, 47, 197, 41, 22, 48, 185, 34, 184]

savepath = datadir("optim_comb_2024","2000_2010")
savepath_mse_b00 = joinpath(savepath,"B00","mse")
savepath_mse_b10 = joinpath(savepath,"B10","mse")

wsave(joinpath(savepath_mse_b00,"fx_exc.jld2"),"inflfn",InflationFixedExclusionCPI(Exc...))
wsave(joinpath(savepath_mse_b10,"fx_exc.jld2"),"inflfn",InflationFixedExclusionCPI(Exc...))

Loading

0 comments on commit c327079

Please sign in to comment.