'x' has to be an array of at least two dimensions - r

I have been trying to price knock-in and knock-out options, but I have a problem I can't seem to solve:
when coding the knock-in option, with the code:
knockInOptionMC <- function( Type = c('Call','Put'), Type2 = c('Down In', 'Up In'), P, T., r, K, B){
if(Type2 == 'Down In'){
knockedIn <- P < B
}else{
knockedIn <- P > B
}
alive <- colSums(knockedIn) == 1
PT <- tail(P,1)
if(Type == 'Call'){
payoff <- ( PT > K ) * (alive) * ( PT - K )
}else{
payoff <- ( PT < K ) * (alive) * ( K - PT )
}
simulatedPayoff <- exp( -r * T. ) * payoff
return( mean(simulatedPayoff) )
}
knockInOptionMC('Put','Down In', P, T., r, K = 105 , B = 105)
I get no error, but when I try to do the same thing for the knock out, with the following code:
knockOutOptionMC <- function( Type = c('Call','Put'), Type2 = c('Down Out', 'Up Out'), P, T., r, K, B){
if(Type2 == 'Down Out'){
knockedOut <- P < B
}else{
knockedOut <- P > B
}
alive <- colSums(knockedOut) == 0
PT <- tail(P,1)
if(Type == 'Call'){
payoff <- ( PT > K ) * (alive) * ( PT - K )
}else{
payoff <- ( PT < K ) * (alive) * ( K - PT )
}
simulatedPayoff <- exp( -r * T. ) * payoff
return( mean(simulatedPayoff) )
}
knockOutOptionMC( 'Put','Up Out', T., r, K = 105, B = 95 )
I get the error 'x' has to be an array of at least two dimensions in the object colsums.
why why why do I get the error since they're basically the same thing?
thank you sm

The error likely comes from the colSums() line - which needs its argument to be two-dimensional to have columns.
The core of the problem is not in the function, but how you call them:
knockInOptionMC ('Put', 'Down In', P, T., r, K = 105, B = 105)
knockOutOptionMC('Put', 'Up Out', T., r, K = 105, B = 95 )
So you are likely passing a two-dimensional variable P in the first case, but missing it in the second, and pass a one-dimensional T. instead.
Chances are that the function run successfully in case 2 because you have the missing variables defined in the parent environment.

Related

Maple magic square

Ok I really need your help guys I'm really lost this looks so simple but I can't figure it out.
Note : this is for 3x3 magic square
So here's the condition for a magic square :
1. the sum of the elements of a row = k
2.the sum of the elements of a column = k
3. the sum of the elements of a diagonal = k
The question is :
I have to translate the 3 conditions up there into a linear systeme Bx=0 where x=(a,b,c,d,e,f,g,h,i) which represents the unknown of the matrix 3x3 and B is a 7x9 matrix.
so here's what I've done :
So yea the goal is to write a homogeneous system with the form Bx=0 to then determine its solution.
But I'm kinda lost at this point, I feel stupid cause it seems easy haha could someone help would be greatly appreciated thank you !
I suggest solving the system in terms of a smaller number of free variables, and then using permutations of [1,...,9] to check for solutions. Please try the following, which uses k=15 and returns the single solution (after removing rotations and reflections):
restart;
# Number of variables.
m := 9;
# Variables.
X := [ seq( x[i], i=1..m ) ];
# Indices.
N := [ seq( i, i=1..m ) ];
# Equations.
EQ := [ x[1] + x[2] + x[3] = 15,
x[4] + x[5] + x[6] = 15,
x[7] + x[8] + x[9] = 15,
x[1] + x[4] + x[7] = 15,
x[2] + x[5] + x[8] = 15,
x[3] + x[6] + x[9] = 15,
x[1] + x[5] + x[9] = 15,
x[3] + x[5] + x[7] = 15
];
# Constraints to remove equivalent solutions.
INEQ := [ x[1] < x[3], x[1] < x[7], x[1] < x[9], x[3] < x[7] ];
# Solve in terms of free parameters.
A, B := LinearAlgebra:-GenerateMatrix( EQ, X );
S := convert( LinearAlgebra:-LinearSolve( A, B, ':-free'=x ), 'list' );
# Free parameters.
Q := convert( indets( S, 'name' ), 'list' );
n := numelems( Q );
# Table to store solutions.
H := table();
# Cycle through all possible values for Q, first by combination, and then by permutation,
# and record any solutions found.
for i from 1 to combinat:-numbcomb( m, n ) do
if i = 1 then
C := convert( combinat:-firstcomb( m, n ), 'list' ):
else
C := convert( combinat:-nextcomb( C, m ), 'list' ):
end if:
for j from 1 to n! do
if j = 1 then
P := C:
else
P := combinat:-nextperm( P ):
end if:
T := eval( S, Q =~ P ):
# Check if it is a solution satisfying all the constraints.
if andmap( is, [ sort( T ) = N, op( eval( EQ, X =~ T ) ), op( eval( INEQ, X =~ T ) ) ] ) then
H[T] := NULL:
end if:
end do:
end do:
# Solutions.
map( op, [ indices( H ) ] );

How to find solution with optim using r

I have quite simple question yet I cannot seem to solve it.
I'm trying to find a parameter with optim() r function.
Here is the case:
library(rootSolve)
d <- read.table(text="indx rate n d
1 0.12 158 14
2 0.095 135 9
3 0.057 123 4
4 0.033 115 5
5 0.019 90 4", header=T)
d$real <- with(d, d/n)
opt <- d[ ,c("rate","real", "n")]
# this is close to the correct solution!
scaler <- apply(opt, 1, function(z) uniroot.all(
function(alpha) z[2] - (1 / (1 + alpha * ( (1 - z[1]) / z[1] )) ), interval = c(0,10)))
# check for solution (not fully correct!)
round(crossprod(scaler * opt$real, opt$n)/sum(opt$n), 3) == round(crossprod(round(opt$rate, 3), opt$n)/sum(opt$n), 3)
# using optim() - completely wrong results
infun <- function(data, alpha){ l <- with(data,
( rate - (1 / ( 1 + alpha[1] * ( (1 - real)/real ))) )); return( -sum( l ) ) }
opt_out <- optim(c(0,0), infun, data=opt, method = "BFGS", hessian = TRUE)
with(opt, (1 / ( 1 + opt_out$par[1] * ( (1 - real)/real ))))
You are trying, with your code, to get an unique alpha for all, but you want to have five values ..
So, you are leaded to make a sum .. but if you have negative and positive values, your sum could go near zero even with individual terms far from 0 ..
Moreover, your infun function is not in accordance with your previous function ..
What you can do is something like that :
infun <- function(alpha){ l <- with(cbind(d, alpha), ( real - (1 / ( 1 +
alpha * ( (1 - rate)/rate ))) )); return( sum(abs(l)) ) }
param <- c(5,5,5,5,5)
opt_out <- optim(par = scaler, infun, method = "BFGS", hessian = TRUE)
And in order to check the result you should have written :
with( cbind(opt,opt_out$par), real -1 / ( 1 + opt_out$par * ( (1 - rate)/rate )))
To get the true solution, you can do (after a very litle mathematics on a paper) :
sol <- -((opt[,2]-1)/(opt[,2]))*(opt[,1]/(1-opt[,1]))
and test it :
with( cbind(opt,sol), real -1 / ( 1 + opt_out$par * ( (1 - rate)/rate )))

Differential Eq using deSolve in R

My apologies, for being unclear earlier. I now understand the function a bit more, but could use some assistance on a few aspects.
I would like to get back a relationship of conversion ( X ) versus volume ( V ), or the other way around would be fine as well. It would seem to me that the traditional "times" term is what I want to replace with an X sequence from 0 - 1, X is conversion remember so bounded by 0 and 1.0
Below, rw is the reaction rate, and is a function of the partial pressures at any given moment, which are described as P.w, P.x, P.y, and P.z which themselves are functions of the initial conditions (P.w0, v.0) and the conversion, again X.
Thank you in advance
rm(list = ls())
weight <- function( Vols, State, Pars ) {
with(as.list(c(State, Pars)), {
y = 1
delta = 2
ya.0 = 0.4
eps = ya.0 * delta
temp = 800
R = 8.314
k.2 = exp( (35000 / ( R*temp )) - 7.912 )
K.3 = exp( 4.084 / temp - 4.33 )
P.w <- P.w0 * ( 1 - X ) * y / ( 1 + eps * X )
P.x <- P.w0 * ( 1 - 2*X ) * y / ( 1 + eps * X )
P.y <- P.w0 * ( 1 + X ) * y / ( 1 + eps * X )
P.z <- P.w0 * ( 1 + 4*X ) * y / ( 1 + eps * X )
r.w <- k.2 * ( K.3 * P.w * P.x ^ 2 - P.y * P.z^4 )
F.w0 <- P.w0 * v.0 / ( R * temp )
dX.dq <- r.w / F.w0
res <- dX.dq
return(list(res))
})
}
pars <- c( y = 1,
P.w0 = 23,
v.0 = 120 )
yini <- c( X = 0 )
vols <- seq( 0 , 100 , by = 1 )
out <- ode( yini , vols , weight , pars )
Just running
vol.func(0,0,params)
i.e., evaluating the gradient at the initial conditions, gives NaN. The proper way to diagnose this is to divide your complex gradient expressions up into separate terms and see which one is causing trouble. I'm not going to go through this in detail, but as #Sixiang.Hu points out in comments above, you're dividing by V in your gradient function, which will cause infinite values if the numerator is finite or NaN values if the numerator is zero ...
More generally, it's not clear whether you understand that the first argument to the gradient function (your vol.func) is supposed to be the current time, not a value of the state variable. Perhaps V is supposed to be your state variable, and X should be a parameter ...?

ContrOptim Function- Error in Argument

I'm trying to replicate the Excel Solver in R- which is basically a constraint optimization problem
I'm trying to minimize the cost per action which is total spend/ total actions which equals to the below function with a few constraints.
CPA function:
(a+b+c+d)/((consta+(Baln(a)))+ (constb+(Bbln(b)))+(constc+(Bcln(c)))+(constd+(Bdln(d)))
where the unknown variables are a,b,c,d and const* stands for constant from a regressions and B* stand for coefficient from a regression (so they are values that I have).
Here is the simplified filled in function that I'm trying to minimize:
(a+b+c+d)/ (((69.31*ln(a))+(14.885*ln(b))+(21.089*ln(c))+(9.934*ln(d))-(852.93))
Constraints:
a+b+c+d>=0
a+b+c+d<=130000(total spend)
a<=119000 (maxa)
a>=272.56(mina)
b<=11000(maxb)
b>=2.04(minb)
c<=2900(maxc)
c>=408.16(minc)
d<=136800(maxd)
d>=55.02(mind)
I'm doing this using the constraints optimization function. My code is below:
g<-function(a,b,c,d) { (a+b+c+d)/((consta+(Balog(a)))+ (constb+(Bblog(b)))+ (constc+(Bclog(c)))+ (constd+(Bdlog(d)))) }
gb<-function(a) g(a[1], a[2], a[3],a[4])
A<-matrix(c(1,0,0,0,-1,0,0,0,0,1,0,0,0,-1,0,0,0,0,1,0,0,0,-1,0,0,0,0,1,0,0,0,-1,-1,-1,-1,-1,1,1,1,1),4,10)
B<- c(mina, -maxa, minb, -maxb, minc, -maxc, mind, -maxd,-totalspend, 0)
constrOptim(c(273,6,409,56),g,gb,A,B)
When I run the optimization function, it states that something is wrong with my arguments (Error in ui %*% theta : non-conformable arguments). I think it is the gradient of the function that is coded wrong but I'm not sure. Any help is appreciated.
You can consider the following approach
library(DEoptim)
fn_Opt <- function(param)
{
a <- param[1]
b <- param[2]
c <- param[3]
d <- param[4]
bool_Cond <- a + b + c + d <= 130000
if(bool_Cond == FALSE)
{
return(10 ^ 30)
}else
{
val <- (a + b + c + d) / (((69.31 * log(a)) + (14.885 * log(b)) + (21.089 * log(c)) + (9.934 * log(d)) - (852.93)))
return(val)
}
}
obj_DEoptim <- DEoptim(fn = fn_Opt, lower = c(272.56, 2.04, 408.16, 55.02),
upper = c(119000, 11000, 2900, 136800),
control = list(itermax = 10000))

Mixture modeling - troublee with infinite values from exp() and log()

I'm writing a function for Gaussian mixture models with spherical covariance structures--ie $\Sigma_k = \sigma_k^2 I$. This particular function is similar to the mclust package with identifier VII.
http://en.wikipedia.org/wiki/Mixture_model
Anyways, the problem I'm having is running into infinite values for the weight matrix. Definition: Let W be an n x m matrix where n = 1, ..., n (number of obs) and m = 1, ..., m (number of mixtues). Each element of W (ie w_ij) can essentially be defined as a specific form of:
w_im = \frac{a / b * exp(c)}{\sum_i=1^m [a_i / b_i * exp(c_i)]}
Computing this numerically is giving me infinite values. So I'm trying to use the log-identity log(x+y) = log(x) + log(1 + y/x). But the issue is that it's not as simple as log(x+y) but rather log(\sum_i=1^m [a_i / b_i * exp(c_i)]).
Here's some code define:
n_im = a / b * exp(c) ;
d_.m = \sum_i=1^m [a_i / b_i * exp(c_i)] ; and
c_mat[i,j] as the value of the exponent for the [i,j]th term.
n_mat[, i] <- log(a[i]) - log(b[i]) - c[,i] # numerator of w_im
internal_vec1[i] <- (a[i] * b[1])/ (a[1] * b[i]) # an internal for the step below
c_mat2 <- cbind(rep(1, n), c_mat[,1] - c_mat[,-1]) # since e^a / e^b = e^(a-b)
for (i in 1:n) {
d_vec[i] <- n_mat[i,1] + log(sum(internal_vec1 * exp(c_mat2[i,)))
} ## still getting infinite values
I'm trying to define the problem as briefly as possible. the entire function is obviously much larger than this. But, since the problem I'm running into is specifically dealing with infinite (and 1/infinity) values, I'm hoping this snippet is sufficient. Anyone with a coding trick here?
Here is the solution!! (I've spent way too damn long on this)
**The first function log_plus() solves the simple problem where you want log(\sum_{i=1)^n x_i)
**The second function log_plus2() solves the more complicated problem described above where you want log(\sum_{i=1}^n [a_i / b_i * exp(c_i)])
log_plus <- function(xvec) {
m <- length(xvec)
x <- log(xvec[1])
for (j in 2:m) {
sum_j <- sum(xvec[1:j-1])
x <- x + log(1 + xvec[j]/sum_j)
}
return(x)
}
log_plus2 <- function(a, b, c) {
# assumes intended input of form sum(a/b * e^c)
if ((length(a) != length(b)) || (length(a) != length(c))) {
stop("Input equal length vectors")
}
if (!(all(c > 0) || all(c < 0))) {
stop("All values of c must be either > 0 or < 0.")
}
m <- length(a)
# initilialize log sum
x <- log(a[1]) - log(b[1]) + c[1]
# aggregate / loop log sum
for (j in 2:m) {
# build denominator
b2 <- b[1:j-1]
for (i in 1:j-1) {
d1 <- 0
c2 <- c[1:i]
if (all(c2 > 0)) {
c_min <- min(c2[1:j-1])
c2 <- c2 - c_min
} else if (all(c2 < 0)) {
c_min <- max(c2[1:j-1])
c2 <- c2 - c_min
}
d1 <- d1 + a[i] * prod(b2[-i]) * exp(c2[i])
}
den <- b[j] * (d1)
num <- a[j] * prod(b[1:j-1]) * exp(c[j] - c_min)
x <- x + log(1 + num / den)
}
return(x)
}

Resources