Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
braverock
GitHub Repository: braverock/portfolioanalytics
Path: blob/master/R/EntropyProg.R
1433 views
1
#' Entropy pooling program for blending views on scenarios with a prior scenario-probability distribution
2
#'
3
#' Entropy program will change the initial predictive distribution 'p' to a new set 'p_' that satisfies
4
#' specified moment conditions but changes other propoerties of the new distribution the least by
5
#' minimizing the relative entropy between the two distributions. Theoretical note: Relative Entropy (Kullback-Leibler information criterion KLIC) is an
6
#' asymmetric measure.
7
#'
8
#' We retrieve a new set of probabilities for the joint-scenarios using the Entropy pooling method
9
#' Of the many choices of 'p' that satisfy the views, we choose 'p' that minimize the entropy or distance of the new probability
10
#' distribution to the prior joint-scenario probabilities.
11
#'
12
#' We use Kullback-Leibler divergence or relative entropy dist(p,q): Sum across all scenarios [ p-t * ln( p-t / q-t ) ]
13
#' Therefore we define solution as p* = argmin (choice of p ) [ sum across all scenarios: p-t * ln( p-t / q-t) ],
14
#' such that 'p' satisfies views. The views modify the prior in a cohrent manner (minimizing distortion)
15
#' We forumulate the stress tests of the baseline scenarios as linear constraints on yet-to-be defined probabilities
16
#' Note that the numerical optimization acts on a very limited number of variables equal
17
#' to the number of views. It does not act directly on the very large number of variables
18
#' of interest, namely the probabilities of the Monte Carlo scenarios. This feature guarantees
19
#' the numerical feasability of entropy optimization.
20
#'
21
#' Note that new probabilities are generated in much the same way that the state-price density modifies
22
#' objective probabilities of pay-offs to risk-neutral probabilities in contingent-claims asset pricing
23
#'
24
#' Compute posterior (=change of measure) with Entropy Pooling, as described in
25
#'
26
#' @param p a vector of initial probabilities based on prior (reference model, empirical distribution, etc.). Sum of 'p' must be 1
27
#' @param Aeq matrix consisting of equality constraints (paired with argument 'beq'). Denoted as 'H' in the Meucci paper. (denoted as 'H' in the "Meucci - Flexible Views Theory & Practice" paper formlua 86 on page 22)
28
#' @param beq vector corresponding to the matrix of equality constraints (paired with argument 'Aeq'). Denoted as 'h' in the Meucci paper
29
#' @param A matrix consisting of inequality constraints (paired with argument 'b'). Denoted as 'F' in the Meucci paper
30
#' @param b vector consisting of inequality constraints (paired with matrix A). Denoted as 'f' in the Meucci paper
31
#' @param verbose If TRUE, prints out additional information. Default FALSE.
32
#'
33
#' ' \deqn{ \tilde{p} \equiv argmin_{Fx \leq f, Hx \equiv h} \big\{ \sum_1^J x_{j} \big(ln \big( x_{j} \big) - ln \big( p_{j} \big) \big) \big\}
34
#' \\ \ell \big(x, \lambda, \nu \big) \equiv x' \big(ln \big(x\big) - ln \big(p\big) \big) + \lambda' \big(Fx - f\big) + \nu' \big(Hx - h\big)}
35
#' @return a list with
36
#' \describe{
37
#' \item{\code{p_}:}{ revised probabilities based on entropy pooling}
38
#' \item{\code{optimizationPerformance}:}{ a list with status of optimization,
39
#' value, number of iterations, and sum of probabilities}
40
#' }
41
#' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com}
42
#' @references
43
#' A. Meucci - "Fully Flexible Views: Theory and Practice". See page 22 for illustration of numerical implementation
44
#' Symmys site containing original MATLAB source code \url{https://www.arpm.co/}
45
#' NLOPT open-source optimization site containing background on algorithms \url{https://nlopt.readthedocs.io/en/latest/}
46
#' We use the information-theoretic estimator of Kitamur and Stutzer (1997).
47
#' Reversing 'p' and 'p_' leads to the empirical likelihood" estimator of Qin and Lawless (1994).
48
#' See Robertson et al, "Forecasting Using Relative Entropy" (2002) for more theory
49
#' @export
50
EntropyProg = function( p , A = NULL , b = NULL , Aeq , beq, verbose=FALSE )
51
{
52
stopifnot("package:nloptr" %in% search() || requireNamespace("nloptr",quietly = TRUE) )
53
54
if( is.vector(b) ) b = matrix(b, nrow=length(b))
55
if( is.vector(beq) ) beq = matrix(beq, nrow=length(beq))
56
57
if( !length(b) ) A = matrix( ,nrow = 0, ncol = 0)
58
if( !length(b) ) b = matrix( ,nrow = 0, ncol = 0)
59
60
# count the number of constraints
61
K_ = nrow( A ) # K_ is the number of inequality constraints in the matrix-vector pair A-b
62
K = nrow( Aeq ) # K is the number of equality views in the matrix-vector pair Aeq-beq
63
64
# parameter checks
65
if ( K_ + K == 0 ) { stop( "at least one equality or inequality constraint must be specified")}
66
if ( ( ( .999999 < sum(p)) & (sum(p) < 1.00001) ) == FALSE ) { stop( "sum of probabilities from prior distribution must equal 1")}
67
if ( nrow(Aeq) != nrow(beq) ) { stop( "number of inequality constraints in matrix Aeq must match number of elements in vector beq") }
68
if ( nrow(A) != nrow(b) ) { stop( "number of equality constraints in matrix A must match number of elements in vector b") }
69
70
# calculate derivatives of constraint matrices
71
A_ = t( A )
72
b_ = t( b )
73
Aeq_ = t( Aeq )
74
beq_ = t( beq )
75
76
# starting guess for optimization search with length = to number of views
77
x0 = matrix( 0 , nrow = K_ + K , ncol = 1 )
78
79
# set up print arguments for verbose
80
if(verbose){
81
check_derivatives_print = "all"
82
print_level = 2
83
} else {
84
check_derivatives_print = "none"
85
print_level = 0
86
}
87
88
if ( !K_ ) # equality constraints only
89
{
90
# define maximum likelihood, gradient, and hessian functions for unconstrained and constrained optimization
91
eval_f_list = function( v ) # cost function for unconstrained optimization (no inequality constraints)
92
{
93
x = exp( log(p) - 1 - Aeq_ %*% v )
94
x = apply( cbind( x , 10^-32 ) , 1 , max ) # robustification
95
# L is the Lagrangian dual function (without inequality constraints). See formula 88 on p. 22 in "Meucci - Fully Flexible Views - Theory and Practice (2010)"
96
# t(x) is the derivative x'
97
# Aeq_ is the derivative of the Aeq matrix of equality constraints (denoted as 'H in the paper)
98
# beq_ is the transpose of the vector associated with Aeq equality constraints
99
# L= x' * ( log(x) - log(p) + Aeq_ * v ) - beq_ * v
100
# 1xJ * ( Jx1 - Jx1 + JxN+1 * N+1x1 ) - 1xN+1 * N+1x1
101
L = t(x) %*% ( log(x) - log(p) + Aeq_ %*% v ) - beq_ %*% v
102
mL = -L # take negative values since we want to maximize
103
104
# evaluate gradient
105
gradient = beq - Aeq %*% x
106
107
# evaluate Hessian
108
# We comment this out for now -- to be used when we find an optimizer that can utilize the Hessian in addition to the gradient
109
# H = ( Aeq %*% (( x %*% ones(1,K) ) * Aeq_) ) # Hessian computed by Chen Qing, Lin Daimin, Meng Yanyan, Wang Weijun
110
111
return( list( objective = mL , gradient = gradient ) )
112
}
113
114
# setup unconstrained optimization
115
start = Sys.time()
116
opts = list( algorithm = "NLOPT_LD_LBFGS" ,
117
xtol_rel = 1.0e-6 ,
118
check_derivatives = TRUE ,
119
check_derivatives_print = check_derivatives_print ,
120
print_level = print_level ,
121
maxeval = 1000 )
122
optimResult = nloptr::nloptr(x0 = x0, eval_f = eval_f_list , opts = opts )
123
end = Sys.time()
124
125
if(verbose){
126
print( c("Optimization completed in ", end - start ))
127
}
128
129
if ( optimResult$status < 0 ) {
130
print( c("Exit code " , optimResult$status ) )
131
stop( "Error: The optimizer did not converge" )
132
}
133
134
# return results of optimization
135
v = optimResult$solution
136
p_ = exp( log(p) - 1 - Aeq_ %*% v )
137
optimizationPerformance = list( converged = (optimResult$status > 0) ,
138
ml = optimResult$objective ,
139
iterations = optimResult$iterations ,
140
sumOfProbabilities = sum( p_ ) )
141
}else # case inequality constraints are specified
142
{
143
# setup variables for constrained optimization
144
InqMat = -diag( 1 , K_ + K ) # -1 * Identity Matrix with dimension equal to number of constraints
145
InqMat = InqMat[ -c( K_+1:nrow( InqMat ) ) , ] # drop rows corresponding to equality constraints
146
InqVec = matrix( 0 , K_ , 1 )
147
148
# define maximum likelihood, gradient, and hessian functions for constrained optimization
149
InqConstraint = function( x ) { return( InqMat %*% x ) } # function used to evalute A %*% x <= 0 or A %*% x <= c(0,0) if there is more than one inequality constraint
150
151
jacobian_constraint = function( x ) { return( InqMat ) }
152
# Jacobian of the constraints matrix. One row per constraint, one column per control parameter (x1,x2)
153
# Turns out the Jacobian of the constraints matrix is always equal to InqMat
154
155
nestedfunC = function( lv )
156
{
157
lv = as.matrix( lv )
158
l = lv[ 1:K_ , , drop = FALSE ] # inequality Lagrange multiplier
159
v = lv[ (K_+1):length(lv) , , drop = FALSE ] # equality lagrange multiplier
160
x = exp( log(p) - 1 - A_ %*% l - Aeq_ %*% v )
161
x = apply( cbind( x , 10^-32 ) , 1 , max )
162
163
# L is the cost function used for constrained optimization
164
# L is the Lagrangian dual function with inequality constraints and equality constraints
165
L = t(x) %*% ( log(x) - log(p) ) + t(l) %*% (A %*% x-b) + t(v) %*% (Aeq %*% x-beq)
166
objective = -L # take negative values since we want to maximize
167
168
# calculate the gradient
169
gradient = rbind( b - A%*%x , beq - Aeq %*% x )
170
171
# compute the Hessian (commented out since no R optimizer supports use of Hessian)
172
# Hessian computed by Chen Qing, Lin Daimin, Meng Yanyan, Wang Weijun
173
#onesToK_ = array( rep( 1 , K_ ) ) ;onesToK = array( rep( 1 , K ) )
174
#x = as.matrix( x )
175
#H11 = A %*% ((x %*% onesToK_) * A_) ; H12 = A %*% ((x %*% onesToK) * Aeq_)
176
#H21 = Aeq %*% ((x %*% onesToK_) * A_) ; H22 = Aeq %*% ((x %*% onesToK) * Aeq_)
177
#H1 = cbind( H11 , H12 ) ; H2 = cbind( H21 , H22 ) ; H = rbind( H1 , H2 ) # Hessian for constrained optimization
178
return( list( objective = objective , gradient = gradient ) )
179
}
180
181
# find minimum of constrained multivariate function
182
start = Sys.time()
183
# Note: other candidates for constrained optimization in library nloptr: NLOPT_LD_SLSQP, NLOPT_LD_MMA, NLOPT_LN_AUGLAG, NLOPT_LD_AUGLAG_EQ
184
# See NLOPT open-source site for more details: http://ab-initio.mit.edu/wiki/index.php/NLopt
185
local_opts <- list( algorithm = "NLOPT_LD_SLSQP",
186
xtol_rel = 1.0e-6 ,
187
check_derivatives = TRUE ,
188
check_derivatives_print = check_derivatives_print ,
189
eval_f = nestedfunC ,
190
eval_g_ineq = InqConstraint ,
191
eval_jac_g_ineq = jacobian_constraint )
192
optimResult = nloptr::nloptr( x0 = x0 ,
193
eval_f = nestedfunC ,
194
eval_g_ineq = InqConstraint ,
195
eval_jac_g_ineq = jacobian_constraint ,
196
opts = list( algorithm = "NLOPT_LD_AUGLAG" ,
197
local_opts = local_opts ,
198
print_level = print_level ,
199
maxeval = 1000 ,
200
check_derivatives = TRUE ,
201
check_derivatives_print = check_derivatives_print ,
202
xtol_rel = 1.0e-6 ))
203
end = Sys.time()
204
if(verbose){
205
print( c("Optimization completed in " , end - start ))
206
}
207
208
if ( optimResult$status < 0 ) {
209
print( c("Exit code " , optimResult$status ) )
210
stop( "Error: The optimizer did not converge" )
211
}
212
213
# return results of optimization
214
lv = matrix( optimResult$solution , ncol = 1 )
215
l = lv[ 1:K_ , , drop = FALSE ] # inequality Lagrange multipliers
216
v = lv[ (K_+1):nrow( lv ) , , drop = FALSE ] # equality Lagrange multipliers
217
p_ = exp( log(p) -1 - A_ %*% l - Aeq_ %*% v )
218
optimizationPerformance = list( converged = (optimResult$status > 0),
219
ml = optimResult$objective,
220
iterations = optimResult$iterations,
221
sumOfProbabilities = sum( p_ ))
222
}
223
224
if(verbose) print( optimizationPerformance )
225
226
if ( sum( p_ ) < .999 ) { stop( "Sum of revised probabilities is less than 1!" ) }
227
if ( sum( p_ ) > 1.001 ) { stop( "Sum of revised probabilities is greater than 1!" ) }
228
229
return ( list ( p_ = p_ , optimizationPerformance = optimizationPerformance ) )
230
}
231
232
233
234
#' Generates histogram
235
#'
236
#' @param X a vector containing the data points
237
#' @param p a vector containing the probabilities for each of the data points in X
238
#' @param nBins expected number of Bins the data set is to be broken down into
239
#' @param freq a boolean variable to indicate whether the graphic is a representation of frequencies
240
#'
241
#' @return a list with
242
#' f the frequency for each midpoint
243
#' x the midpoints of the nBins intervals
244
#'
245
#' @references
246
#' \url{https://www.arpm.co/}
247
#' See Meucci script pHist.m used for plotting
248
#' @author Ram Ahluwalia \email{ram@@wingedfootcapital.com} and Xavier Valls \email{flamejat@@gmail.com}
249
pHist = function( X , p , nBins, freq = FALSE )
250
{
251
if ( length( match.call() ) < 3 )
252
{
253
J = dim( X )[ 1 ]
254
nBins = round( 10 * log(J) )
255
}
256
257
dist = hist( x = X , breaks = nBins , plot = FALSE );
258
n = dist$counts
259
x = dist$breaks
260
D = x[2] - x[1]
261
262
N = length(x)
263
# np = zeros(N , 1)
264
np = matrix(0, nrow=N, ncol=1)
265
for (s in 1:N)
266
{
267
# The boolean Index is true is X is within the interval centered at x(s) and within a half-break distance
268
Index = ( X >= x[s] - D/2 ) & ( X <= x[s] + D/2 )
269
# np = new probabilities?
270
np[ s ] = sum( p[ Index ] )
271
f = np/D
272
}
273
274
plot( x , f , type = "h", main = "Portfolio return distribution")
275
276
return( list( f = f , x = x ) )
277
}
278
279