Minimizes a function (variance over 1mln data-points)?

I have attached below one Mathematica notebook and a MATLAB file where I try to find the \theta which minimizes a function (variance over 1mln data-points).

The MATLAB code runs pretty fast, while the execution of the Mathematica code freezes my machine.

Any suggestions how to make the Mathematica code executable (at least)?

The problem is that:

$HistoryLength=1;
S=100;K=70;\[Sigma]=0.2;T=1;r=0.01;\[Alpha]=r-\[Sigma]^2/2;
n=100;
Z=RandomVariate[NormalDistribution[],n];
fVarPut[\[Theta]_]:=Variance[E^(-r T) Ramp[K-S E^(\[Alpha] T+\[Sigma] Sqrt[T](Z+\[Theta]))]E^(-\[Theta](Z+\[Theta])+\[Theta]^2/2)];

LogPlot[fVarPut[x],{x,-2,4},PlotRange->All]

looks like something like:

so

fVarPut[100]

will always give 0. it is ‘flat’ on the right (equal to 0, because of the Ramp function), so there is not one minimum…

The definition of pVarPut needs to signal that the function only works with a numeric argument.

In[1]:= S = 100; K = 70; [Sigma] = 0.2; T = 1; r = 0.01; [Alpha] =
r - [Sigma]^2/2;

In[2]:= n = 100;
Z = RandomVariate[NormalDistribution[], n];

In[4]:= fVarPut[\[Theta]_?NumberQ] := 
  Variance[E^(-r T)
     Ramp[K - 
      S E^(\[Alpha] T + \[Sigma] Sqrt[
         T] (Z + \[Theta]))] E^(-\[Theta] (Z + \[Theta]) + \[Theta]^2/
      2)];

In[5]:= (* freezes even with WorkingPrecision\[Rule]5 *)
NMinimize[fVarPut[x], x, WorkingPrecision -> 5]

Out[5]= {0, {x -> 3.3686}}

In[6]:= FindMinimum[fVarPut[x], {x, -2}, WorkingPrecision -> 5]

Out[6]= {1.0248*10^-382, {x -> -32.000}}

I don’t get any freeze with your code. However, it may run faster if you use the immediate assignment

fVarPut[\[Theta]_?NumberQ] = 
  Variance[E^(-r T) Ramp[
     K - S E^(\[Alpha] T + \[Sigma] Sqrt[
            T] (Z + \[Theta]))] E^(-\[Theta] (Z + \[Theta]) + \
\[Theta]^2/2)];

instead of the delayed assignment :=, because with delayed assignment Mathematica has to recalculate the Variance formula every time fVarPut is called.

Thank you very much all of you!

I was about to write that it freezes either way even if I ask for the minimum for the interval (-4,-1), when I read Frank’s paramount remark.

So much better now! :slight_smile:

This will calculate the variance in a symbolic way once; that might be or not be a smart idea depending on the number of points. Definitely not a smart move if n is large, it will do a lot of (comparatively) slow symbolic processing.

Frank Kampas’s solution is a good idea; to turn it into a numeric computation, which is very fast. It will avoid Mathematica trying to do any symbolic manipulation on it.

You will need to constrain it using something like:

FindMinimum[f,{x,x0,xmin,xmax}]

As this problem will have a minimum for x → -infinity and for x>a for some ‘a’ it is constant (kind of a minimum) (a depends on the random values).

I have a poor machine, Gianluca.. and a bit weird I guess, because it gives me that the implementation with “=” is slower than the one with “:=”