Initialization

(*Copyright (c)<year=2012,2013,2014,2015,2016,2017>, <copyright holder owner-Rixhard John Belshaw AGU,AAAS,ASA,IEEE,ACS,ACM>All rights reserved.  Using a Modified MUSIC (Multiple Signal Classification) I was able to identify the periodicities and cyclical trends in the data.  The Book 'Introduction to Spectral Analysis' was instrumental in this modification by Stoica and Moses.  This allowed extrapolation of periodicities in the data with a Fourier technique.  I call this Fourier Extrapolation.
 Modified algorithm fourieranalysis copyright Richard J Belshaw 2014, All rights reserved.  I used a Multiple Signal Classification (MUSIC) algorthm first invented by myself in 1989 (University of Waterloo, Ontario, Canada) as a student in Dr. Madavan's Adaptive Neurophysiological Signal Processing Class.  I extended it with root finding to include slow frequencies from the high resolution FFT of the data.  Then i calculated the phase and magnitude at each root and FFT slow frequency and then extrapolated them beyond the window.  It is very accurate and quite fast!  I call this Fourier Extrapolation.  With the Wavelets,  i computed the wavelets of the data,  then at each level i used Fourier Extrapolation to extrapolate the wavelet coefficients into the future.  This is called Wavelet Extrapolation!  I used no backpropagation in the development of my Neural Net software but used a functional insight to solve them with random perturbations,  and it is quicker and more accurate than backpropagation.  This was a unique idea on my part and if simulated annealing or a Boltzman type machine or genetic algorithms were applied to the weights on a cooling schedule,  a better global minimum might more reliably be found, but this would indeed be slower than backpropagation or the functional insight so it was not implemented, however it might yield a better final result if speed can be sacrificed for a more accurate global minimum.
I have adapted a technique from Sornette et al. to estimate the extreme values of the Density Functional Bayesian markov ratio distribution in getPDF5,  and have estimated the probabilities for the Markov transition probabilities empirically from the data.  Using these markov probabilities i was able to generate as many probable paths into the future as i wished, and this formed the basis of the Monte Carlo simulation and path integration.
The Bayesian Markov Monte Carlo simulation does not do a good job at estimating cyclical trends or periodicities in the data , however it does do a good job of predicting long term exponential increases or descreases unlike fourier, wavelets or the neural nets. However the neural nets can also do an excellent job at estimating periodicities in the data.  The Wavelet extrapolation and the Fourier extrapolation and the Neural Nets are in place in order to assess by the expert the periodicities and cyclical trends in the data.  Sometimes a look back of 1,2 or 3 or 5 years is necessary to get these cycles estimated adequately.  the future is not completely known.  News events for a stock can change its fortunes overnight or if a competitor eclipses it, or they have shady or illegal accounting and tax practices or they are very inefficient at what they do or are not able to sufficiently innovate new products to capture new market niches.  That said,  past performance is not necessarily the best indicator of future success,  but it can be a reliable indicator,  thats what Buffet bases his analysis on over the previous 10 years Earnings per Share increases, as well as assessing the human resources capital of a company.  
Please read the BSD-3 license below to establish that there is no liability on the authors part.  This sofware is supplied
as is,  can be commercialized, and can be used at universities or colleges or for educational purposes as well.
********  The techniques developed in this software can also be applied to nuclear fission for load prediction and control and radiation intensity forecasting and control with graphite rod control feedback,  nuclear fusion for plasma intensity and location forecasting and magnetic field containment control and feedback, political polling and forecasting, Insurance for assessing solvency and profit of an insurance program, metallurgy for achieving optimal thermal trajectories and control, airplane turbulence forecasting and control and mitigation, it can also be used for 60 minute binary currency options and Scientific Forecasting and Time Series Forecasting and
Control Theory when added to a Kalman Filter or a feedback system for Control.


BSD-3 License - Open Source Software.
Redistribution and use in source and binary forms,with or without
modification,are permitted provided that the following conditions are met:
*Redistributions of source code must retain the above copyright
notice,this list of conditions and the following disclaimer.
*Redistributions in binary form must reproduce the above copyright
notice,this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
*Neither the name of the<organization>nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES,INCLUDING,BUT NOT LIMITED TO,THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.IN NO EVENT SHALL<COPYRIGHT HOLDER>BE LIABLE FOR ANY
DIRECT,INDIRECT,INCIDENTAL,SPECIAL,EXEMPLARY,OR CONSEQUENTIAL DAMAGES
(INCLUDING,BUT NOT LIMITED TO,PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE,DATA,OR PROFITS;OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY,WHETHER IN CONTRACT,STRICT LIABILITY,OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE,EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*)

(* Stock Forecasting with Bayesian Markov Monte Carlo Simulation and with Wavelet extrapolation or Fourier extrapolation or Neural Networks for American Option Pricing with Timely Indicators for long and short term investment *)

(*Please scroll down to the bottom of the file to see the input section where it says optionPrices[*****] etc... there is info there and a sample output of both AAPL and MSFT  *)

(* All Rights Reserved - CopyRight 2012, Richard John Belshaw, AGU,AAAS,ASA,IEEE,ACS,ACM*)

LaunchKernels[]

Needs["Calendar`"]

ClearAll[matlabFind1]
matlabFind1[lst_List,Op_:{Unequal,,Greater,Equal,GreaterEqual,LessEqual},elt_:0]:=Module[{x},Flatten[Position[lst,x_/;Op[x,elt]]]];

NeuralNet

ClearAll[NeuralNet1];

NeuralNet1[x_List,nodeslayer_List,inneriterations_Integer,rho_Real,toler_Real,numberpasses_Integer,futuresteps_Integer,w1in_List,w2in_List,w3in_List,w4in_List,Ain_Real,optionflag_Integer,deTrendflag_Integer,debugflag2_Integer] := Module[{w1,w2,w3,w4,w1min,w2min,w3min,w4min,wstar,i,j,k,temp1,temp2,temp3,mpe,minmpe,temp4,epsilon,y,ystar,x4,x3,x2,x1,lastmpe,wtemp1,wtemp2,wtemp3,wtemp4,debugflag,wtemp1last,wtemp2last,wtemp3last,wtemp4last,z1,lastw,z,z2,z3,y1,n,m,w1mem,w2mem,w3mem,w4mem,count,list1,list2,OrderList,q,x0,Amin,A,p,maxval,minval,maxranval,ratio,mpe2,sumval1,sumval2,ratiomin,gamma,alpha1,alpha2,coeffs,deTrendedData,volatility,lastflag,lastAmin,lastw1min,lastw2min,lastw3min,lastw4min,count2,R,theta,x5,y5,delta,minrmse,A1,s0,plot1,signal,x10},
maxranval=.114488;
coeffs = ConstantArray[0,2];
deTrendedData = ConstantArray[0,Length[x]+futuresteps];
volatility = 0;
debugflag=0;
s0=x[[-1]];
{plot1,signal}=MusicFinal[x,futuresteps,s0,Length[x],0,debugflag];
x10= Join[x,Flatten[signal[[1,1;;futuresteps]]]];
If[deTrendflag==1,
{coeffs,deTrendedData,volatility}=getPercentErrorLinear[x10,debugflag];
minval = Min[deTrendedData];
maxval = Max[deTrendedData];
x0= N[(deTrendedData-minval)/(maxval-minval)*.2-.1],
minval=Min[x1];
maxval=Max[x1];
x0=N[(x10-minval)/(maxval-minval)*.2-.1]];

gamma=1;
minmpe=100000;
minrmse=100000;
lastmpe = 100000;
w1 = ConstantArray[0.0,{nodeslayer[[1]],nodeslayer[[2]]}];
w1min = ConstantArray[0.0,{nodeslayer[[1]],nodeslayer[[2]]}];
w1mem = ConstantArray[0.0,{nodeslayer[[1]],nodeslayer[[2]]}];
wtemp1= ConstantArray[0.0,{nodeslayer[[1]],nodeslayer[[2]]}];
 wtemp1last=ConstantArray[0.0,{nodeslayer[[1]],nodeslayer[[2]]}];
w2 = ConstantArray[0.0,{nodeslayer[[2]],nodeslayer[[3]]}];
w2min= ConstantArray[0.0,{nodeslayer[[2]],nodeslayer[[3]]}];
w2mem = ConstantArray[0.0,{nodeslayer[[2]],nodeslayer[[3]]}];
wtemp2 =  ConstantArray[0.0,{nodeslayer[[2]],nodeslayer[[3]]}];
wtemp2last =  ConstantArray[0.0,{nodeslayer[[2]],nodeslayer[[3]]}];
w3 = ConstantArray[0.0,{nodeslayer[[3]],nodeslayer[[4]]}];
w3min = ConstantArray[0.0,{nodeslayer[[3]],nodeslayer[[4]]}];
w3mem = ConstantArray[0.0,{nodeslayer[[3]],nodeslayer[[4]]}];

wtemp3 =  ConstantArray[0.0,{nodeslayer[[3]],nodeslayer[[4]]}];
wtemp3last =  ConstantArray[0.0,{nodeslayer[[3]],nodeslayer[[4]]}];
w4 = ConstantArray[0.0,nodeslayer[[4]]];
w4min= ConstantArray[0.0,nodeslayer[[4]]];
w4mem= ConstantArray[0.0,nodeslayer[[4]]];
wtemp4 = ConstantArray[0.0,nodeslayer[[4]]];
wtemp4last = ConstantArray[0.0,nodeslayer[[4]]];
x4=ConstantArray[0.0,nodeslayer[[4]]];
x3 = ConstantArray[0.0,nodeslayer[[3]]];
x2 = ConstantArray[0.0,nodeslayer[[2]]];
x1 = ConstantArray[0.0,nodeslayer[[1]]];
A1=ConstantArray[1.0,Length[x]-nodeslayer[[1]]];
If[optionflag==1,
epsilon = 0.0;
z2 = numberpasses;
n=0;
z3=0;
count2=0;

While[count2<numberpasses,
A=1.0;
Do[Do[If[RandomReal[{0.0,1.0}]<.5,w1[[i,j]]=RandomReal[{.001,maxranval}],w1[[i,j]]=RandomReal[{-.001,-maxranval}]],{i,1,nodeslayer[[1]]}],{j,1,nodeslayer[[2]]}];

Do[Do[If[RandomReal[{0.0,1.0}]<.5,w2[[i,j]]=RandomReal[{.001,maxranval}],w2[[i,j]]=RandomReal[{-.001,-maxranval}]],{i,1,nodeslayer[[2]]}],{j,1,nodeslayer[[3]]}];

Do[Do[If[RandomReal[{0.0,1.0}]<.5,w3[[i,j]]=RandomReal[{.001,maxranval}],w3[[i,j]]=RandomReal[{-.001,-maxranval}]],{i,1,nodeslayer[[3]]}],{j,1,nodeslayer[[4]]}];

Do[If[RandomReal[{0.0,1.0}]<.5,w4[[i]]=RandomReal[{.001,maxranval}],w4[[i]]=RandomReal[{-.001,-maxranval}]],{i,1,nodeslayer[[4]]}];

z1=1;
z=0;
While[z< z1,
list1 = Range[Length[x10]-nodeslayer[[1]]];
OrderList ={};
Do[ temp1 = RandomInteger[{1,Length[list1]}];  AppendTo[OrderList,list1[[temp1]]];
list2 = matlabFind1[list1,Unequal,list1[[temp1]]];
If[Length[list2]>0,list1= list1[[list2]]],{q,1,Length[x]-nodeslayer[[1]]}];
k=1;
Clear[lastw];
While[k+nodeslayer[[1]]≤ Length[x],
i=1;


wtemp1= N[w1*rho];
Clear[temp1,temp2,temp3];
{x1,temp1,temp2,temp3,y}=EvaluateNet[x0[[OrderList[[k]];;OrderList[[k]]+nodeslayer[[1]]-1]],nodeslayer,A,wtemp1,w2,w3,w4];
wtemp1last=N[w1*(1+2*(rho-1))];
Clear[temp1,temp2,temp3];
{x1,temp1,temp2,temp3,y}=EvaluateNet[x0[[OrderList[[k]];;OrderList[[k]]+nodeslayer[[1]]-1]],nodeslayer,A,wtemp1last,w2,w3,w4];
Clear[temp1,temp2,temp3];
{x1,temp1,temp2,temp3,y}=EvaluateNet[x0[[OrderList[[k]];;OrderList[[k]]+nodeslayer[[1]]-1]],nodeslayer,A,w1,w2,w3,w4];
Clear[wstar];
If [debugflag==1,Print["*14"]];
Do[i=1;lastw=rho*w1; While[i≤ inneriterations &&Abs[1-Sqrt[Total[wtemp1[[All,j]]*wtemp1[[All,j]]]/Total[w1[[All,j]]*w1[[All,j]]]]]>toler,
wstar = w1;
If [debugflag==1,Print["*15"]];
alpha1 = N[ArcTan[Tan[Total[wtemp1[[All,j]]*x1]/Pi*4.]-Tan[Total[wtemp1last[[All,j]]*x1]/Pi*4.]]];
alpha2 = N[ArcTan[Tan[Total[w1[[All,j]]*x1]/Pi*4.]-Tan[Total[wtemp1[[All,j]]*x1]/Pi*4.]]];
If [Abs[alpha1-alpha2]>0&&Abs[alpha2]>0,
wstar[[All,j]] = w1[[All,j]]+gamma*(w1[[All,j]]-2*wtemp1[[All,j]]+wtemp1last[[All,j]])/(1-alpha1/alpha2); 
Clear[temp1,temp2,temp3];
{x1,temp1,temp2,temp3,y}=EvaluateNet[x0[[OrderList[[k]];;OrderList[[k]]+nodeslayer[[1]]-1]],nodeslayer,A,wstar,w2,w3,w4];
wtemp1last=wtemp1;
wtemp1= w1;
w1 = wstar;
If [debugflag==1,Print["*16"]];
,i=inneriterations];i=i+1],{j,1,nodeslayer[[2]]}];


wtemp2= w2*rho;
Clear[temp1,temp2];
{x1,x2,temp1,temp2,y}=EvaluateNet[x0[[OrderList[[k]];;OrderList[[k]]+nodeslayer[[1]]-1]],nodeslayer,A,w1,wtemp2,w3,w4];
Clear[temp1,temp2];
wtemp2last=w2*(1+2*(rho-1));
{x1,x2,temp1,temp2,y}=EvaluateNet[x0[[OrderList[[k]];;OrderList[[k]]+nodeslayer[[1]]-1]],nodeslayer,A,w1,wtemp2last,w3,w4];
Clear[temp1,temp2];
{x1,x2,temp1,temp2,y}=EvaluateNet[x0[[OrderList[[k]];;OrderList[[k]]+nodeslayer[[1]]-1]],nodeslayer,A,w1,w2,w3,w4];
If [debugflag==1,Print["*10"]];
Do[i=1;lastw=w2*rho;While[i≤ inneriterations &&Abs[1-Sqrt[Total[wtemp2[[All,j]]*wtemp2[[All,j]]]/Total[w2[[All,j]]*w2[[All,j]]]]]>toler,

If [debugflag==1,Print["*11"]];
wstar =w2;
alpha1 = N[ArcTan[Tan[Total[wtemp2[[All,j]]*x2]/Pi*4.]-Tan[Total[wtemp2last[[All,j]]*x2]/Pi*4.]]];
alpha2 = N[ArcTan[Tan[Total[w2[[All,j]]*x2]/Pi*4.]-Tan[Total[wtemp2[[All,j]]*x2]/Pi*4.]]];
If [Abs[alpha1-alpha2]>0&&Abs[alpha2]>0,
wstar[[All,j]] = w2[[All,j]]+gamma*(w2[[All,j]]-2*wtemp2[[All,j]]+wtemp2last[[All,j]])/(1-alpha1/alpha2); 
Clear[temp1,temp2];
{x1,x2,temp1,temp2,y}=EvaluateNet[x0[[OrderList[[k]];;OrderList[[k]]+nodeslayer[[1]]-1]],nodeslayer,A,w1,wstar,w3,w4];
wtemp2last=wtemp2;
wtemp2 = w2;
w2 = wstar;
If [debugflag==1,Print["*12"]];

(*Do[
epsilon =ArcTan[Tan[Total[w2[[All,j]]*x2]/Pi*4.]-x3[[j]]];
     x2[[m]]= x2[[m]]+w2[[m,j]]^(-1)*epsilon,{m,1,nodeslayer[[2]]}];*)
If [debugflag==1,Print["*13"]];
,i=inneriterations];i=i+1],{j,1,nodeslayer[[3]]}];

Clear[wstar];


If [debugflag==1,Print["*5"]];
wtemp3 = w3*rho;
Clear[temp1];
{x1,x2,x3,temp1,y}=EvaluateNet[x0[[OrderList[[k]];;OrderList[[k]]+nodeslayer[[1]]-1]],nodeslayer,A,w1,w2,wtemp3,w4];
Clear[temp1];
wtemp3last=w3*(1+2*(rho-1));
{x1,x2,x3,temp1,y}=EvaluateNet[x0[[OrderList[[k]];;OrderList[[k]]+nodeslayer[[1]]-1]],nodeslayer,A,w1,w2,wtemp3last,w4];
Clear[temp1];
{x1,x2,x3,temp1,y}=EvaluateNet[x0[[OrderList[[k]];;OrderList[[k]]+nodeslayer[[1]]-1]],nodeslayer,A,w1,w2,w3,w4];
lastw = w3;
If [debugflag==1,Print["*6"]];
Clear[wstar];
Do[i=1;lastw=w3*rho;While [i≤ inneriterations &&Abs[1-Sqrt[Total[wtemp3[[All,j]]*wtemp3[[All,j]]]/Total[w3[[All,j]]*w3[[All,j]]]]]>toler,
If [debugflag==1,Print["*7"]];
wstar =w3;
alpha1 = N[ArcTan[Tan[Total[wtemp3[[All,j]]*x3]/Pi*4.]-Tan[Total[wtemp3last[[All,j]]*x3]/Pi*4.]]];
alpha2 = N[ArcTan[Tan[Total[w3[[All,j]]*x3]/Pi*4.]-Tan[Total[wtemp3[[All,j]]*x3]/Pi*4.]]];
If [Abs[alpha1-alpha2]>0&&Abs[alpha2]>0,
wstar[[All,j]] = w3[[All,j]]+gamma*(w3[[All,j]]-2*wtemp3[[All,j]]+wtemp3last[[All,j]])/(1-alpha1/alpha2); 
If [debugflag==1,Print["*8"]];
Clear[temp1];
{x1,x2,x3,temp1,y}=EvaluateNet[x0[[OrderList[[k]];;OrderList[[k]]+nodeslayer[[1]]-1]],nodeslayer,A,w1,w2,wstar,w4];
wtemp3last=wtemp3;
wtemp3 = w3;
w3=wstar;

(*Do[
epsilon =ArcTan[Tan[Total[w3[[All,j]]*x3]/Pi*4.]-x4[[j]]];
     x3[[m]]= x3[[m]]+w3[[m,j]]^(-1)*epsilon,{m,1,nodeslayer[[3]]}];*)
If [debugflag==1,Print["*9"]];
,i=inneriterations];i=i+1],{j,1,nodeslayer[[4]]}];

Clear[wstar];
wtemp4 = w4*rho;
{x1,x2,x3,x4,y1}=EvaluateNet[x0[[OrderList[[k]];;OrderList[[k]]+nodeslayer[[1]]-1]],nodeslayer,A,w1,w2,w3,wtemp4];

wtemp4last=w4*(1+2*(rho-1));
{x1,x2,x3,x4,y1}=EvaluateNet[x0[[OrderList[[k]];;OrderList[[k]]+nodeslayer[[1]]-1]],nodeslayer,A,w1,w2,w3,wtemp4last];
{x1,x2,x3,x4,y}=EvaluateNet[x0[[OrderList[[k]];;OrderList[[k]]+nodeslayer[[1]]-1]],nodeslayer,A,w1,w2,w3,w4];
Clear[wstar];
If [debugflag==1,Print["*1"]];
While[i≤ inneriterations&&Abs[1-Sqrt[Total[wtemp4*wtemp4]/Total[w4*w4]]]>toler,
If [debugflag==1,Print["*2"]];
wstar = w4;
alpha1 = N[Total[wtemp4*x4]-Total[wtemp4last*x4]];
alpha2 =N[Total[w4*x4]-Total[wtemp4*x4]]; 
If [Abs[alpha1-alpha2]>0&&Abs[alpha2]>0,
wstar = w4+gamma*(w4-2*wtemp4+wtemp4last)/(1-alpha1/alpha2); 

If [debugflag==1,Print["*3"]];
{x1,x2,x3,x4,y}=EvaluateNet[x0[[OrderList[[k]];;OrderList[[k]]+nodeslayer[[1]]-1]],nodeslayer,A,w1,w2,w3,wstar];


wtemp4last=wtemp4;
wtemp4 = w4;
w4=wstar;


(*epsilon =A*Total[w4*x4]-y;
Do[

     x4[[j]]=x4[[j]]+ w4[[j]]^(-1)*epsilon,{j,1,nodeslayer[[4]]}];*)


If [debugflag==1,Print["*4"]];
,i=inneriterations];i=i+1];



A1[[k]]=N[x0[[OrderList[[k]]+nodeslayer[[1]]]]/(Total[w4*x4]+10^(-20))];
A=.85*A+.15*A1[[k]];
If [debugflag==1,Print["*17"]];
k=k+1];

If [debugflag==1,Print["*18"]];
mpe2= ConstantArray[0.0,Length[x0]];
mpe=0.0;
count=0;
p=0;
While[p< Length[x0]-nodeslayer[[1]],
p=p+1;
{x1,x2,x3,x4,y}=EvaluateNet[x0[[p;;p+nodeslayer[[1]]-1]],nodeslayer,A,w1,w2,w3,w4];
mpe2[[p]] = Abs[y-x0[[p+nodeslayer[[1]]]]];



If[Abs[x0[[p+nodeslayer[[1]]]]]>0,count = count+1;
mpe = mpe + (1-y/x0[[p+nodeslayer[[1]]]])^2];
];
If [debugflag==1,Print["*19"]];
Clear[temp1,temp2,sumval1,sumval2];
{sumval1,temp1}=getIntegrate2[mpe2[[1;;Length[x0]-nodeslayer[[1]]]],1,1,Length[x0]-nodeslayer[[1]]];
{sumval2,temp2}=getIntegrate2[Abs[x0[[nodeslayer[[1]]+1;;Length[x0]]]],1,1,Length[x0]-nodeslayer[[1]]];

ratio =N[sumval1/(sumval2+10^(-20))*100];
mpe =N[Sqrt[mpe/(count-1)]];


If [debugflag==1,Print["*20"]];
If[ratio≤ 2.5 ,ratio = 10*minmpe;z1=1];
If[ratio<minrmse,count2=0;z1=1;w1min=w1;w2min=w2;w3min=w3;w4min=w4; minrmse=ratio;minmpe=mpe;Amin=A];
If[ratio<20, count2 =numberpasses;z1=1];

If[debugflag2==1,Print[{n,minrmse,minmpe,ratio,mpe,count,maxranval,inneriterations}]];
z=z+1;
];
(*If [minmpe < 3, minmpe=lastmpe,A=lastAmin;w1=lastw1min;w2=lastw2min;w3=lastw3min;w4=lastw4min];*)

z1=1;
count2=count2+1;
n=n+1;

];
,
w1 = w1in;
w2=w2in;
w3=w3in;
w4=w4in;
A=Ain;


If [debugflag==1,Print["*18"]];
mpe= 0.0;
mpe2= ConstantArray[0.0,Length[x0]];
count=0;
p=0;
While[p< Length[x0]-nodeslayer[[1]],
p=p+1;
{x1,x2,x3,x4,y}=EvaluateNet[x0[[p;;p+nodeslayer[[1]]-1]],nodeslayer,A,w1,w2,w3,w4];
mpe2[[p]] = Abs[y-x0[[p+nodeslayer[[1]]]]];
If[y<10000,

If[Abs[x0[[p+nodeslayer[[1]]]]]>0,count = count+1;
mpe = mpe + (1-y/x0[[p+nodeslayer[[1]]]])^2]];
];
If [debugflag==1,Print["*19"]];
Clear[temp1,temp2,sumval1,sumval2];
{sumval1,temp1}=getIntegrate2[mpe2[[1;;Length[x0]-nodeslayer[[1]]]],1,1,Length[x0]-nodeslayer[[1]]];
{sumval2,temp2}=getIntegrate2[Abs[x0[[nodeslayer[[1]]+1;;Length[x0]]]],1,1,Length[x0]-nodeslayer[[1]]];


ratio =N[sumval1/(sumval2+10^(-20))*100];
mpe =N[Sqrt[mpe/(count-1)]];

If[ratio<minrmse&& mpe<minmpe,w1min=w1;w2min=w2;w3min=w3;w4min=w4; minmpe=mpe;minrmse=ratio;Amin=A];
If [debugflag==1,Print["*20"]];
If[debugflag2==1,Print[{n,minrmse,minmpe,ratio,mpe,count,maxranval,inneriterations}]];
];

If [debugflag==1,Print["*21"]];

z3 = x;
Clear[temp1,z2,temp2];

Do[


Clear[x1,x2,x3,x4,y,temp1,temp2];
{x1,x2,x3,x4,y}=EvaluateNet[z3[[-nodeslayer[[1]];;-1]],nodeslayer,Amin,w1min,w2min,w3min,w4min];

AppendTo[z3,N[y]];
temp1= N[(N[y]+.1)/.2*(maxval-minval)+minval];
If [deTrendflag==1,
y5= temp1+coeffs[[1]]*(Length[z3])+coeffs[[2]],
y5=temp1];
If[k==1,z2={y5},
temp2=Join[z2,{y5}];z2 = temp2]


,{k,1,futuresteps}];

{minrmse,minmpe,z2,Amin,w1min,w2min,w3min,w4min}]
EvaluateNet[x_List,nodeslayer_List,A_Real,w1_List,w2_List,w3_List,w4_List]:=Module[{i,j,y,x1,x2,x3,x4,temp1,temp2,temp3},
x1=ConstantArray[0.0,nodeslayer[[1]]];
x2 = ConstantArray[0.0,nodeslayer[[2]]];
x3=ConstantArray[0.0,nodeslayer[[3]]];
x4 =ConstantArray[0.0,nodeslayer[[4]]];
x1=x;
y = 0.0;
If[Length[x]== nodeslayer[[1]],

Do[temp1=N[Total[w1[[All,j]]*x1]];x2 [[j]]=N[Tan[temp1/Pi*4]],{j,1,nodeslayer[[2]]}];

Do[temp2=N[Total[w2[[All,j]]*x2]];x3 [[j]]=N[Tan[temp2/Pi*4.]],{j,1,nodeslayer[[3]]}];

Do[temp3=N[Total[w3[[All,j]]*x3]];x4[[j]]=N[Tan[temp3/Pi*4.]],{j,1,nodeslayer[[4]]}];

y=N[A*Total[w4*x4]]];

{x1,x2,x3,x4,y}]

SetDirectory["C:\\Users\\Chondrally\\Documents"];

optionflag=1;
debugflag2 =1;
Clear[minrmse,futurepath];

futuresteps=100;
If[optionflag==0,
Get["outoptions3.txt"];

];

data2 = ConstantArray[0,801];
data3=ConstantArray[0,801];
Clear[temp];

Do[temp = RandomReal[{-.01,.01}];data2[[i]]=N[Cos[2*Pi*30*(i-1)/1024+Pi/7]+temp];
data3[[i]]=N[Cos[2*Pi*30*(i-1)/1024+Pi/7]+.03*i+temp+50],{i,1,801}];
Clear[coeffs,deTrendedData,volatility];
{coeffs,deTrendedData,volatility}=getPercentErrorLinear[data3,debugflag];
temp4= ConstantArray[0,801];
coeffs
Do[temp4[[i]]= coeffs[[1]]*i+coeffs[[2]],{i,1,801}];
Show[ListLinePlot[data3],ListLinePlot[temp4]]
If [optionflag==1,
Clear[futureA,futurew1,futurew2,futurew3,futurew4];
{minrmse,minmpe,futurepath,futureA,futurew1,futurew2,futurew3,futurew4}=NeuralNet1[data3[[1;;701]],{37,27,17,11},7,1.005,N[10^(-3)],27,futuresteps,{},{},{},{},1.0,optionflag,1],
Clear[futureA2,futurew12,futurew22,futurew32,futurew42];

{minrmse,minmpe,futurepath,futureA2,futurew12,futurew22,futurew32,futurew42}=
NeuralNet1[data3[[1;;701]],{37,27,17,11},7,1.005,N[10^(-3)],27,futuresteps,futurew1,futurew2,futurew3,futurew4,futureA,optionflag,1]];
Print["minrmse = " , minrmse,"   minmpe = ",minmpe];

If[optionflag==1,
If[FileExistsQ["outoptions3.txt"],DeleteFile["outoptions3.txt"]];
Save["outoptions3.txt",{futureA,futurew1,futurew2,futurew3,futurew4}];


];
temp2=Join[data3[[-200;;-100]],futurepath];

ListLinePlot[temp2]
ListLinePlot[data3[[-200;;-1]]]
ListLinePlot[futurepath[[1;;100]]]

ListLinePlot[Join[{67.62618019567533`,67.83661910322249`,68.04174829905244`,68.25850713595554`,68.46882082326273`,68.66304915975873`,68.85803898298667`,69.0112712692598`,69.16370872311703`,69.25824247336256`,69.33512927217339`,69.39057036717729`,69.39817897816329`,69.37375607173125`,69.32770509648608`,69.2454009920378`,69.13414881052049`,69.00729209952658`,68.86679649725234`,68.72439734430043`,68.56331325175996`,68.41127368737648`,68.26748992279144`,68.14790877087925`,68.04374890668905`,67.96548331961125`,67.90905009639307`,67.89397919836298`,67.89922962838257`,67.94285406713229`,68.02304529059458`,68.12655348415987`,68.2680892120438`,68.43180193615754`,68.61596818223894`,68.81698868651644`,69.03098725932185`,69.24679904979459`,69.45532628058619`,69.66960065524675`,69.84488350672028`,70.02567361552157`,70.16237450751699`,70.28371873237779`,70.36374637162534`,70.40367538516566`,70.42684570951528`,70.4071816788399`,70.3539990540531`,70.27561490513709`,70.17188918505936`,70.04638031807596`,69.91987879077234`,69.76048952952665`,69.61371861187787`,69.4539556827748`,69.31355985903332`,69.19067535556577`,69.08551604897882`,69.00053084889343`,68.94597500757621`,68.91140156442809`,68.92856538166711`,68.95734011540223`,69.02872665034867`,69.13621243141588`,69.28026483380116`,69.44026093906974`,69.62084148485941`,69.82830975281257`,70.02341716187448`,70.25342393624979`,70.45643611949524`,70.65393802428656`,70.84360622988456`,71.01411220933689`,71.1764894024411`,71.29496295226654`,71.37617851367273`,71.43215198755342`,71.44686091292702`,71.44438144045512`,71.40152863013854`,71.32344367338126`,71.21169428657086`,71.10004740497334`,70.96361476958438`,70.81341792437777`,70.66410398523311`,70.51302886522396`,70.36438178274571`,70.23663147898682`,70.12458167186281`,70.01996266742961`,69.96145614057487`,69.93813766938192`,69.93652645410006`,69.97485899163595`,70.04766571262186`,70.15020606408561`,70.2820439107238`},futurepath]]

ListLinePlot[futurepath[[1;;100]]]

ClearAll[fourieranalysis];
 

fourieranalysis[x_List,futuresteps_Integer,debugflag_Integer]:= Module[{xk,maxima,maximaind,yk1,yk2,N5,M,M1,N1,N2,N3,N4,x2,x3,x4,y,y2,y1,y3,i,j,k,pi,Jcg1,Jcg2,temp,temp1,temp3,sincf,sincF,temp2,flaga,count,S,dSdA1,dSdw1,dSdtheta1,maxval1,maxval2,maxval3,dsdA0,dSdA2,dSdw2,dSdtheta2,dSdA3,dSdw3,dSdtheta3,S2,dSdA12,dSdw12,dSdtheta12,dsdA02,dSdA22,dSdw22,dSdtheta22,dSdA32,dSdw32,dSdtheta32,A1,A2,A3,w1,w2,w3,theta1,theta2,theta3,A12,A22,A32,w12,w22,w32,theta12,theta22,theta32,A13,A23,A33,w13,w23,w33,theta13,theta23,theta33,S3,dsdA03,dSdA13,dSdw13,dSdtheta13,dSdA23,dSdw23,dSdtheta23,dSdA33,dSdw33,dSdtheta33,eps,T,coeffs,deTrendedData,volatility,sigman,avg,x1,avg1,avg2,eps2},
N1 =Length[x];
Clear[coeffs,deTrendedData,volatility];
{coeffs,deTrendedData,volatility}=getPercentErrorLinear[x[[1;;N1]],debugflag];

x2=deTrendedData;

N1=Length[deTrendedData];


avg = Mean[deTrendedData];
sigman =0.0;
Do[sigman=sigman+(deTrendedData[[j]]-avg)^2,{j,1,Length[deTrendedData]}];
sigman=Sqrt[sigman/(Length[deTrendedData]-1)];
x3=ConstantArray[avg,N1];


pi=N[4.0*ArcTan[1]];
N2= 2;
While [N2≤ N1,N2=N2*2;];
yk1 = ConstantArray[0,futuresteps];
yk2 = ConstantArray[0,N2];
yk2=ForwardFFT[Join[ConstantArray[0,N2-N1],x2]];maximaind = Ordering[Abs[yk2[[1;;N2/2+1]]]][[N2/2+1-2;;N2/2+1]];
maxima = Sort[Abs[yk2[[1;;N2/2+1]]]][[N2/2+1-2;;N2/2+1]];

w1=N[pi*(maximaind[[3]]-1)/(N2/2+1)];
If[Abs[w1]==0,w1 = N[10^(-200)];];
w2 =N[ pi*(maximaind[[2]]-1)/(N2/2+1)];
If[Abs[w2]==0,w2 = N[10^(-200)];];

w3=N[pi*(maximaind[[1]]-1)/(N2/2+1)];
If[Abs[w3]==0,w3 = N[10^(-200)];];
A1=maxima[[3]]*2/N2;
If [Abs[Re[yk2[[maximaind[[3]]]]]]>0&& Abs[Im[yk2[[maximaind[[3]]]]]]>0,
theta1=ArcTan[Re[yk2[[maximaind[[3]]]]],Im[yk2[[maximaind[[3]]]]]];,theta1=N[10^(-200)];];
A2=maxima[[2]]*2/N2;
If [Abs[Re[yk2[[maximaind[[2]]]]]]>0&& Abs[Im[yk2[[maximaind[[2]]]]]]>0,
theta2=ArcTan[Re[yk2[[maximaind[[2]]]]],Im[yk2[[maximaind[[2]]]]]];,theta2 = N[10^(-200)];];
A3=maxima[[1]]*2/N2;
If [Abs[Re[yk2[[maximaind[[1]]]]]]>0&& Abs[Im[yk2[[maximaind[[1]]]]]]>0,
theta3=ArcTan[Re[yk2[[maximaind[[1]]]]],Im[yk2[[maximaind[[1]]]]]];,theta3 = N[10^(-200)];];

{maxval1,dsdA0,dSdA1,dSdw1,dSdtheta1,dSdA2,dSdw2,dSdtheta2,dSdA3,dSdw3,dSdtheta3}=getequations[x2,A1,w1,theta1,A2,w2,theta2,A3,w3,theta3];
A1=A1*maxval1;
A2=A2*maxval1;
A3=A3*maxval1;
A12=A1*0.995;w12=w1*0.995;theta12=theta1*0.995;
A22=A2*0.995;w22=w2*0.995;theta22=theta2*0.995;
A32=A3*0.995;w32=w3*0.995;theta32=theta3*.995;

{maxval2,dsdA02,dSdA12,dSdw12,dSdtheta12,dSdA22,dSdw22,dSdtheta22,dSdA32,dSdw32,dSdtheta32}=getequations[x2,A12,w12,theta12,A22,w22,theta22,A32,w32,theta32];
A12=A12*maxval2;
A22=A22*maxval2;
A32=A32*maxval2;
eps=10^(-4);
eps2=10^(-2);
count = 1;
While[(Abs[1-A12/A1]>eps|| Abs[1-w12/w1]>eps||Abs[1-theta12/theta1]>eps||Abs[1-A22/A2]>eps|| Abs[1-w22/w2]>eps||Abs[1-theta22/theta2]>eps||Abs[1-A32/A3]>eps|| Abs[1-w32/w3]>eps||Abs[1-theta32/theta3]>eps||Abs[1-maxval2/maxval1]>eps)&&count<500,
If [count ≤ 400,T =  10^((count-400)/130);,T=1;];

count = count + 1;
If[Abs[1-A12/A1]>eps&&Abs[dSdA12-dSdA1]>0,
N[A13=A12-T*dSdA12*(A12-A1)/(dSdA12-dSdA1)];,A13=A12;A12=A1;];
If[Abs[Im[A13]]>0||Abs[A13]>1500,A13=N[10^(-200)];];
If[Abs[1-A22/A2]>eps&&Abs[dSdA22-dSdA2]>0,
A23=N[A22-T*dSdA22*(A22-A2)/(dSdA22-dSdA2)];,A23=A22;A22=A1;];
If[Abs[Im[A23]]>0||Abs[A23]>1500,A23=N[10^(-200)];];
If[Abs[1-A32/A3]>eps&&Abs[dSdA32-dSdA3]>0,
A33=N[A32-T*dSdA32*(A32-A3)/(dSdA32-dSdA3)];,A33=A32;A32=A3;];
If[Abs[Im[A33]]>0||Abs[A33]>1500,A33=N[10^(-200)];];


If [Abs[1-w12/w1]>eps*eps2&&Abs[dSdw12-dSdw1]>0,
      w13 = N[w12-T*dSdw12*(w12-w1)/(dSdw12-dSdw1)];,w13=w12;w12=w1;];
If[Abs[1-w22/w2]>eps*eps2&&Abs[dSdw22-dSdw2]>0,
w23=N[w22-T*dSdw22*(w22-w2)/(dSdw22-dSdw2)];,w23=w22;w22=w2;];
If[Abs[1-w32/w3]>eps*eps2&&Abs[dSdw32-dSdw3]>0,
w33=N[w32-T*dSdw32*(w32-w3)/(dSdw32-dSdw3)];,w33=w32;w32=w3;];

If[Abs[1-theta12/theta1]>eps*eps2&&Abs[dSdtheta12-dSdtheta1]>0,
theta13 =N[ theta12-T*dSdtheta12*(theta12-theta1)/(dSdtheta12-dSdtheta1)];,theta13=theta12;theta12=theta1;];
If[Abs[1-theta22/theta2]>eps*eps2&&Abs[dSdtheta22-dSdtheta2]>0,
theta23=N[theta22-T*dSdtheta22*(theta22-theta2)/(dSdtheta22-dSdtheta2)];,theta23=theta22;theta22=theta2;];
If[Abs[1-theta32/theta3]>eps*eps2&&Abs[dSdtheta32-dSdtheta3]>0,
theta33=N[theta32-T*dSdtheta32*(theta32-theta3)/(dSdtheta32-dSdtheta3)];,theta33=theta32;theta32=theta3;];
If[Abs[1-maxval2/maxval1]>eps&&Abs[dsdA02-dsdA0]>0,
maxval3 = N[maxval2-T*dsdA02*(maxval2-maxval1)/(dsdA02-dsdA0)];,maxval3=maxval2;maxval2=maxval1;];
(*If[debugflag==1,Print[A13,w13,theta13,A23,w23,theta23,A33,w33,theta33]];*)
{maxval3,dsdA03,dSdA13,dSdw13,dSdtheta13,dSdA23,dSdw23,dSdtheta23,dSdA33,dSdw33,dSdtheta33}=getequations[x2,A13,w13,theta13,A23,w23,theta23,A33,w33,theta33];


A13=A13*maxval3;
A23=A23*maxval3;
A33=A33*maxval3;

dSdA1=dSdA12;
dSdA2=dSdA22;
dSdA3=dSdA32;
dSdw1=dSdw12;
dSdw2=dSdw22;
dSdw3=dSdw32;
dSdtheta1=dSdtheta12;
dSdtheta2 = dSdtheta22;
dSdtheta3 = dSdtheta32;
dSdA12=dSdA13;
dSdA22=dSdA23;
dSdA32=dSdA33;
dSdw12=dSdw13;
dSdw22=dSdw23;
dSdw32=dSdw33;
dSdtheta12=dSdtheta13;
dSdtheta22 = dSdtheta23;
dSdtheta32 = dSdtheta33;
A1=A12;
A2=A22;
A3=A32;
w1=w12;
w2=w22;
w3=w32;
theta1=theta12;
theta2 =theta22;
theta3 =theta32;
A12=A13;
A22=A23;
A32=A33;
w12=w13;
w22=w23;
w32=w33;
theta12=theta13;
theta22 = theta23;
theta32 = theta33;
maxval1=maxval2;
maxval2 = maxval3;
dsdA0=dsdA02;
dsdA02=dsdA03;




];
Clear[yk1];
yk1 = ConstantArray[0,futuresteps];
If[theta13<0,theta13=theta13+2*pi;];
If[theta23<0,theta23=theta23+2*pi;];
If[theta33<0,theta33=theta33+2*pi;];
Do[

yk1[[i-N1]]=A13*Sin[w13*i+theta13]+A23*Sin[w23*i+theta23]+A33*Sin[w33*i+theta33];,{i,N1+1,N1+futuresteps}];
Clear[avg1,temp1];
{avg1,temp1}= getIntegrate2[Abs[x],1,1,Length[x]];
Clear[avg2,temp1];
{avg2,temp1}=getIntegrate2[Abs[yk1],1,1,Length[yk1]];


yk1=Sign[yk1[[1]]/x[[N1]]]*yk1*N[avg1/Length[x]/(avg2/Length[yk1])];
{x,yk1}];

ClearAll[getequations];
getequations[x_List,A1_Real,w1_Real,th1_Real,A2_Real,w2_Real,th2_Real,A3_Real,w3_Real,th3_Real] := Module[{maxval,maxvalx,maxvaly,N1,i,j,y,yi,s1,c1,s2,c2,s3,c3,dsdA,dsdA1,dsdw1,dsdth1,dsdA2,dsdw2,dsdth2,dsdA3,dsdw3,dsdth3,S,temp},
N1=Length[x];


y = ConstantArray[0,N1];


dsdA1=0;
dsdw1 =0;
dsdth1 =0;
dsdA2=0;
dsdw2=0;
dsdth2=0;
dsdA3=0;
dsdw3=0;
dsdth3=0;
dsdA=0;
s1 = N[Sin[w1*i+th1]];
c1 = N[Cos[w1*i+th1]];
s2 = N[Sin[w2*i+th2]];
c2 = N[Cos[w2*i+th2]];
s3 = N[Sin[w3*i+th3]];
c3=N[Cos[w3*i+th3]];
Do[yi=N[A1*s1+A2*s2+A3*s3];
y[[i]]=yi;,{i,1,N1}];
Clear[temp,maxvaly];
{maxvaly,temp}= getIntegrate2[Abs[y],1,1,Length[y]];
Clear[temp,maxvalx];
{maxvalx,temp} = getIntegrate2[Abs[x],1,1,Length[x]];
maxval = N[maxvalx/Length[x]/(maxvaly/Length[y])];
Do[
dsdA1=dsdA1+N[(y[[i]]*maxval-x[[i]])*maxval*s1];
dsdw1=dsdw1+N[(y[[i]]*maxval-x[[i]])*A1*i*maxval*c1];
dsdth1=dsdth1+N[(y[[i]]*maxval-x[[i]])*A1*maxval*c1];
dsdA2=dsdA2+N[(y[[i]]*maxval-x[[i]])*maxval*s2];
dsdw2=dsdw2+N[(y[[i]]*maxval-x[[i]])*A2*i*maxval*c2];
dsdth2=dsdth2+N[(y[[i]]*maxval-x[[i]])*A2*maxval*c2];
dsdA3=dsdA3+N[(y[[i]]*yi*maxval-x[[i]])*maxval*s3];
dsdw3=dsdw3+N[(y[[i]]*maxval-x[[i]])*A3*i*maxval*c3];
dsdth3=dsdth3+N[(y[[i]]*maxval-x[[i]])*A3*c3*maxval];
dsdA=dsdA+N[(y[[i]]*maxval-x[[i]])*y[[i]]];
,{i,1,N1}];
If[dsdA1==0,dsdA1=10^(-200);];
If[dsdA2==0,dsdA2=10^(-200);];
If[dsdA3==0,dsdA3=10^(-200);];
If[dsdw1==0,dsdw1=10^(-200);];
If[dsdw2==0,dsdw2=10^(-200);];
If[dsdw3==0,dsdw3=10^(-200);];
If[dsdth1== 0,dsdth1=10^(-200);];
If[dsdth2== 0,dsdth2=10^(-200);];
If[dsdth3== 0,dsdth3=10^(-200);];
If[dsdA==0,dsdA=10^(-200)];





{maxval,dsdA,dsdA1,dsdw1,dsdth1,dsdA2,dsdw2,dsdth2,dsdA3,dsdw3,dsdth3}];
ClearAll[fourieranalysis];
 fourieranalysis[x_List,futuresteps_Integer,debugflag_Integer]:= Module[{xk,yk,N5,M,M1,N1,N2,N3,N4,x2,x3,x4,y,y2,y1,y3,i,j,k,pi,Jcg1,Jcg2,temp,temp1,temp3,sincf,sincF,temp2,flaga,count,theta1,theta2,maxima,maxima2,maxima3,maxima4,yk1,avg1,avg2,coeffs,deTrendedData,volatility},
N1 =Length[x];
Print["N1=",N1];
Clear[coeffs,deTrendedData,volatility];
{coeffs,deTrendedData,volatility}=getPercentErrorLinear[x[[1;;N1]],debugflag];

x2=deTrendedData;

N1=Length[deTrendedData];



N5=2;
pi=N[4.0*ArcTan[1]];
While[N5< N1+futuresteps,N5=2*N5];
M=N5-N1;

N2 = 2;
While[N2< N1,N2=N2*2;];
Print["N2=",N2];
M1 = N2 - N1;
N3=N2;
If [N2==N5,N5=N5*2];
temp = Join[ConstantArray[0,M1],x];
y =ForwardFFT[temp];

Print[M1];
xk=yk=ConstantArray[0,N5];
Print["*00"];
maxima= Max[Abs[y]];

maxima2=Reverse[Ordering[Abs[y]][[N2-5;;N2]]];
Print["maxima2=",maxima2];
maxima3 = matlabFind1[maxima2,LessEqual,N2/2+1];
maxima4 = matlabFind1[maxima2,Greater,N2/2+1];
Print[maxima2[[maxima3]]];
Print[maxima2[[maxima4]]];
Print["*1"];
Do[Do[temp1 =N[pi*( 2*maxima2[[maxima3[[i]]]]-(2*j-1))/N5];



yk[[2*j-1]]=yk[[2*j-1]]+N[Sin[temp1]/temp1*y[[maxima2[[maxima3[[i]]]]]]];,

{j,1,N2}];
Print[maxima2[[maxima3[[i]]]],",y=",y[[maxima2[[maxima3[[i]]]]]]];,{i,1,Length[maxima3]}];
Print["*1a"];
Do[
Do[temp1 = N[pi(2*maxima2[[maxima4[[i]]]]-(2*j-1))/N5];  


yk[[N5+2*j+1]]=yk[[N5+2*j+1]]+N[Sin[temp1]/temp1*y[[maxima2[[maxima4[[i]]]]]]];,{j,-1,-N2}];Print[maxima2[[maxima4[[i]]]],", y=",y[[maxima2[[maxima4[[i]]]]]]];,{i,1,Length[maxima4]}];
Print["*2"];
Do[yk[[2*i]]=y[[i]];,{i,1,N2}];

xk =Re[N[ IFFT[yk]]];
Clear[yk1];
yk1 = Join[Join[ConstantArray[1,N5/16],ConstantArray[0,14*N5/16]],ConstantArray[1,N5/16]];
xk =Re[N[IFFT[yk*yk1]]];
Clear[avg1,temp,temp1];
{avg1,temp1}=getIntegrate2[Abs[xk],1,N1+1,N1+futuresteps];
{avg2,temp}=getIntegrate2[Abs[x],1,1,N1];

xk = Sign[xk[[N1]]/x[[N1]]]*xk[[N1+1;;N1+futuresteps]]*Total[Abs[x]]/N1/(Total[Abs[xk[[N1+1;;N1+futuresteps]]]]/futuresteps);

Do[xk[[i-N1]]=coeffs[[1]]*xk[[i-N1]]*i+coeffs[[2]];,{i,N1+1,N1+futuresteps}];
xk]

ClearAll[MusicFinal];
MusicFinal[x_List,futuresteps_Integer,s0_Real,N1_Integer,flatflag_Integer,debugflag_Integer] := Module[{N1a,coeffs,deTrendedData,volatility,,x2,p,lags1,sum1,lags2,R2,R,R1,J,eigvecs,eigs,eqn1,roots2,theroots2,w,w2,Amps,theta,s,w5,i,j,count,N2,w3,w4,magphase,y,plot1,plot2,delk,m,k,magphase2,aminus,v1,v2,z1,coeffs2,temp1,aplus,G,S1,S2,indx,indx2,roots1,z,pi,y1,y3,t1,t2,t3,t4,temp,x1,X,temp2,temp0},

If[debugflag==1,Print["**1"]];
N2 =Length[x];
N1a=N1;

If [N1a>N2-1,N1a=N2-1];
If[N1a>100,N1a=100];
If[debugflag==1,Print["N2=",N2]];
If[debugflag==1,Print["x=",x];];
Clear[coeffs,deTrendedData,volatility];
If [flatflag== 0,
{coeffs,deTrendedData,volatility}=getPercentErrorLinear[x,debugflag];
,
coeffs=ConstantArray[0.0,2];
coeffs[[1]]=0;
coeffs[[2]]=Mean[x[[1;;N2]]];
deTrendedData=x-coeffs[[2]];
];

x2=deTrendedData;

N2=Length[deTrendedData];

p=3;
If[debugflag==1,Print["**1a"]];
lags1 =lags2= ConstantArray[0.0,N1a];
Do[If[i==0,sum1 =0;Do[sum1=sum1 + x2[[j]]*x2[[j]];,{j,1,N2}];lags1[[1]]= N[sum1/(N2-1)]; lags2[[1]]=N[sum1/(N2-1)];
,sum1 =0;Do[sum1=sum1 + x2[[j]]*x2[[j+i]],{j,1,N2-i}];lags1[[i+1]]=N[sum1/(N2-i-1)];sum1 =0;Do[sum1 = sum1 +x2[[j]]*x2[[j-i]];,{j,N2,i+1,-1}];
lags2[[i+1]]=N[sum1/(N2-i-1)];],
{i,0,N1a-1}];
If[debugflag==1,Print["**1a1"]];
R1=R2=R=ConstantArray[0,{N1a,N1a}];
Do[R1[[i,j]] = lags1[[Abs[i-j]+1]];R2[[i,j]]=lags2[[Abs[i-j]+1]];,{i,1,N1a},{j,1,N1a}];
J=ConstantArray[0,{N1a,N1a}];
Do[J[[i,N1a-i+1]]=1;,{i,1,N1a}];
If[debugflag==1,Print["**1a2"]];
R1=(R1+J.Transpose[R1].J)/2;
R2=(R2+J.Transpose[R2].J)/2;
R=(R1+R2)/2;
R=(R+Transpose[R])/2;
eigvecs = Eigenvectors[R];
If[debugflag==1,Print["**1b"]];
eigs = Eigenvalues[R];
m = Ordering[eigs];
eqn1=0;
Clear[s]
Clear[aminus,aplus];aminus=aplus=ConstantArray[0,{1,N1a}];
Do[aminus[[1,j]]=z^(-(j-1));aplus[[1,j]] =z^(j-1);,{j,1,N1a}];
Clear[G];
G=ConstantArray[0,{N1a,N1a}];
S1=Conjugate[Transpose[eigvecs[[All,All]]]];
S2=eigvecs[[All,All]];
G =S1.S2;

eqn1 = aminus.G.Transpose[aplus];


If[debugflag==1,Print["**1c"]];

Clear[roots2,roots1,theroots2];theroots2={};
Off[Solve::ratnz];
roots2 = z/.Solve[eqn1==0,z];theroots2 = Append[theroots2,roots2];
If[debugflag==1,Print["**1d"]];
theroots2=Flatten[Flatten[theroots2]];
indx2=matlabFind1[Abs[theroots2[[All]]],Less,1];

roots1 = theroots2[[indx2[[All]]]];
If[debugflag==1,Print["roots=",roots1]];
w = ArcTan[Re[roots1[[All]]],Im[roots1[[All]]]];
Clear[w2];w2 ={};pi=4*ArcTan[1];
Do[If[w[[i]]≥ 0 && w[[i]]< pi,w2=Append[w2,w[[i]]];],{i,1,Length[w]}];(* select low frequency spectrum *)
temp = ConstantArray[0.0,8192];
temp[[1;;N2]]= x;
X=ForwardFFT[temp];
(*Clear[temp1];
temp1 = ConstantArray[{},512-10+1];
Do[temp1[[i]]={i+9,Abs[X[[i+9]]]},{i,1,512-10+1}];
plot1 = ListLinePlot[temp1,PlotRange-> Automatic,PlotStyle-> Red,PlotLabel-> "Fourier Transform ABS",Joined-> True];*)
temp2 = Max[Abs[X[[55;;256]]]];
temp0 = matlabFind1[Abs[X[[55;;256]]],Equal,temp2];
If[Length[temp0]>0,
If[debugflag==1,Print["temp0=",temp0[[1]]+53]];
temp=N[(temp0[[1]]+53)/4096*pi];
If[debugflag==1,Print["rad ratio = ",N[4096/(temp0[[1]]+53)]]];
w2 = Append[w2,temp];
];
temp2 = Max[Abs[X[[temp0[[1]]+53+16;;300]]]];
temp0 = matlabFind1[Abs[X[[55;;300]]],Equal,temp2];
If[Length[temp0]>0,
temp = N[(temp0[[1]]+53)/4096*pi];
w2=Append[w2,temp];
];
temp2 = Max[Abs[X[[temp0[[1]]+53+16;;350]]]];
temp0=matlabFind1[Abs[X[[55;;350]]],Equal,temp2];
If[Length[temp0]>0,
temp = N[(temp0[[1]]+53)/4096*pi];
w2 = Append[w2,temp];
];
temp2 = Max[Abs[X[[temp0[[1]]+53+16;;400]]]];
temp0=matlabFind1[Abs[X[[55;;400]]],Equal,temp2];
If[Length[temp0]>0,
temp = N[(temp0[[1]]+53)/4096*pi];
w2 = Append[w2,temp];
];
temp2 = Max[Abs[X[[temp0[[1]]+53+16;;450]]]];
temp0=matlabFind1[Abs[X[[55;;450]]],Equal,temp2];
If[Length[temp0]>0,
temp = N[(temp0[[1]]+53)/4096*pi];
w2 = Append[w2,temp];
];
w3=Sort[w2];
w4={};
i=1;
While[i≤ Length[w3],
k=w3[[i]];
i=i+1;
While[i≤  Length[w3]&& w3[[i]]== k,
i=i+1;
];
w4=Append[w4,k];
];




Clear[Amps,theta,y3,delk];
If[debugflag==1,Print["w4=",w4]];

If[debugflag==1,Print["**1e"]];
delk=N[1/2/pi];
y3=ConstantArray[0,{2,N2+futuresteps}];
Amps=magphase=theta= ConstantArray[0,Length[w4]];
Do[ magphase[[i]]= magphase[[i]]+ x2[[j]]*Exp[-Sqrt[-1]*w4[[i]]*(j-1)];,{j,1,N2},{i,1,Length[w4]}];

magphase = magphase/N2;

Do[Amps[[i]]=Abs[magphase[[i]]];theta[[i]]=ArcTan[Re[magphase[[i]]],Im[magphase[[i]]]],{i,1,Length[w4]}];
If[debugflag==1,Print["**1f"]];
y = ConstantArray[0,N2+futuresteps];
Do[y[[j]]=y[[j]]+2*Amps[[i]]*Cos[w4[[i]]*(j-1)+theta[[i]]];,{j,1,N2+futuresteps},{i,1,Length[w4]}];

Do[y3[[m,i]]=y[[i]];,{i,1,N2+futuresteps},{m,1,2}];
If [debugflag==1,Print["*3"];];
Do[magphase[[i]]=0;Do[magphase[[i]]=magphase[[i]]+x2[[j]]*Exp[Sqrt[-1]*w4[[i]]*(1-delk*k)*(j-1)];,{j,1,N2}];
Amps[[i]]=Abs[magphase[[i]]];theta[[i]]=ArcTan[Re[magphase[[i]]],Im[magphase[[i]]]];
Do[y3[[Floor[N[.5*k+3/2+10^(-4)]],j]]=y3[[Floor[N[.5*k+3/2+10^(-4)]],j]]+2*Amps[[i]]*Cos[w4[[i]]*(1-delk*k)*(j-1)+theta[[i]]];,{j,N2+1,N2+futuresteps}],{i,1,Length[w4]},{k,-1,1,2}];
If[debugflag==1,Print["**1f1",y3]];

If[debugflag==1,Print["**1g"]];
Clear[t1,t2,t3,t4,temp];
y1 = ConstantArray[0.0,N2+futuresteps];
x1 = ConstantArray[0.0,N2];
temp = N[Mean[y[[1;;N2]]]];
y1 = y - temp;
x1 = x2-N[Mean[x2[[All]]]];
 v1=ConstantArray[0.0,N2+futuresteps];
Clear[coeffs2];
{plot1,coeffs2,v1}= getPercentErrorLinear3[x1,y1,debugflag];
Clear[y];
y = ConstantArray[0,{3,N2+futuresteps}];

y[[1,All]]=v1;
If[debugflag==1,Print["*1"];];
y[[2,N2;;N2+futuresteps]]=y[[1,N2;;N2+futuresteps]];
y[[3,N2;;N2+futuresteps]]=y[[1,N2;;N2+futuresteps]];
If[debugflag==1,Print["*2"];];
y[[2,N2+1;;N2+futuresteps]]=N[coeffs2*(y3[[1,N2+1;;N2+futuresteps]]-temp)+temp];
y[[3,N2+1;;N2+futuresteps]]=N[coeffs2*(y3[[2,N2+1;;N2+futuresteps]]-temp)+temp];
If[debugflag==1,Print["v1=",v1];];   
 Do[y[[k,i]]=y[[k,i]]+coeffs[[1]]*i-y[[k,N2]]+s0;,{i,N2+1,N2+futuresteps},{k,1,3}];

       

{plot1,y[[1;;3,N2+1;;N2+futuresteps]]}];

x=N[10*Sin[2*4*ArcTan[1]*100*Range[255]/255]+20+Range[255]/255*2];
{plot1,signal}=MusicFinal[x,100,N[x[[1]]],255,0,1]
signal
Flatten[signal[[1,All]]]

ClearAll[getPercentErrorLinear]  (* definition from Feb 7, 2013 
where actdata is original stock prices, dataarray is either Null matrix {{}} or temperatures SeasData *)

getPercentErrorLinear[actdata_List,debugflag_Integer]:=Module[{delta,i,j,k,a=1,b,N1,N2,R,theta,coeffs,vol6,vol7,x5,y5,L1,L,Temp,temp0,temp1,temp2,Soy,Soy2,Sxoy,Sxoy2,Sx2oy2,vol,volatility,vol2,deTrendedData},N1=0;N2=Length[actdata];L=N2-N1; L1=N1+1;
coeffs=ConstantArray[0,2];vol6=ConstantArray[0,L];vol7=0;

Temp=N[SetPrecision[actdata,60]+1000.0]; 
temp0=matlabFind1[Abs[Temp]LessEqual,10^(-60)];
If[Length[temp0]>0,Temp[[temp0]]=0.0];
temp1 = matlabFind1[Temp,Unequal,0.0];
If[debugflag==1,Print["***1a"]];
N2=L= Length[Temp];
L1 = 1;
temp2 = Temp[[temp1]];
L=Length[temp2];
Soy=Total[1/(10^(-60)+temp2[[All]])];
Soy2=Total[1/(10^(-60)+temp2[[All]]^2)];
Sxoy = Total[temp1[[All]]/(10^(-60)+temp2[[All]])];
Sxoy2=Total[temp1/(10^(-60)+temp2[[All]]^2)];
Sx2oy2=Total[temp1^2/(10^(-60)+temp2[[All]]^2)];
If[debugflag==1,Print["***1b"]];
N2=Length[temp1];
If[debugflag==1,Print["Sxoy2=",Sxoy2];Print["Soy=",Soy,", Sxoy=",Sxoy,", Soy2=",Soy2];Print["Sxoy2 =",Sxoy2,", Sx2oy2 =",Sx2oy2,", Soy2 =",Soy2];];
coeffs[[1]]=N[(Sxoy2*Soy-Sxoy*Soy2)/(10^(-60)+Sxoy2^2-Sx2oy2*Soy2)];
If[debugflag==1,Print["***1ba"]];
coeffs[[2]]=N[(Soy-coeffs[[1]]*Sxoy2)/(10^(-60)+Soy2)];
If[debugflag==1,Print["***1c"]];
L= Length[Temp];
vol=ConstantArray[0,L];
deTrendedData=ConstantArray[0,L];
vol7=0;
Do[

deTrendedData[[j]]= temp2[[j]]-coeffs[[1]]*temp1[[j]]-coeffs[[2]];
vol[[j]]=(deTrendedData[[j]])^2;
vol7=vol7+vol[[j]],{j,1,L}];
If[debugflag==1,Print["***1d"]];

coeffs[[2]]=coeffs[[2]]-1000.0;
{coeffs,deTrendedData,vol7}];


ClearAll[getPercentErrorLinear2]  (* definition from Feb 7, 2013 
where actdata is original stock prices, dataarray is either Null matrix {{}} or temperatures SeasData *)

getPercentErrorLinear2[x_List,y_List,debugflag_Integer]:=Module[{z,vol1,delta,futuresteps,f1,f2,f3,i,j,k,a,b,N1,N2,R,theta,coeffs,vol6,vol7,x5,y5,L1,L,a2,a1,Temp,temp0,temp1,temp2,Soy,Soy2,Sxoy,Sxoy2,Sx2oy2,vol,volatility,vol2,deTrendedData,MostPurseAir,coeffs3,xvals,vol9,m,plot1,plot2},N1=0;N2=Length[x];L=N2; 
futuresteps = Length[y]-N2;
coeffs=ConstantArray[0,3];
vol1 =ConstantArray[0,3];
a=ConstantArray[0,3];
a[[1]]= 1;
a[[2]]=.95;
z= ConstantArray[0.0,{3,N2}];

Do[
Do[z[[k,i]]= N[a[[k]]*y[[i]]-x[[i]]+1000.0];,{i,1,N2}];
Temp = z;
Temp=SetPrecision[Temp,60]; 
temp0=matlabFind1[Abs[Temp[[k,All]]],LessEqual,10^(-60)];
If[Length[temp0]>0,Temp[[k,temp0]]=0.0];
temp1 = matlabFind1[Temp[[k,All]],Unequal,0.0];
If[debugflag==1,Print["***1a"]];
temp2 = Temp[[k,temp1]];
L = Length[temp2];
Soy=Total[1/(10^(-60)+temp2)];
Soy2=Total[1/(10^(-60)+temp2^2)];
Sxoy = Total[temp1/(10^(-60)+temp2)];
Sxoy2=Total[temp1/(10^(-60)+temp2^2)];
Sx2oy2=Total[temp1^2/(10^(-60)+temp2^2)];
If[debugflag==1,Print["***1b"]];
N2=Length[temp1];
If[debugflag==1,Print["Sxoy2=",Sxoy2];Print["Soy=",Soy,", Sxoy=",Sxoy,", Soy2=",Soy2];Print["Sxoy2 =",Sxoy2,", Sx2oy2 =",Sx2oy2,", Soy2 =",Soy2];];
coeffs[[1]]=N[(Sxoy2*Soy-Sxoy*Soy2)/(10^(-60)+Sxoy2^2-Sx2oy2*Soy2)];
If[debugflag==1,Print["***1ba"]];
coeffs[[2]]=N[(Soy-coeffs[[1]]*Sxoy2)/(10^(-60)+Soy2)];
If[debugflag==1,Print["***1c"]];
L= Length[Temp];
vol=ConstantArray[0,L];
deTrendedData=ConstantArray[0,L];
vol7=0;
Do[

deTrendedData[[j]]= N[temp2[[j]]-coeffs[[1]]*temp1[[j]]-coeffs[[2]]];
vol[[j]]=deTrendedData[[j]];
,{j,1,L}];
vol1[[k]]=Sum[vol[[i]],{i,1,L}];

,{k,1,2}];

f1 = vol1[[1]];
f2 = vol1[[2]];
a[[3]] =N[a[[2]]-(a[[2]]-a[[1]])/(f2-f1+10^(-200))*f2];
If[a[[3]]≤ 0.2|| a[[3]]≥ 3, a[[3]]=.2+2.8*RandomReal[];];
k=3;
m=3;
a[[1]]=a[[2]];
a[[2]]=a[[3]];

While [Abs[1-a[[2]]/a[[1]]]>10^(-3)&&m<1000,

Do[z[[3,i]]= N[a[[3]]*y[[i]]-x[[i]]+1000.0];,{i,1,N2}];
Temp = z;
Temp=SetPrecision[z,60]; 
temp0=matlabFind1[Abs[Temp[[3,All]]],LessEqual,10^(-60)];
If[Length[temp0]>0,Temp[[3,temp0]]=0.0];
temp1 = matlabFind1[Temp[[3,All]],Unequal,0.0];
If[debugflag==1,Print["***1a"]];
temp2 = Temp[[3,temp1]];
L = Length[temp2];
Soy=Total[1/(10^(-60)+temp2)];
Soy2=Total[1/(10^(-60)+temp2^2)];
Sxoy = Total[temp1/(10^(-60)+temp2)];
Sxoy2=Total[temp1/(10^(-60)+temp2^2)];
Sx2oy2=Total[temp1^2/(10^(-60)+temp2^2)];
If[debugflag==1,Print["***1b"]];
N2=Length[temp1];
If[debugflag==1,Print["Sxoy2=",Sxoy2];Print["Soy=",Soy,", Sxoy=",Sxoy,", Soy2=",Soy2];Print["Sxoy2 =",Sxoy2,", Sx2oy2 =",Sx2oy2,", Soy2 =",Soy2];];
coeffs[[1]]=N[(Sxoy2*Soy-Sxoy*Soy2)/(10^(-60)+Sxoy2^2-Sx2oy2*Soy2)];
If[debugflag==1,Print["***1ba"]];
coeffs[[2]]=N[(Soy-coeffs[[1]]*Sxoy2)/(10^(-60)+Soy2)];
If[debugflag==1,Print["***1c"]];
L= Length[Temp];
vol=ConstantArray[0,L];
deTrendedData=ConstantArray[0,L];
vol7=0;
If[debugflag==1,Print["coeffs=",coeffs];];
If[debugflag==1,Print["a[[All]]=",a[[All]]];];
Do[

deTrendedData[[j]]=N[ temp2[[j]]-coeffs[[1]]*temp1[[j]]-coeffs[[2]]];
vol[[j]]=deTrendedData[[j]];
,{j,1,L}];
vol1[[k]]=Sum[vol[[i]],{i,1,L}];
a[[1]]=a[[2]];
a[[2]]=a[[3]];
f1=f2;
f2=vol1[[k]];
If[debugflag==1,Print["vol1=",vol1];];
coeffs[[3]]=a[[3]];
If[Abs[1-a[[2]]/a[[1]]]>10^(-3),
a[[3]] =N[a[[2]]-(a[[2]]-a[[1]])/(f2-f1+10^(-200))*f2];
If[a[[3]]≤0.2|| a[[3]]≥ 3,a[[3]]=.2+2.8*RandomReal[];];
];
m=m+1;


];

 coeffs[[3]]=a[[3]];
Clear[MostPurseAir];
MostPurseAir=ConstantArray[0,N2+futuresteps];
Do[MostPurseAir[[i]]=a[[3]]*y[[i]],{i,1,N2+futuresteps}];
If[debugflag==1,Print["MostPurseAir=",MostPurseAir];Print["x1=",x-Mean[x]];];
Clear[temp1];
temp1=StringJoin["MostPurseAir vs. x,  a[[3]]=",a[[3]],", vol1=",vol1[[k]]];

plot1=ListLinePlot[{MostPurseAir[[1;;N2]],x},PlotRange-> Automatic,PlotLabel-> temp1,PlotStyle-> {Red,Black},GridLines-> Automatic,Joined-> True];





{plot1,coeffs,MostPurseAir,vol1[[k]]}];

ClearAll[getPercentErrorLinear3]  (* definition from Feb 7, 2013 
where actdata is original stock prices, dataarray is either Null matrix {{}} or temperatures SeasData *)

getPercentErrorLinear3[x_List,y_List,debugflag_Integer]:=Module[{z,vol1,delta,futuresteps,f1,f2,f3,i,j,k,a,b,N1,N2,R,theta,coeffs,vol6,vol7,x5,y5,L1,L,a2,a1,Temp,temp0,Soy,Soy2,Sxoy,Sxoy2,Sx2oy2,vol,volatility,vol2,deTrendedData,x1,y1,MostPurseAir,coeffs3,xvals,vol9,m,plot1,plot2,t1,t2,t3,t4,t5,t1a,t2a,t3a,t4a,temp1,temp2,temp3,temp4,temp5,temp1a,temp2a,temp3a,temp4a,t0,t0a,temp0a},N1=0;N2=Length[x];L=N2; 
futuresteps = Length[y]-N2;
coeffs=ConstantArray[0,3];
vol1 =ConstantArray[0,3];
a=ConstantArray[0,3];
a[[1]]= 1;
a[[2]]=.95;

k=3;
x1= x-Mean[x];
y1 = y - Mean[y[[1;;N2]]];
t0 = Max[x1[[1;;Floor[N2/5]]]];
t0a=Min[x1[[1;;Floor[N2/5]]]];
t1=Max[x1[[Floor[N2/5]+1;;Floor[2*N2/5]]]];
t1a=Min[x1[[Floor[N2/5]+1;;Floor[2*N2/5]]]];
t2=Max[x1[[Floor[2*N2/5]+1;;Floor[3*N2/5]]]];
t2a=Min[x1[[Floor[2*N2/5]+1;;Floor[3*N2/5]]]];
t3=Max[x1[[Floor[3*N2/5]+1;;Floor[4*N2/5]]]];
t3a=Min[x1[[Floor[3*N2/5]+1;;Floor[4*N2/5]]]];
t4=Max[x1[[Floor[4*N2/5]+1;;N2]]];
t4a=Min[x1[[Floor[4*N2/5]+1;;N2]]];
t5 = Abs[x1[[N2]]];
(*temp1=matlabFind1[Abs[x[[Floor[N2/5];;Floor[2*N2/5]]]],Equal,t1];
temp2 = matlabFind1[Abs[x[[Floor[2*N2/5]+1;;Floor[3*N2/5]]]],Equal,t2];
temp3 =matlabFind1[Abs[x[[Floor[3*N2/5]+1;;Floor[4*N2/5]]]],Equal,t3];
temp4=matlabFind1[Abs[x[[Floor[4*N2/5]+1;;N2]]],Equal,t4];
temp5=N2;*)
temp0 =Max[y1[[1;;Floor[N2/5]]]];
temp0a=Min[y1[[1;;Floor[N2/5]]]];
temp1 =Max[y1[[Floor[N2/5]+1;;Floor[2*N2/5]]]];
temp1a=Min[y1[[Floor[N2/5]+1;;Floor[2*N2/5]]]];
temp2=Max[y1[[Floor[2*N2/5]+1;;Floor[3*N2/5]]]];
temp2a=Min[y1[[Floor[2*N2/5]+1;;Floor[3*N2/5]]]];
temp3=Max[y1[[Floor[3*N2/5]+1;;Floor[4*N2/5]]]];
temp3a=Min[y1[[Floor[3*N2/5]+1;;Floor[4*N2/5]]]];
temp4=Max[y1[[Floor[4*N2/5]+1;;N2]]];
temp4a=Min[y1[[Floor[4*N2/5]+1;;N2]]];

temp5=Abs[y1[[N2]]];
a[[k]]=  N[((t0-t0a)/(temp0-temp0a)+(t1-t1a)/(temp1-temp1a)+(t2-t2a)/(temp2-temp2a)+2*(t3-t3a)/(temp3-temp3a)+2*(t4-t4a)/(temp4-temp4a))/7];


 
Clear[MostPurseAir];
MostPurseAir=ConstantArray[0,N2+futuresteps];
Do[MostPurseAir[[i]]=a[[3]]*y1[[i]]+Mean[y[[1;;N2]]];,{i,1,N2+futuresteps}];
If[debugflag==1,Print["MostPurseAir=",MostPurseAir];Print["x1=",x-Mean[x]];];
Clear[temp1];
temp1=StringJoin["MostPurseAir vs. x, a[[3]]=",ToString[N[a[[3]]]]];

plot1=ListLinePlot[{MostPurseAir[[1;;N2]],x1},PlotRange-> Automatic,PlotLabel-> temp1,PlotStyle-> {Red,Black},GridLines-> Automatic,Joined-> True];





{plot1,a[[3]],MostPurseAir}];

x=ConstantArray[0.0,701];
Do[x[[i]]=Sin[2*Pi*30*(i-1)/1024]+RandomReal[{-.001,.001}]+10.2,{i,1,701}];
{coeffs,deTrendedData,volatility}=GetPercentErrorex[x];
coeffs
ListLinePlot[deTrendedData]

FFT

ClearAll[ForwardFFT];
ForwardFFT[x_List] := Module[{N1,odd,t1,t2,even,W,X,k,t},
N1 = Length[x];

X = ConstantArray[0.0,N1];
If [N1>1,
odd = ConstantArray[0.0,N1/2];
even = ConstantArray[0.0,N1/2];

odd = x[[2;;N1;;2]];
even = x[[1;;N1;;2]];
t1= ForwardFFT[odd];

t2=ForwardFFT[even];
X =Join[t2,t1];

Do[W=Exp[-Sqrt[-1]*N[2*Pi*(k-1)/N1]];t=X[[k]];X[[k]]=t+W*X[[k+N1/2]];X[[k+N1/2]]=t-W*X[[k+N1/2]],{k,1,N1/2}]
,
X = {x[[1]]}];
X]

temp = {1,1,1,1,0,0,0,0};
y = ForwardFFT[temp]

{4.` +0.` I,1.` -2.414213562373095` I,0.` +0.` I,1.` -0.4142135623730949` I,0.` +0.` I,0.9999999999999999` +0.4142135623730949` I,0.` +0.` I,0.9999999999999997` +2.414213562373095` I}

IFFT

ClearAll[IFFT];
IFFT[y_List] := Module[{N1,x2},
N1 = Length[y];
x2 = Conjugate[ForwardFFT[Conjugate[y]/N1]];
x2]

x = {1,1,1,1,0,0,0,0};
y = ForwardFFT[x];
x2 = IFFT[y]

x=ConstantArray[0.0,1024];
Do[x[[i]] = N[Sin[2*Pi*30*(i-1)/1024+5*Pi/6]+.2+1.4*Sin[2*Pi*50*(i-1)/1024+3*Pi/4]],{i,1,701}];
ListLinePlot[x]
y = ForwardFFT[x];
ListLinePlot[Abs[y],PlotRange-> {0,1024}]
x2 = IFFT[y];
ListLinePlot[Re[x2]]
data2 = ConstantArray[0.0,700];
Do[ data2[[j]] =x[[j]],{j,1,700}];
N1 = Floor[Log[Length[data2]+.5]/Log[2.0]]+1
temp3 =Join[data2,ConstantArray[0.0,2^N1-Length[data2]]];
y=ForwardFFT[temp3]/2^N1;
futuresteps = 40;
futurearma=ConstantArray[0.0,futuresteps+1];(* Sinusoidal path *)
i=0;While[i≤ futuresteps,j=1;While[j≤ 2^(N1),futurearma[[i+1]]=futurearma[[i+1]]+y[[j]]*Exp[Sqrt[-1]*2*Pi*(i*(j-1)+700)/2^N1];j=j+1]; futurearma[[i+1]]=Re[futurearma[[i+1]]];i=i+1];
futurepath = futurearma[[2;;futuresteps+1]];
ListLinePlot[futurepath]

x[[701]]
data2[[700]]
futurepath[[1]]
futurepath[[2]]

getRT

ClearAll[getRT];
getRT[PriceData_List,VolData_List,debugflag_Integer]:=Module[{PercPrice,PercVol,RTPercPrice,RTPercVol,IntPercPriceRT,IntPercVolRT,IntRT,RT,i,j,,temp,N1,MarketAccumulation,MarketIncrease,MarketDecline,Accumulation,temp1,temp2,temp3,temp4,N2,N0,MinAccumulation,MinPercPriceRT,MinPercVolRT},
N2=Length[PriceData];
Clear[temp1,temp2,temp3,temp4];
temp2 = matlabFind1[VolData,GreaterEqual,0.0];
temp3 = matlabFind1[PriceData,Greater,0.0];
temp1 = Intersection[temp2,temp3];




N1=Length[temp1];
If[N1>0,

MarketIncrease = MarketDecline=MarketAccumulation=ConstantArray[0.0,N1-1];

PercPrice = ConstantArray[0.0,N1-1];
PercVol = ConstantArray[0.0,N1-1];
RTPercPrice = ConstantArray[0.0,N1-1];
RTPercVol = ConstantArray[0.0,N1-1];
RT = ConstantArray[0.0,N1-1];
If [debugflag==1,Print["**1"]];

Do[PercPrice[[i]]=N[PriceData[[temp1[[i+1]]]]/(10^(-100)+PriceData[[temp1[[i]]]])];RTPercPrice[[i]]=N[(PercPrice[[i]]-1.0)*100];

PercVol[[i]]=N[VolData[[temp1[[i+1]]]]/(10^(-100)+VolData[[temp1[[i]]]])];RTPercVol[[i]]=N[(PercVol[[i]]-1.0)*100];,{i,1,N1-1}];

If [debugflag==1,Print["**1a"]];
Do[If[PercPrice[[i]]>1&&PercVol[[i]]>1,MarketIncrease[[i]]=Sqrt[PercPrice[[i]]*PercVol[[i]]]];
If[PercPrice[[i]]<1&&PercVol[[i]]<1,MarketDecline[[i]]=Sqrt[1/PercPrice[[i]]*1/(10^(-100)+PercVol[[i]])]];
If[PercPrice[[i]]>1&&PercVol[[i]]<1,MarketIncrease[[i]]=Sqrt[PercPrice[[i]]*1/(10^(-100)+PercVol[[i]])]];
If[PercPrice[[i]]<1&&PercVol[[i]]>1,MarketDecline[[i]]=Sqrt[1/PercPrice[[i]]*PercVol[[i]]]];
MarketAccumulation[[i]]=N[(MarketIncrease[[i]]-1)*100-(MarketDecline[[i]]-1)*100],{i,1,N1-1}];
If [debugflag==1,Print["**1b"]];
(*EMARTPercPrice = ConstantArray[0,N-1];-
EMARTPercPrice[[3]]=Total[RTPercPrice[[1;;3]]]/3;
Do[EMARTPercPrice[[i+1]] = (RTPercPrice[[i+1]]-EMARTPercPrice[[i]])*.5+EMARTPercPrice[[i]],{i,3,N-2}];*)

(*EMARTPercVol=ConstantArray[0,N-1];
EMARTPercVol[[3]]=Total[RTPercVol[[1;;3]]]/3;
Do[EMARTPercVol[[i+1]] = (RTPercVol[[i+1]]-EMARTPercVol[[i]])*.5+EMARTPercVol[[i]],{i,3,N-2}];*)
RT = N[(RTPercPrice/Max[Abs[RTPercPrice]]+RTPercVol/(10^(-100)+Max[Abs[RTPercVol]]))/2*100.0];
If [debugflag==1,Print["**1c"]];
(*{temp2,IntPercPriceRT}=getIntegrate2[EMARTPercPrice[[3;;N-1]]-1,1,1,N-3];
{temp2,IntPercVolRT}=getIntegrate2[EMARTPercVol[[3;;N-1]]-1,1,1,N-3];
{temp2,IntRT} = getIntegrate2[RT[[3;;N-1]]-1,1,1,N-3];*)
Clear[temp2];
temp2 =0.0;
IntPercPriceRT=Accumulation=IntPercVolRT=IntRT=ConstantArray[0.0,N1-1];
MinPercPriceRT = Min[RTPercPrice];
{temp2,IntPercPriceRT}=getIntegrate2[RTPercPrice,1,1,N1-1];
IntPercPriceRT = IntPercPriceRT - IntPercPriceRT[[1]];
RTPercPrice = RTPercPrice-MinPercPriceRT+100;

{temp2,Accumulation}=getIntegrate2[MarketAccumulation,1,1,N1-1];
Accumulation = Accumulation - Accumulation[[1]];
MinAccumulation = Min[Accumulation];
Accumulation = Accumulation - Min[Accumulation]+100;
MinPercVolRT = Min[RTPercVol];
{temp2,IntPercVolRT}=getIntegrate2[RTPercVol,1,1,N1-1];

RTPercVol=RTPercVol-MinPercVolRT+100;
IntPercVolRT = IntPercVolRT - IntPercVolRT[[1]];
{temp2,IntRT} = getIntegrate2[RT,1,1,N1-1];
IntRT=IntRT-IntRT[[1]];
If [debugflag==1,Print["**1d"]];,

MarketIncrease = MarketDecline=MarketAccumulation=ConstantArray[0.0,N1-1];

PercPrice = ConstantArray[0.0,N1-1];
PercVol = ConstantArray[0.0,N1-1];
RTPercPrice = ConstantArray[0.0,N1-1];
RTPercVol = ConstantArray[0.0,N1-1];
IntPercPriceRT=IntPercVolRT=IntRT=Accumulation=RT = ConstantArray[0.0,N1-1];];
{RT,RTPercPrice,RTPercVol,IntPercPriceRT,IntPercVolRT,IntRT,Accumulation,MarketAccumulation,MinAccumulation,MinPercPriceRT,MinPercVolRT}]

getVolumeEMA

ClearAll[getVolumeEMA];
getVolumeEMA[VolData_List,N2_Integer,N3_Integer,N4_Integer]:=Module[{N,i,j,EMA2,EMA3,EMA9},
N=Length[VolData];
EMA2 = ConstantArray[0.0,N];
EMA3 = ConstantArray[0.0,N];
EMA9=ConstantArray[0.0,N];
EMA2[[N2]]=Total[VolData[[1;;N2]]]/N2;
EMA3[[N3]]=Total[VolData[[1;;N3]]]/N3;
EMA9[[N4]]=Total[VolData[[1;;N4]]]/N4;
Do[EMA2[[i+N2]]=(VolData[[i+N2]]-EMA2[[i+N2-1]])*2.0/(N2+1)+EMA2[[i+N2-1]],{i,1,N-N2}];
Do[EMA3[[i+N3]]=(VolData[[i+N3]]-EMA3[[i+N3-1]])*2.0/(N3+1)+EMA3[[i+N3-1]],{i,1,N-N3}];
Do[EMA9[[i+N4]]=(VolData[[i+N4]]-EMA9[[i+N4-1]])*2.0/(N4+1)+EMA9[[i+N4-1]],{i,1,N-N4}];
{EMA2,EMA3,EMA9}]

getMomentum

ClearAll[getMomentum];
getMomentum[PriceData_List,N2_Integer]:=Module[{N,i,j,Momentum},
N=Length[PriceData];
Momentum = ConstantArray[0.0,N];
Do[Momentum[[i+N2-1]]=PriceData[[i+N2-1]]-PriceData[[i]],{i,1,N-N2+1}];
Momentum]

getStochastics

ClearAll[getStochastics];
getStochastics[PriceData_List,N2_Integer]:=Module[{i,j,N,PercK,percD,percDslow,H5,L5},
N=Length[PriceData];
H5=ConstantArray[0.0,N];
L5=ConstantArray[0.0,N];
PercK = ConstantArray[0.0,N];
percD = ConstantArray[0.0,N];
percDslow =  ConstantArray[0.0,N];
H5[[N2]]= Max[PriceData[[1;;N2]]];
L5[[N2]]=Min[PriceData[[1;;N2]]];
Do[H5[[N2+i]]=Max[PriceData[[i+1;;i+N2]]];L5[[N2+i]]=Min[PriceData[[i+1;;i+N2]]],{i,1,N-N2}];
Do[PercK[[i]]=100.0*(PriceData[[i]]-L5[[i]])/(H5[[i]]-L5[[i]]+10^(-20)),{i,N2,N}];
percD[[3+N2]]=Total[PercK[[N2;;N2+2]]]/3;
Do[percD[[i+N2+3]]=(PercK[[i+N2+3]]-percD[[i+N2+2]])/2.0+percD[[i+N2+2]],{i,1,N-N2-3}];
percDslow[[6+N2]]=Total[percD[[N2+3;;N2+5]]]/3;
Do[percDslow[[i+N2+6]]=(percD[[i+N2+6]]-percDslow[[i+N2+5]])/2.0+percDslow[[i+N2+5]],{i,1,N-N2-6}];
{PercK,percD,percDslow}]

getSigma

ClearAll[getSigma];
getSigma[PriceData_List,DaysTillExpiry_Integer]:=Module[{N3,pricedata,temp,i,j,N1,sigma,,sumval,mean},
temp= matlabFind1[PriceData,Greater,0.0];
pricedata = PriceData[[temp]];
N1=Length[pricedata];
N3 = DaysTillExpiry;
If[N3>N1,N3=N1];
sumval = 0.0;
Do[sumval = sumval + Log[pricedata[[i+1]]/pricedata[[i]]],{i,-N3,-2}];
mean = sumval/N3;
sumval = 0.0;
Do[sumval = sumval + (Log[pricedata[[i+1]]/pricedata[[i]]]-mean)^2,{i,-N3,-2}];
sigma = N[Sqrt[sumval/(N3-1)]/Sqrt[1/365]];
sigma]

getDelta

ClearAll[getDelta];
getDelta[InterestRate_Real,DaysTillExpiry_Integer,Strike_Real,S_Real,sigma_Real]:= Module[{temp,d1,r,DeltaCall,DeltaPut,f,x,Tau},
r = InterestRate;
Tau =N[ DaysTillExpiry/365];


f[x_]:=  1/2*(1+Erf[x/Sqrt[2.0]]);
If[Tau >0.0,
d1 =N[ 1/sigma/Sqrt[Tau]*(Log[S/Strike]+(r+sigma^2/2)*Tau)],
d1 = 100000.0];


DeltaCall =N[ f[d1]];
DeltaPut =N[DeltaCall-1.0];

{DeltaCall,DeltaPut}]

{deltacall,deltaput} = getDelta[0.02,0,67.0,87.0,.345]

temp=N[10^(-40)]
{deltacall,deltaput} = getDelta[0.02,N[10^(-40)],67.0,80.0,.345]

getBSGreeks

ClearAll[getBSGreeks];
getBSGreeks[PriceData_List,DaysTillExpiry_Integer,InterestRate_Real,Strike_Real,debugflag_Integer]:=Module[{N3,pricedata,temp,temp1,i,j,N1,Nd1,Nd2,S,d1,r,d2,sigma,callBS,putBS,Nnegd1,Nnegd2,DeltaCall,DeltaPut,Gamma2,Vega,ThetaCall,ThetaPut,RhoCall,RhoPut,f,x,df,sumval,mean,Tau},
temp= matlabFind1[PriceData,Greater,0.0];
pricedata = PriceData[[temp]];
N1=Length[pricedata];
r = InterestRate;
Tau = DaysTillExpiry/365;
N3 = DaysTillExpiry;
If[DaysTillExpiry<3,N3=3];

If[N3>N1,N3=N1];
S = pricedata[[-1]];
sumval = 0.0;
Do[sumval = sumval + Log[pricedata[[i+1]]/pricedata[[i]]],{i,-N3,-2}];
mean = sumval/(N3-1);
sumval = 0.0;
Do[sumval = sumval + (Log[pricedata[[i+1]]/pricedata[[i]]]-mean)^2,{i,-N3,-2}];
sigma = N[Sqrt[sumval/(N3-2)]/Sqrt[1/365]];


f[x_]:=  1/2*(1+Erf[x/Sqrt[2.0]]);
df[x_]:= f'[x];
If [debugflag==1,Print["Strike=",Strike];Print["S=",S];];
If[Tau>0.0,
d1 =N[ 1/sigma/Sqrt[Tau]*(Log[S/Strike]+(r+sigma^2/2)*Tau)];
d2 = N[1/sigma/Sqrt[Tau]*(Log[S/Strike]+(r-sigma^2/2)*Tau)],
d1 = 100000.0;d2=100000.0];


callBS = N[f[d1]*S-f[d2]*Strike*Exp[-r*Tau]];
putBS = N[Strike*Exp[-r*Tau]-S+callBS];
DeltaCall =N[ f[d1]];
DeltaPut =N[DeltaCall-1.0];

Gamma2= N[df[d1]/S/sigma/(10^(-100)+Sqrt[Tau])];
Vega= N[df[d1]*S*Sqrt[Tau]];
ThetaCall =N[ -S*df[d1]*sigma/2/Sqrt[Tau]-r*Strike*Exp[-r*Tau]*f[d2]];
ThetaPut = N[-S*df[d1]*sigma/2/Sqrt[Tau]+r*Strike*Exp[-r*Tau]*f[-d2]];
RhoCall = N[Strike*Tau*Exp[-r*Tau]*f[d2]];
RhoPut =  N[-Strike*Tau*Exp[-r*Tau]*f[-d2]];
sigma=sigma*Sqrt[1/365];
{callBS,putBS,sigma,DeltaCall,DeltaPut,Gamma2,Vega,ThetaCall,ThetaPut,RhoCall,RhoPut}]

callc = ConstantArray[0,4];
putc = ConstantArray[0,4];
calle=ConstantArray[0,4];
pute=ConstantArray[0,4];
strikes=ConstantArray[0,4];
strikes[[1]]=23;
strikes[[2]]=25;
OptionCounts=ConstantArray[0,4];
OptionCounts[[1]]=-2;
OptionCounts[[2]]=1;
busdays = ConstantArray[0,4];
busdays[[1]]=14;
busdays[[2]]=14;
{price,volume}=googlePrices["GOOG","05/05/16","05/26/16",1,1];
futurepath=Transpose[price][[2]];
Clear[temp6];
debugflag=0;
InterestRate=.02
{price,volume}=googlePrices["GOOG","05/05/15","05/04/16","Close",1,1];
YrData2=Transpose[price][[2]];
Clear[sigma,DeltaCall,DeltaPut,Gamma2,Vega,ThetaCall,ThetaPut,RhoCall,RhoPut];
Do[Clear[temp6,temp7];

callBS=0;putBS=0;
temp7=N[strikes[[i]]];
If[busdays[[i]]>0,temp6=Join[YrData2,futurepath[[1;;busdays[[i]]]]];
If[Abs[OptionCounts[[i]]]>0,{callBS,putBS,sigma,DeltaCall,DeltaPut,Gamma2,Vega,ThetaCall,ThetaPut,RhoCall,RhoPut}=getBSGreeks[temp6,1,interestRate,temp7,debugflag]]];callc[[i]]=callBS;putc[[i]]=putBS;,{i,1,4}];

getBollinger

ClearAll[getBollinger];
getBollinger[PriceData_List,N2_Integer,K_Real]:=Module[{N,i,j,BandWidth,sumval,Percb,Upper,Lower,StdDev,EMAN2},
N=Length[PriceData];
BandWidth =ConstantArray[0.0,N];
Percb = ConstantArray[0.0,N];
StdDev=ConstantArray[0.0,N];
Upper =  ConstantArray[0.0,N];
Lower =  ConstantArray[0.0,N];
EMAN2= ConstantArray[0.0,N];
EMAN2[[N2]]=Total[PriceData[[1;;N2]]]/N2;
Do[EMAN2[[N2+i]]=(PriceData[[N2+i]]-EMAN2[[N2+i-1]])*2/(N2+1.0)+EMAN2[[N2+i-1]],{i,1,N-N2}];
Do[sumval=0.0;Do[sumval = sumval + (PriceData[[i]]-EMAN2[[i]])^2,{i,j-N2+1,j}];StdDev[[j]]=Sqrt[sumval/(N2-1.0)],{j,N2,N}];
Do[Upper[[i]]=EMAN2[[i]]+K*StdDev[[i]];Lower[[i]]=EMAN2[[i]]-K*StdDev[[i]];BandWidth[[i]]=Upper[[i]]-Lower[[i]];Percb[[i]]=(PriceData[[i]]-Lower[[i]])/BandWidth[[i]]*100.0,{i,N2,N}];
{EMAN2,Upper,Lower,Percb,BandWidth}]

getDPO

ClearAll[getDPO];
getDPO[PriceData_List,N2_Integer]:=Module[{N,N3,i,j,SMA20,DPOResult},
N=Length[PriceData];
N3=Floor[N2/2.0+1.5];
SMA20 = ConstantArray[0.0,N];
DPOResult = ConstantArray[0.0,N];
Do[SMA20[[N2+i-1]]=Total[PriceData[[i;;N2+i-1]]]/N2,{i,1,N-N2+1}];
Do[DPOResult[[i]]=PriceData[[i]]-SMA20[[i+N3]],{i,1,N-N3}];
DPOResult]

getMACD

ClearAll[getMACD];
getMACD[PriceData_List,N2_Integer,N3_Integer,N4_Integer]:=Module[{N,i,j,EMA26,EMA12,EMA9,MACD,BuySignal},
N=Length[PriceData];
MACD = ConstantArray[0.0,N];
BuySignal = ConstantArray[0.0,N];
EMA26=ConstantArray[0.0,N];
EMA12=ConstantArray[0.0,N];
EMA9=ConstantArray[0.0,N];
EMA26[[N2]] = Total[PriceData[[1;;N2]]]/N2;
EMA12[[N2]]=Total[PriceData[[1;;N3]]]/N3;
Do[EMA26[[N2+i]]=(PriceData[[N2+i]]-EMA26[[N2+i-1]])*2.0/(N2+1)+EMA26[[N2+i-1]],{i,1,N-N2}];
Do[EMA12[[N3+i]]=(PriceData[[N3+i]]-EMA12[[N3+i-1]])*2.0/(N3+1)+EMA12[[N3+i-1]],{i,1,N-N3}];
MACD = EMA12-EMA26;
EMA9[[N4]]=Total[MACD[[1;;N4]]]/N4;
Do[EMA9[[N4+i]]=(MACD[[N4+i]]-EMA9[[N4+i-1]])*2.0/(N4+1)+EMA9[[N4+i-1]],{i,1,N-N4}];
BuySignal = EMA9-MACD;
BuySignal];

getRSI

ClearAll[getRSI];
getRSI[Pricedata_List,N3_Integer] := Module[{N,N2,error,i,j,delta,RSI,UpData,DownData,up,down,upavg,downavg,PriceData},
N2=Length[Pricedata];
PriceData=Pricedata[[-N2;;-1]];

RSI = ConstantArray[0.0,N2];
up = ConstantArray[0.0,N2];
down = ConstantArray[0.0,N2];
Do[delta= PriceData[[i+1]]-PriceData[[i]];If[delta≥ 0.0,up[[i+1]]=PriceData[[i+1]]-PriceData[[i]],down[[i+1]]= PriceData[[i]]-PriceData[[i+1]]],{i,1,N2-1}];
downavg = ConstantArray[0.0,N2];
upavg = ConstantArray[0.0,N2];
downavg[[N3]] =Total[down[[1;;N3]]]/N3;
upavg[[N3]] = Total[up[[1;;N3]]]/N3;
RSI[[N3]] = 100.0-100.0/(10^(-200)+downavg[[N3]]+upavg[[N3]])*downavg[[N3]];If[RSI[[N3]]<0.0,RSI[[N3]]=0.0];If[RSI[[N3]]>100.0,RSI[[N3]]=100.0];

Do[downavg[[i+N3]] =(down[[i+N3]]-downavg[[i+N3-1]])*2.0/(N3+1.0)+downavg[[i+N3-1]];upavg[[i+N3]]=(up[[i+N3]]-upavg[[i+N3-1]])*2.0/(N3+1.0)+upavg[[i+N3-1]];RSI[[N3+i]]=100.0-100.0/(10^(-200)+downavg[[i+N3]]+upavg[[i+N3]])*downavg[[i+N3]];If[RSI[[N3+i]]<0.0,RSI[[N3+i]]=0.0];If[RSI[[N3+i]]>100.0,RSI[[N3+i]]=100.0]
,{i,1,N2-N3}];
RSI];

N2 = Min[Length

RSI=getRSI[100*RandomReal[1,100],120*RandomReal[1,100],90*RandomReal[1,100],17];
RSI

getData

(* All Rights Reserved - CopyRight 2012, Richard John Belshaw, AGU,AAAS,ASA,IEEE,ACS,ACM*)

ClearAll[getData];
getData[SeasonalFlag_Integer,data_List,numpts_Integer:8192,extendflag_Integer,debugflag_Integer]/; ((extendflag==0||extendflag==1)&&(debugflag==1||debugflag==0)):=Module[{xa, xb, MaxRatio,ratios, difflist,phaselist, extenlst, intlist, data1,pdflist, outlst, sdifflist},
If[debugflag==1,Print["Start getData:"];Print[Length[data]]];
MaxRatio = Max[data]/(10^(-100)+Min[data]);

Clear[ratios];ratios = ConstantArray[0,Length[data]-1];
Do[If[Abs[data[[j]]]>0,ratios[[j]]=data[[j+1]]/data[[j]],ratios[[j]]=0;];,{j,1,Length[data]-1}];

If[debugflag==1,Print["ratios=",ratios];Print["3a"]];
 If [Max[Abs[ratios]]>0, {xa, xb, extenlst, intlist, pdflist, outlst}=getPDF5[ratios,numpts,MaxRatio,extendflag,debugflag];,xa=xb=0;extenlst=intlist=pdflist=outlst=ConstantArray[0,Length[ratios]];];
If[debugflag==1,Print["3b"]];
{xa, xb, ratios, extenlst, intlist, pdflist, outlst}]

getPDF5

(* All Rights Reserved - CopyRight 2012, Richard John Belshaw, AGU,AAAS,ASA,IEEE,ACS,ACM*)

ClearAll[getPDF5]; (* new definition from 3/5/2013 *)

getPDF5[temp_List,N2_Integer,MaxRatio_,extendflag_Integer:0,debugflag_Integer:0]/;(N2>Length[temp]&&(extendflag==0||extendflag==1)&&(debugflag==1||debugflag==0)):=Module[{sortlst,N1,xa,xb,extenlst,extenlst1,i,h0,intlist,pdflist,outlst,h7,coeffs,FlagRatioa2,FlagRatiob1,j,x0,sumval,m,mat,y,x,z,a,b,x1,x2,c,d,a5,b5,c5,d5,a7,b7,c7,d7,nlm1,a2,f7,c2,d2,f1,nlm2,b1,f8,c1,d1,z1,f2,count,temp1,n,delta,f11,f12,k,flag1,down,up,n1,n2,N3,intpdflist,pdflistfn,a3,b2,temp2,func1,pdf,int,f,temp3,z2,k1,pdflist2,h01,nlm1pars,nlm2pars},
If [debugflag==1, Print["Start GetPDF5"]];
sortlst=Sort[temp];N1=Length[temp];
xa=sortlst[[1]];xb=sortlst[[-1]];extenlst1=sortlst;extenlst={};
temp1={};
i=1;
While[i≤ N1, While[i≤ N1 && (extenlst1[[i]]==0||extenlst1[[i]]==Infinity||!NumberQ[extenlst1[[i]]]),i+=1];If[i≤ N1,AppendTo[extenlst,extenlst1[[i]]]];i+=1];
i=2;
extenlst = Sort[extenlst];
temp1 = {};
While[i≤ N1, While [i≤N1 &&(extenlst[[i]]==extenlst[[i-1]]),i+=1];If[i≤ N1+1,AppendTo[temp1,extenlst[[i-1]]]];i=i+1];
If [ i== N1+1 && extenlst[[i-2]]≠ extenlst[[i-1]], AppendTo[temp1,extenlst[[i-1]]]];
temp1=Sort[temp1];

N1=Length[extenlst];xa=extenlst[[1]];xb=extenlst[[-1]];
(*Print[xa," , ",xb];*)
If[extendflag ==1,
a=xa;
b=xb;
If[debugflag==1,Print["4a"];
Print[temp1[[1;;Min[7,Length[temp1]]]]]];
nlm1pars[a2,f7,c2,d2,x] = Log[Abs[a2]] + c2*Log[x+2.+f7]+d2*Log[x+2.+f7]^2;
Off[NonlinearModelFit::nrlnum,NonlinearModelFit::cvmit,NonlinearModelFit::sszero];
nlm1 = NonlinearModelFit[Log[temp1[[1;;Min[7,Length[temp1]]]]],nlm1pars[a2,f7,c2,d2,x],{a2,f7,c2,d2},x,MaxIterations-> 30000];
z1 = nlm1["BestFitParameters"];
If[debugflag==1,Print[z1]];
a2 =Abs[z1[[1,2]]];
If[debugflag==1,Print["a2= ",a2]];
FlagRatioa2=0;
If[a2<1/(10*MaxRatio),a2=1/(10*MaxRatio);FlagRatioa2=1;If[debugflag==1,Print["a2new= ",a2]]];

f7 =z1[[2,2]];
c2 = z1[[3,2]];
d2 = z1[[4,2]];



If[x1<1E-20, x1=1E-20];
If[debugflag==1,Print["4b"];
If[Length[temp1]>7,
Print[temp1[[-7;;-1]]]];
nlm2pars[b1,f8,c1,d1,x] = Log[Abs[b1]]+ c1*Log[x+2.+f8]-d1*Log[x+2.+f8]^2;
nlm2= NonlinearModelFit[Log[Reverse[temp1[[-Min[7,Length[temp1]];;-1]]]],nlm2pars[b1,f8,c1,d1,x],{b1,f8,c1,d1},x,MaxIterations->30000];
(*Print[z1];*)
z2 = nlm2["BestFitParameters"];
b1 = Abs[z2[[1,2]]];
If[debugflag==1,Print["z2 = ",z2];Print["b1 = ",b1]];
FlagRatiob1=0;
If [b1 > 10*MaxRatio,b1 = 10*MaxRatio;FlagRatiob1=1;If[debugflag==1,Print["b1new = ",b1]]];

f8 =z2[[2,2]];
c1 = z2[[3,2]];
d1 = z2[[4,2]];];
If [debugflag==1,Print["4c"]];
delta =1;
up = 12;
down = up - delta;
flag1=0;
count=0;
If [debugflag==1,Print["a2 = ",a2]];
While [((Re[Exp[ nlm1[down]]]< Re[Exp[nlm1[up]]]) && (Re[Exp[nlm1[down]]] == Exp[nlm1[down]]) &&Re[Exp[nlm1[down]]]≥ a2&& count < 200 && FlagRatioa2==0),

up = down;
count = count +1;
down = down - delta;
];

If[debugflag==1,Print["4d "]];
up = N[up];


temp2 = {};

i= 12;
While [(i≥ up && FlagRatioa2==0),
If[Exp[nlm1[i]]==Re[Exp[nlm1[i]]]&& Re[Exp[nlm1[i]]]<a &&Re[Exp[nlm1[i]]]≥a2,
AppendTo[temp2,Exp[nlm1[i]]];
If[debugflag==1,Print[Exp[nlm1[i]]]]];
       i=i-delta;
];
If[FlagRatioa2==0,
If[temp2=={}, a3 = a, a3 = Sort[temp2][[1]]];
If [a2>0&& a3>a2,
AppendTo[temp2,a2];
If[debugflag==1,Print[a2]];
];
];

extenlst = Join[temp2,extenlst];
extenlst = N[Sort[extenlst]];
xa = extenlst[[1]],
xa = a];
If [extendflag==1,
If [debugflag==1,
Print["4e"]];
delta = 1;
up = 12;
down = up - delta;
If[debugflag==1,
Print["b1= ",b1]];

count =0;
While [((Re[Exp[ nlm2[down]]]> Re[Exp[nlm2[up]]]) && (Re[Exp[nlm2[down]]] == Exp[nlm2[down]])&&Re[Exp[nlm2[down]]]≤ b1&& count < 200 && FlagRatiob1==0),

up = down;
count = count +1;
down = down - delta;
];

If[debugflag==1,Print["4f"]];
up = N[up];
temp2 = {};


i=0;
While [(i≥ up  && FlagRatiob1==0),
If[Re[Exp[nlm2[i]]]≤  b1&& Exp[nlm2[i]]==Re[Exp[nlm2[i]]]&&Re[Exp[nlm2[i]]]>b,
If [debugflag==1,Print[Exp[nlm2[i]]]];
AppendTo[temp2,Exp[nlm2[i]]]];
       i=i-delta;
];
If [FlagRatiob1==0,
If [ temp2 == {}, b2 = b, b2 = Sort[temp2][[-1]]];
If [ b1 > b2,
If[debugflag==1,Print[b1]];
AppendTo[temp2,b1];
];
];
extenlst = Join[extenlst,temp2];
extenlst =N[ Sort[extenlst]];
xb = extenlst[[-1]],
xb=b];


If[debugflag==1,Print["4g"]];
N1 = Length[extenlst];
f = ConstantArray[{},N2];
func1 = ConstantArray[{},N1];
outlst = ConstantArray[0,N2];
pdflist = ConstantArray[0,N2];
xa=extenlst[[1]];
xb=extenlst[[-1]];

Clear[f2];
  Do [ func1[[i]] = {i ,(SetPrecision[ extenlst[[i]],30])},{i,1,N1}];
y = Interpolation[func1];
  h0 = N[(N1-1)/(N2-1)];
     Do [f[[i+1]] = {N[h0*i+1] ,N[Evaluate[y[h0*i+1]]]}, {i,0,N2-1}];
    f2 = Interpolation[f];
   temp2 = Derivative[1][f2];
   Do [If[temp2[h0*i+1]==0,pdflist[[i+1]] = 0,pdflist[[i+1]]=1/N[Evaluate[temp2[h0*i+1]]]],{i,0,N2-1}];
 
     Do [ outlst[[i+1]] = N[y[(i*h0+1)]],{i,0,N2-1}];
 (*    z = Fourier[pdflist];
     z[[Floor[N2/2*1/5];;N2/2+1+Floor[N2/2*4/5]]]=0;
     pdflist = Re[InverseFourier[z]];*)
 Do[If[pdflist[[i]]<0,pdflist[[i]] = 0],{i,1,N2}];
{sumval,intlist} = getIntegrate2[pdflist[[1;;N2]],1,1,N2];
pdflist = pdflist/sumval;
          intlist = intlist/intlist[[-1]];
If[debugflag==1,Print["End GetPDF5"]];
{xa,xb,extenlst,intlist,pdflist,outlst}]

getIntegrate2

(* All Rights Reserved - CopyRight 2012, Richard John Belshaw, AGU,AAAS,ASA,IEEE,ACS,ACM*)

k = Boltzmann's constant or 1, a and b limits of integration on x axis from first to last point,eg .95 to 1.1

ClearAll[getIntegrate2];

getIntegrate2[datapts_?(VectorQ[#,NumberQ]&),k_?NumberQ,a_?NumberQ,b_?NumberQ]:=Module[{N1=Length[datapts],coeffs={14,32,12,32},h1,intlist,sumval,j,temp1},h1=((b-a)/(N1-1)*2/45);
intlist = ConstantArray[0,N1];
intlist[[1]]=N[7*datapts[[1]]^k*h1];sumval=intlist[[1]];
j=1;While[j≤ N1-2,temp1=coeffs[[j+1-Floor[j/4]*4]]*datapts[[j+1]]^k*h1;sumval=sumval+temp1; intlist[[j+1]]=N[sumval];j+=1];sumval=sumval+7*datapts[[N1]]^k*h1;
intlist[[N1]]=N[sumval];
{N[sumval],intlist}];
ClearAll[getMultiply2];

getMultiply2[datapts_List,k_?NumberQ,a_?NumberQ,b_?NumberQ]:=Module[{N1=Length[datapts],intlist,mulval,j,temp1},
intlist={datapts[[1]]^k};mulval = intlist[[1]];
j=1;While[j≤ N1-2,temp1=datapts[[j+1]]^k;mulval=N[mulval+temp1-mulval*temp1]; intlist=Append[intlist,mulval];j+=1];
mulval= N[mulval+datapts[[N1]]^k- mulval*datapts[[N1]]^k];intlist=Append[intlist,mulval];
N[intlist]]

datapts=Range[0.05,.95,.05];N1=Length[datapts];
getIntegrate2[Range[0.05,0.95,0.05],1,1,N1]

datapts=Range[0.05,.95,.05];
N1=Length[datapts];
getMultiply2[datapts,1,1,N1]

getDist

(* All Rights Reserved - CopyRight 2012, Richard John Belshaw, AGU,AAAS,ASA,IEEE,ACS,ACM*)

ClearAll[getDist];(*new definition from 2/14/2013*)getDist[lst_?(VectorQ[#,Positive[#]&]&)]:=Module[{L,i,j,k,lst1,newlist,sdifflist,sumval},lst1=lst;
L=Length[lst1];
While[j≤L,If[lst1[[j]]==0||lst1[[j]]≠NumberQ,i=j;While[i≤L,lst1[[i]]=lst1[[i+1]];i=i+1;];L=L-1,i=j;] j=j+1;];
(*sdifflist=Sort[Abs[Differences[Transpose[SortBy[Transpose[{Range[1,Length[lst1]],lst1}],Last]][[1]]]]];*)
sdifflist=Sort[Abs[Differences[Ordering[lst1]]]];
L=L-1;
newlist=ConstantArray[0,L];
j=1;
i=1;
While[i≤L&&j≤L,k=0;
While[j≤L&&sdifflist[[j]]==i,k=k+1;
j=j+1];
newlist[[i]]=k;
i=i+1];
sumval=Total[newlist];
newlist=N[newlist/sumval]];

vec=RandomVariate[ParetoDistribution[2,2,1],15]

getDist[vec](* value from 2/14/2012 *)

getPercentErrorCubic

(* All Rights Reserved - CopyRight 2012, Richard John Belshaw, AGU,AAAS,ASA,IEEE,ACS,ACM*)

ClearAll[getPercentErrorCubic]  (* definition from Feb 7, 2013 
where actdata is original stock prices, dataarray is either Null matrix {{}} or temperatures SeasData *)

getPercentErrorCubic[actdata_List,dataarray_List?MatrixQ]:=Module[{i,j,k,a=1,b,N1,N2,coeffs,vol6,vol7,L1,L,Temp,Soy,Sxoy,Sx2oy,Sx3oy,Soy2,Sxoy2,Sx2oy2,Sx3oy2,Sx4oy2,Sx5oy2,Sx6oy2,vol,volatility,vol2},{a,b}=Dimensions[dataarray];If[b==0,N1=0;N2=Length[actdata],N1=Length[actdata];N2=Length[actdata]+b];L=N2-N1; L1=N1+1;
coeffs=ConstantArray[0,4];vol6=ConstantArray[0,L];vol7=0;
Do[ If[a>1,Temp=SetPrecision[dataarray[[i,1;;L]],60],Temp=SetPrecision[actdata,60]]; 
Do[ If[Temp[[k]]==0,Temp[[k]] = 10^(-20)],{k,1,L}];
Soy=Total[1/Temp[[1;;L]]];
Sxoy=Total[Range[L1,N2]/Temp[[1;;L]]];
Sx2oy=Total[Range[L1,N2]^2/Temp[[1;;L]]];
Sx3oy=Total[Range[L1,N2]^3/Temp[[1;;L]]];
Soy2=Total[1/Temp[[1;;L]]^2];
Sxoy2=Total[Range[L1,N2]/Temp[[1;;L]]^2];
Sx2oy2=Total[Range[L1,N2]^2/Temp[[1;;L]]^2];
Sx3oy2=Total[Range[L1,N2]^3/Temp[[1;;L]]^2];
Sx4oy2=Total[Range[L1,N2]^4/Temp[[1;;L]]^2];
Sx5oy2=Total[Range[L1,N2]^5/Temp[[1;;L]]^2];
Sx6oy2=Total[Range[L1,N2]^6/Temp[[1;;L]]^2];
coeffs[[1]]=(Sx4oy2*Sxoy2*Sx3oy2*Sxoy+Soy2*Sx3oy2*Sx4oy2*Sx2oy-Soy2*Sx3oy2^2*Sx3oy-Sx5oy2*Sx3oy2*Sxoy2*Soy+ Sx3oy2^3*Soy-Sxoy2^2*Sx4oy2*Sx3oy+2*Sx2oy2*Sxoy2*Sx3oy2*Sx3oy+Sxoy2^2*Sx5oy2*Sx2oy-Sx2oy2*Sxoy2*Sx4oy2*Sx2oy- 2*Sx2oy2*Sx4oy2*Sx3oy2*Soy-Sx2oy2*Sx5oy2*Sxoy2*Sxoy+Sx2oy2^2*Sx3oy2*Sx2oy+Soy2*Sx2oy2*Sx4oy2*Sx3oy-Soy2*Sx2oy2*Sx5oy2*Sx2oy- Sx2oy2*Sx3oy2^2*Sxoy-Sx2oy2^3*Sx3oy+Soy2*Sx5oy2*Sx3oy2*Sxoy-Soy2*Sx4oy2^2*Sxoy+Sx2oy2^2*Sx4oy2*Sxoy+Sx4oy2^2*Sxoy2*Soy- Sx3oy2^2*Sxoy2*Sx2oy+Sx2oy2^2*Sx5oy2*Soy)/(2*Sx2oy2^2*Sx5oy2*Sx3oy2-Sx2oy2^3*Sx6oy2-2*Sx5oy2*Sx3oy2^2*Sxoy2-3*Sx2oy2*Sx4oy2*Sx3oy2^2+Sx2oy2^2*Sx4oy2^2+2*Sx4oy2^2*Sxoy2*Sx3oy2-Soy2*Sx2oy2*Sx5oy2^2-Soy2*Sx4oy2^3- Sxoy2^2*Sx4oy2*Sx6oy2+Sx3oy2^4-Soy2*Sx3oy2^2*Sx6oy2+Sxoy2^2*Sx5oy2^2-2*Sx2oy2*Sx5oy2*Sxoy2*Sx4oy2+2*Sx2oy2*Sxoy2*Sx3oy2*Sx6oy2+Soy2*Sx2oy2*Sx4oy2*Sx6oy2+2*Soy2*Sx3oy2*Sx4oy2*Sx5oy2);
coeffs[[2]]=-(Sx3oy2*Sx5oy2*Sxoy*Sxoy2-Sx3oy2^3*Sxoy-Sx3oy*Sx5oy2*Sxoy2^2+Sx3oy*Sx3oy2^2*Sxoy2-Sx2oy2*Sx6oy2*Sxoy*Sxoy2+ Sx2oy2*Sx3oy2*Sx4oy2*Sxoy+Sx2oy2*Sx3oy*Sx4oy2*Sxoy2-Sx2oy2^2*Sx3oy*Sx3oy2+Sx2oy*Sx6oy2*Sxoy2^2-2*Sx2oy*Sx3oy2*Sx4oy2*Sxoy2+ Sx2oy*Sx2oy2*Sx3oy2^2-Soy2*Sx4oy2*Sx5oy2*Sxoy+Soy2*Sx3oy2*Sx6oy2*Sxoy-Soy2*Sx3oy*Sx3oy2*Sx4oy2+Soy2*Sx2oy2*Sx3oy*Sx5oy2+ Soy2*Sx2oy*Sx4oy2^2-Soy2*Sx2oy*Sx2oy2*Sx6oy2+Soy*Sx4oy2*Sx5oy2*Sxoy2-Soy*Sx3oy2*Sx6oy2*Sxoy2+Soy*Sx3oy2^2*Sx4oy2- Soy*Sx2oy2*Sx4oy2^2-Soy*Sx2oy2*Sx3oy2*Sx5oy2+Soy*Sx2oy2^2*Sx6oy2)/(2*Sx2oy2^2*Sx5oy2*Sx3oy2-Sx2oy2^3*Sx6oy2- 2*Sx5oy2*Sx3oy2^2*Sxoy2-3*Sx2oy2*Sx4oy2*Sx3oy2^2+Sx2oy2^2*Sx4oy2^2+2*Sx4oy2^2*Sxoy2*Sx3oy2-Soy2*Sx2oy2*Sx5oy2^2-Soy2*Sx4oy2^3- Sxoy2^2*Sx4oy2*Sx6oy2+Sx3oy2^4-Soy2*Sx3oy2^2*Sx6oy2+Sxoy2^2*Sx5oy2^2-2*Sx2oy2*Sx5oy2*Sxoy2*Sx4oy2+2*Sx2oy2*Sxoy2*Sx3oy2*Sx6oy2+Soy2*Sx2oy2*Sx4oy2*Sx6oy2+2*Soy2*Sx3oy2*Sx4oy2*Sx5oy2);
coeffs[[3]]=(Soy2*Sx3oy2*Sx3oy*Sx5oy2+Soy2*Sx4oy2*Sx5oy2*Sx2oy-Soy2*Sx4oy2^2*Sx3oy-Soy2*Sxoy*Sx5oy2^2-Soy2*Sx3oy2*Sx2oy*Sx6oy2+ Soy2*Sxoy*Sx4oy2*Sx6oy2+Sx2oy2^2*Sx4oy2*Sx3oy-Sx2oy2^2*Sxoy*Sx6oy2+Sx2oy2*Sxoy2*Sx2oy*Sx6oy2-Sx2oy2*Sxoy2*Sx3oy*Sx5oy2- Sx2oy2*Sx4oy2*Sx5oy2*Soy+Sx2oy2*Sx3oy2*Soy*Sx6oy2+2*Sx2oy2*Sx5oy2*Sx3oy2*Sxoy-Sx3oy2^2*Sx2oy2*Sx3oy- Sx3oy2*Sx4oy2*Sx2oy2*Sx2oy-Sx4oy2*Sx3oy2^2*Sxoy+Sxoy2*Soy*Sx5oy2^2-Sx3oy2^2*Soy*Sx5oy2-Sxoy2*Sx3oy2*Sx5oy2*Sx2oy- Sxoy2*Soy*Sx4oy2*Sx6oy2+Sx4oy2^2*Sx3oy2*Soy+Sx3oy2^3*Sx2oy+Sx4oy2*Sxoy2*Sx3oy2*Sx3oy)/(2*Sx2oy2^2*Sx5oy2*Sx3oy2- Sx2oy2^3*Sx6oy2-2*Sx5oy2*Sx3oy2^2*Sxoy2-3*Sx2oy2*Sx4oy2*Sx3oy2^2+Sx2oy2^2*Sx4oy2^2+2*Sx4oy2^2*Sxoy2*Sx3oy2- Soy2*Sx2oy2*Sx5oy2^2-Soy2*Sx4oy2^3-Sxoy2^2*Sx4oy2*Sx6oy2+Sx3oy2^4-Soy2*Sx3oy2^2*Sx6oy2+Sxoy2^2*Sx5oy2^2- 2*Sx2oy2*Sx5oy2*Sxoy2*Sx4oy2+2*Sx2oy2*Sxoy2*Sx3oy2*Sx6oy2+Soy2*Sx2oy2*Sx4oy2*Sx6oy2+2*Soy2*Sx3oy2*Sx4oy2*Sx5oy2);
coeffs[[4]]=(Sxoy2*Sx4oy2^2*Sx3oy+Sxoy2*Sxoy*Sx5oy2^2-Soy*Sx2oy2*Sx5oy2^2-Soy*Sx3oy2^2*Sx6oy2-Sx3oy2^2*Sx4oy2*Sx2oy- Sx5oy2*Sx3oy2^2*Sxoy+Sx3oy2*Sx4oy2^2*Sxoy+Sx2oy2^2*Sx3oy*Sx5oy2+Sx2oy2*Sx2oy*Sx4oy2^2-Sx2oy*Sx2oy2^2*Sx6oy2- 2*Sx3oy2*Sx2oy2*Sx4oy2*Sx3oy+Sx3oy2*Sx2oy2*Sx5oy2*Sx2oy-Sx2oy2*Sx4oy2*Sx5oy2*Sxoy+Sx2oy2*Sx3oy2*Sx6oy2*Sxoy- Sxoy2*Sx3oy2*Sx3oy*Sx5oy2-Sxoy2*Sx4oy2*Sx5oy2*Sx2oy+Sxoy2*Sx3oy2*Sx2oy*Sx6oy2-Sxoy2*Sxoy*Sx4oy2*Sx6oy2+ Soy*Sx2oy2*Sx4oy2*Sx6oy2+2*Soy*Sx3oy2*Sx4oy2*Sx5oy2+Sx3oy2^3*Sx3oy-Soy*Sx4oy2^3)/(2*Sx2oy2^2*Sx5oy2*Sx3oy2- Sx2oy2^3*Sx6oy2-2*Sx5oy2*Sx3oy2^2*Sxoy2-3*Sx2oy2*Sx4oy2*Sx3oy2^2+Sx2oy2^2*Sx4oy2^2+2*Sx4oy2^2*Sxoy2*Sx3oy2- Soy2*Sx2oy2*Sx5oy2^2-Soy2*Sx4oy2^3-Sxoy2^2*Sx4oy2*Sx6oy2+Sx3oy2^4-Soy2*Sx3oy2^2*Sx6oy2+Sxoy2^2*Sx5oy2^2- 2*Sx2oy2*Sx5oy2*Sxoy2*Sx4oy2+2*Sx2oy2*Sxoy2*Sx3oy2*Sx6oy2+Soy2*Sx2oy2*Sx4oy2*Sx6oy2+2*Soy2*Sx3oy2*Sx4oy2*Sx5oy2);
vol=ConstantArray[0,L];
Do[vol[[j]]=(Temp[[j]]-coeffs[[1]]*(N1+j)^3-coeffs[[2]]*(N1+j)^2-coeffs[[3]]*(N1+j)-coeffs[[4]])^2;
vol6[[j]]=vol6[[j]]+vol[[j]],{j,1,L}];
vol7=vol7+Sqrt[Total[vol[[1;;L]]]/(L-1)],{i,1,a}];
If[a>1, vol2=vol7/a;volatility=Sqrt[vol6/(a-1)],volatility=vol7;vol2=0];
{coeffs,volatility,vol2}];
ClearAll[getPercentErrorCubic2];
getPercentErrorCubic2[actdata_List,dataarray_List?MatrixQ,futurearma_List]:=Module[{i,j,k,a=1,b,N1,N2,coeffs,vol6,vol7,L1,L,Temp,Soy,Sxoy,Sx2oy,Sx3oy,Soy2,Sxoy2,Sx2oy2,Sx3oy2,Sx4oy2,Sx5oy2,Sx6oy2,vol,volatility,vol2},{a,b}=Dimensions[dataarray];If[b==0,N1=0;N2=Length[actdata],N1=Length[actdata];N2=Length[actdata]+b];L=N2-N1; L1=N1+1;
coeffs=ConstantArray[0,4];vol6=ConstantArray[0,L];vol7=0;
Do[ If[a>1,Temp=SetPrecision[dataarray[[i,1;;L]],60],Temp=SetPrecision[actdata,60]]; 
Do[ If[Temp[[k]]==0,Temp[[k]] = 10^(-20)],{k,1,L}];

vol=ConstantArray[0,L];
Do[vol[[j]]=(Temp[[j]]-futurearma[[j]])^2;
vol6[[j]]=vol6[[j]]+vol[[j]],{j,1,L}];
vol7=vol7+Sqrt[Total[vol[[1;;L]]]/(L-1)],{i,1,a}];
If[a>1, vol2=vol7/a;volatility=Sqrt[vol6/(a-1)],volatility=vol7;vol2=0];
{coeffs,volatility,vol2}]

generateMagPhase

(* All Rights Reserved - CopyRight 2012, Richard John Belshaw, AGU,AAAS,ASA,IEEE,ACS,ACM*)

ClearAll[generateMagPhase];(*new definition from Mar 4,2013*)

generateMagPhase[ratios_List,intlist_List,pdflist_List,outlst_List,xa_?NumberQ,xb_?NumberQ,np_Integer,steps_Integer,ppast_,debugflag_Integer]/;((0≤ppast≤1)&&(debugflag==1||debugflag==0)):=Module[{phasedistpdf,ft,sigma,psi,mu,x,nlm,h,h1,dB,pdB,phaselistpdf2,phaselistcdf,sumval,N3,i,j,k,x0,indxvals,g1list,g2list,rv,k1,p2,futureflag,mag,p1,phasedistcdf,temp,phasedistpdf2,k2,p11,x2,N5,weights,p3},
If [debugflag==1,Print["Start GenerateMagPhase:",DateString[]]];
phasedistpdf=getDist[SetPrecision[ratios,20]];
If[debugflag==1,Print["****1"]];
{sumval,phasedistcdf}=getIntegrate2[phasedistpdf,1,1,Length[phasedistpdf]];
phasedistcdf=phasedistcdf/sumval;

If[debugflag==1,Print["****2"]];
ft[sigma_,psi_,mu_,x_]:=Re[1/sigma*(1+psi*(x-mu)/sigma)^((-1/sigma)-1)];
(*ft[sigma_,psi_,mu_,x_]:=Re[PDF[ParetoDistribution[sigma,psi,mu],x]];*)
nlm=NonlinearModelFit[phasedistpdf,ft[sigma,psi,mu,x],{sigma,psi,mu},x,Method->"NMinimize",MaxIterations->1000,PrecisionGoal->20];
{sigma,psi,mu}=Transpose[nlm["ParameterTableEntries"]][[1]];
(* h[sigma_,psi_,mu_,x_]:=If[1+psi*(x-mu)/sigma>0,Re[1/sigma*(1+psi*(x-mu)/sigma)^((-1/sigma)-1)],0]; *)
(*weights = ConstantArray[1,9*Length[phasedistpdf]];
*)
weights = ft[sigma,psi,mu,#]&/@Range[Length[phasedistpdf]+1,9*Length[phasedistpdf]];
phaselistpdf2=Join[phasedistpdf,weights];

{sumval,phaselistcdf}=getIntegrate2[phaselistpdf2,1,1,Length[phaselistpdf2]];
phaselistcdf=phaselistcdf/sumval;
N3=Length[intlist];indxvals=ConstantArray[0,Length[intlist]];
i=1;k=1;
While[i≤N3,x0=(i-1)/(N3-1);
While[k≤N3&&intlist[[k]]<x0,k=k+1];
If[k>1,indxvals[[i]]=k-1,indxvals[[i]]=1.];
i=i+1];
g1list=ConstantArray[0,Length[phaselistpdf2]];
i=1;k=1;
While[i≤Length[phaselistpdf2],x0=(i-1)/(Length[phaselistpdf2]-1);
While[k≤Length[phaselistcdf]&&phaselistcdf[[k]]<x0,k=k+1];
If[k>1,g1list[[i]]=(k-1),g1list[[i]]=1.];
i=i+1];
g2list=ConstantArray[0,Length[phasedistpdf]];
i=1;k=1;
While[i≤Length[phasedistpdf],x0=(i-1)/(Length[phasedistpdf]-1);
While[k≤Length[phasedistpdf]&&phasedistcdf[[k]]<x0,k=k+1];
If[k>1,g2list[[i]]=(k-1),g2list[[i]]=1.];
i=i+1];
dB=ConstantArray[0.0,{np,steps}];
pdB=ConstantArray[0.0,{np,steps}];
N5=Length[pdflist];



Do[rv=RandomReal[];
futureflag=0;
If[rv<ppast,rv=RandomReal[];
k1=Floor[rv*(Length[phasedistpdf]-1)+1.5];
k=g2list[[k1]];

p2=phasedistpdf[[k]]
If[k≥j,mag=ratios[[Length[ratios]-(k-j)]],mag=dB[[i,j-k]]],
k1=Floor[rv*(Length[phaselistpdf2]-1)+1.5];
If[k1≤Length[phasedistpdf],rv=RandomReal[];


k=g2list[[k1]];
p2=phasedistpdf[[k]],
k2=g1list[[k1]];
p2=phaselistpdf2[[k2]];
futureflag=1];
rv=RandomReal[];
k1=Floor[rv*(Length[intlist]-1)+1.5];
k2=indxvals[[k1]];mag=outlst[[k2]]];
If[mag<xa||mag>xb,p1=0,
temp=(mag-xa)/(xb-xa)*(N5-1)+1;
k1=Floor[temp];
x2=temp-k1;
p11=pdflist[[k1]];
If[k1<N5,p1=p11*(1-x2)+pdflist[[k1+1]]*x2,p1=p11]];
dB[[i,j]]=mag;
pdB[[i,j]]=(p1*p2),{i,1,np},{j,1,steps}];
If[debugflag==1,Print["End GenerateMagPhase:",DateString[]]];
{dB,pdB,phasedistpdf}]
(* All Rights Reserved - CopyRight 2012, Richard John Belshaw, AGU,AAAS,ASA,IEEE,ACS,ACM*)
ClearAll[generateMagPhase2];(*new definition from Mar 4,2013*)

generateMagPhase2[threshold_,ratios_List,intlist_List,pdflist_List,outlst_List,xa_,xb_,np_Integer,steps_Integer,ppast_,debugflag_Integer]/;((0≤ppast≤1)&&(debugflag==1||debugflag==0)):=Module[{phasedistpdf,ft,sigma,psi,mu,x,nlm,h,h1,dB,dB2,pdB,pdB2,phaselistpdf2,phaselistcdf,sumval,N3,i,j,k,x0,indxvals,g1list,g2list,rv,k1,p2,futureflag,mag,p1,phasedistcdf,indices,temp,phasedistpdf2,k2,p11,x2,N5,weights,p3},
If [debugflag==1,Print["Start GenerateMagPhase"]];
If[debugflag==1,Print[Dimensions[ratios],Dimensions[intlist],Dimensions[pdflist],Dimensions[outlst]]];
phasedistpdf=getDist[SetPrecision[ratios,20]];
If[debugflag==1,Print["****1"]];
{sumval,phasedistcdf}=getIntegrate2[phasedistpdf,1,1,Length[phasedistpdf]];
phasedistcdf=phasedistcdf/sumval;
If[debugflag==1,Print["****2"]];
indices=matlabFind1[phasedistpdf,Unequal,0];
If[debugflag==1,Print["****3"]];
ft[sigma_,psi_,mu_,x_]:=Re[1/sigma*(1+psi*(x-mu)/sigma)^((-1/sigma)-1)];
(*ft[sigma_,psi_,mu_,x_]:=Re[PDF[ParetoDistribution[sigma,psi,mu],x]];*)
Off[NonlinearModelFit::sszero];
nlm=NonlinearModelFit[phasedistpdf,ft[sigma,psi,mu,x],{sigma,psi,mu},x,Method->"NMinimize",MaxIterations->10000,PrecisionGoal->20];
{sigma,psi,mu}=Transpose[nlm["ParameterTableEntries"]][[1]];
(* h[sigma_,psi_,mu_,x_]:=If[1+psi*(x-mu)/sigma>0,Re[1/sigma*(1+psi*(x-mu)/sigma)^((-1/sigma)-1)],0]; *)
(*weights = ConstantArray[1,9*Length[phasedistpdf]];
*)
phaselistpdf2=phasedistpdf;

{sumval,phaselistcdf}=getIntegrate2[phaselistpdf2,1,1,Length[phaselistpdf2]];
phaselistcdf=phaselistcdf/sumval;
N3=Length[intlist];indxvals=ConstantArray[0,Length[intlist]];
i=1;k=1;
While[i≤N3,x0=(i-1)/(N3-1);
While[k≤N3&&intlist[[k]]<x0,k=k+1];
If[k>1,indxvals[[i]]=k-1,indxvals[[i]]=1.];
i=i+1];
g1list=ConstantArray[0,Length[phaselistpdf2]];
i=1;k=1;
While[i≤Length[phaselistpdf2],x0=(i-1)/(Length[phaselistpdf2]-1);
While[k≤Length[phaselistcdf]&&phaselistcdf[[k]]<x0,k=k+1];
If[k>1,g1list[[i]]=(k-1),g1list[[i]]=1.];
i=i+1];
g2list=ConstantArray[0,Length[indices]];
i=1;k=1;
While[i≤Length[indices],x0=(i-1)/(Length[phasedistpdf]-1);
While[k≤Length[indices]&&phasedistcdf[[indices[[k]]]]<x0,k=k+1];
If[k>1,g2list[[i]]=(k-1),g2list[[i]]=1.];
i=i+1];
dB2=dB=ConstantArray[0,{np,steps}];

pdB2=pdB=ConstantArray[0,{np,steps}];
N5=Length[pdflist];
Do[rv=RandomReal[];
If[Length[indices]≥ 252,
k1=Floor[rv*251+1.5],
k1 = Floor[rv*(Length[indices]-1)+1.5]];
k=g2list[[k1]];
p2=phasedistpdf[[indices[[k]]]];

rv=RandomReal[];
k1=Floor[rv*threshold*(Length[intlist]-1)+1.5];
k2=indxvals[[k1]];mag=outlst[[k2]];
If[mag<xa||mag>xb,p1=0,
temp=(mag-xa)/(xb-xa)*(N5-1)+1;
k1=Floor[temp];
x2=temp-k1;
p11=pdflist[[k1]];
If[k1<N5,p1=p11*(1-x2)+pdflist[[k1+1]]*x2,p1=p11]];
dB[[i,j]]=mag;
pdB[[i,j]]=N[p1*p2];
rv=RandomReal[];

If[Length[indices]≥ 252,
k1=Floor[rv*251+1.5],
k1 = Floor[rv*(Length[indices]-1)+1.5]];
k=g2list[[k1]];
p2=phasedistpdf[[indices[[k]]]];

rv=RandomReal[];
k1=Floor[(threshold*rv+1.0-threshold)*(Length[intlist]-1)+1.5];
k2=indxvals[[k1]];mag=outlst[[k2]];
If[mag<xa||mag>xb,p1=0,
temp=(mag-xa)/(xb-xa)*(N5-1)+1;
k1=Floor[temp];
x2=temp-k1;
p11=pdflist[[k1]];
If[k1<N5,p1=p11*(1-x2)+pdflist[[k1+1]]*x2,p1=p11]];
dB2[[i,j]]=mag;
pdB2[[i,j]]=N[p1*p2],{i,1,np},{j,1,steps}];

pdB=pdB*threshold;
pdB2=pdB2*threshold;
If[debugflag==1,Print["End GenerateMagPhase"]];
{dB,dB2,pdB,pdB2}]

vec=RandomVariate[ParetoDistribution[2,2,1],250];
{xa, xb, ratios, extenlst, intlist, pdflist, outlst}=getData[0,vec,8192,1,0];
{dB,pdB,phasedistpdf}=generateMagPhase[vec,intlist,pdflist,outlst,xa,xb,4000,50,.5,0]

dB

pdB

phasedistpdf

generateTemperatures

(* All Rights Reserved - CopyRight 2012, Richard John Belshaw, AGU,AAAS,ASA,IEEE,ACS,ACM*)

ClearAll[generateTemperatures]; (* 11/6/2012 and 12/10/2012 and 12/11/2012 where s0 is initial price *)

generateTemperatures[dB_List?MatrixQ,s0_,coeffs_]:=Module[{temperatures,i,j,np,steps},
{np,steps}=Dimensions[dB];
temperatures=ConstantArray[0,{np,steps}];
i=2;
temperatures[[1;;np,1]]=s0;
Do[
Do[temperatures[[i,j]]=temperatures[[i,j-1]]*dB[[i,j]],{j,2,steps}],{i,1,np}];
Do[Do[temperatures[[i,j]]=temperatures[[i,j]]+coeffs[[1]]*j,{j,1,steps}],{i,1,np}];

temperatures]

generateTemperatures[RandomReal[{0.95,1.05},{10,5}],21.2,10,5]

calculateConfLevels

(* All Rights Reserved - CopyRight 2012, Richard John Belshaw, AGU,AAAS,ASA,IEEE,ACS,ACM*)

ClearAll[calculateConfLevels]; (* 11/11/2012 *)

calculateConfLevels[temperatures_List?MatrixQ,pdB_List?MatrixQ,k7_,dis_List, negFlag_Integer,simpleflag_Integer] /; (negFlag==1||negFlag==0):=Module[{np,steps,conf01,conf10,conf25,conf60,conf50,conf75,conf90,conf99,temp1,columnindx,temper2,i,j,ratio,temp3,temp2,sumval1,k,sumval2,ratio33,ratio50,ratio80,ratio99,confarray,conford,sumval3,sumval4,temp5,temp6,sumval5,sumval6,indxlist,temp4,p1,p2,columnord,ratioALLC},
{np,steps}=Dimensions[temperatures];
columnindx = ConstantArray[0,np];
conf10=conf25=conf50=conf75=conf90=conf99=conf01=ConstantArray[0.0,steps];
confarray = ConstantArray[0,{np,steps}];
conford = ConstantArray[0,{np,steps}];


Do[
temp1=temperatures[[1;;np,j]];columnindx=Sort[temp1];columnord = Ordering[temp1];
i=Floor[.01*np+0.5];If[i<1,i=1];
conf01[[j]]=columnindx[[i]];
i=Floor[.05*np+0.5];
conf10[[j]]=columnindx[[i]];
i=Floor[.25*np+0.5];
conf25[[j]]=columnindx[[i]];
i=Floor[.5*np+0.5];
conf50[[j]]=columnindx[[i]];
i=Floor[.75*np+0.5];
conf75[[j]]=columnindx[[i]];
i=Floor[.95*np+0.5];
conf90[[j]]=columnindx[[i]];
i=Floor[.99*np+0.5];
conf99[[j]]=columnindx[[i]];
confarray[[1;;np,j]] = columnindx;
conford[[1;;np,j]] = columnord;
,{j,1,steps}];

If[simpleflag==0,
ratio = ConstantArray[0,steps];
indxlist= ConstantArray[0,198];
p2 = ConstantArray[0,198];
p1 = ConstantArray[0,steps];
sumval1=sumval2=ConstantArray[0.0,{198,steps}];
sumval3=sumval4=ConstantArray[0.0,198];
sumval5=sumval6=ConstantArray[0.0,{198,steps}];
Clear[temp1,temp3,temp5,temp6];
temp1=temp3=ConstantArray[0.0,steps];
temp5=temp6=ConstantArray[0.0,steps];
ratioALLC = ConstantArray[0.0,198];
Clear[temp2,temp4];
temp2 = ConstantArray[0.0,{198,steps}];
temp4=ConstantArray[0.0,{198,steps}];
Do[p2[[j]] =( .005*j),{j,1,198}];
Do[k=Floor[(.005*j)*np];Do[indxlist[[j]] = p2[[j]];p1[[i]]=pdB[[conford[[k,i]],i]];  temp1[[i]] =( confarray[[k,i]]-k7);If[temp1[[i]]<0.0,temp1[[i]]=10^(-20)];temp5[[i]]=temp1[[i]]/dis[[i]];temp1[[i]]=temp1[[i]]*p1[[i]]/dis[[i]]; 

temp3[[i]] = (k7-confarray[[k,i]]);If[temp3[[i]]<0.0,temp3[[i]]=10^(-20)];temp6[[i]]=temp3[[i]]/dis[[i]];temp3[[i]]=p1[[i]]*temp3[[i]]/dis[[i]];
sumval1[[j,i]]= temp1[[i]];sumval5[[j,i]]=temp5[[i]];sumval2[[j,i]] = temp3[[i]];sumval6[[j,i]]=temp6[[i]] ,{i,1,steps}];sumval3[[j]] = Total[sumval5[[j,1;;steps]]];sumval4[[j]]=Total[sumval6[[j,1;;steps]]],{j,1,198}];

Clear[temp3,temp1] ;
If[debugflag==1,Print["*2a"]];
Do[temp1 = Total[sumval1[[1;;198,i]]];temp2=Total[sumval2[[1;;198,i]]];If[temp2<=0.0,temp2 =10^(-20)];temp3 =temp1/(10^(-20)+temp2);
          
	ratio[[i]]=If [temp3<0,If [negFlag==1,-N[1/(1+Abs[temp3])*100.],N[Abs[temp3]/(1+Abs[temp3])*100.]],If[negFlag==1,-N[1/(1+temp3)*100],N[temp3/(1+temp3)*100.]]],{i,1,steps}];
Do[temp3 = N[sumval3[[j]]/(sumval4[[j]]+10^(-20))]; ratioALLC[[j]]  =If [temp3≥0.0,If[negFlag==0,N[temp3/(1+temp3)*100.],-N[1/(1+temp3)*100]],If [negFlag==1,-N[1/(1+Abs[temp3])*100.],N[Abs[temp3]/(1+Abs[temp3])*100.]]],{j,1,198}];
If[negFlag==1,
Do[ratioALLC[[j]]=N[-100.0-ratioALLC[[j]]],{j,1,198}]];
ratio33=ratioALLC[[66]];ratio50=ratioALLC[[100]];ratio80=ratioALLC[[160]];
ratio99 = ratioALLC[[198]]];
If[simpleflag==1,{conf01,conf10,conf25,conf50,conf75,conf90,conf99,p2},
{conf01,conf10,conf25,conf50,conf75,conf90,conf99,indxlist,ratioALLC,ratio,ratio33,ratio50,ratio80,ratio99}]]

calculateConfLevels[generateTemperatures[RandomReal[{0.95,1.05},{10,5}],21.2,10,5]]

198*.005

calculateFutureValues

(* All Rights Reserved - CopyRight 2012, Richard John Belshaw, AGU,AAAS,ASA,IEEE,ACS,ACM*)

ClearAll[calculateFutureValues];(*s0 initial price,k7 strike price,r int rate,d discount rate,infl inflation rate,T is time ratio,{np,steps} is dimensions of Temperatures,dB,pdB, Feb 21 later 2013 *)

calculateFutureValues[PriceData_List,temperatures_List?MatrixQ,pdB_List?MatrixQ,r_Real,s0_?NumberQ,k7_?NumberQ,dis_List,T_?NumberQ,debugflag_Integer]/;(debugflag==1||debugflag==0):=Block[{np,steps,confcall10,confcall50,confcall60,confcall90,confput10,confput50,confput60,confput90,Tvalforwardup,Tvalforwarddown,valueforwardup,valueforwarddown,meanpath,i,sumprob,L,h7=1.,j,newpassedthresholdforwarddown,newpassedthresholdforwardup,v,valsup,lengthsup,temp,valsdown,lengthsdown,nup,ndown,indx,count1,count2,TvalForwarddown,TvalForwardup,pi=4 ArcTan[1],p,phase,newpassedthresholdsindown,newpassedthresholdsinup,indxup,indxdown,valuesindownd,valuesinupd,temp1,k,callup,calldown,confcall,confput,callup1,calldown1,sigma,deltacall,deltaput,temp2,p1,p2,sumprob1,t1,t2,valsupord,valsdownord,sumval,callup2,diffprob,calldown2,call2,put2},{np,steps}=Dimensions[temperatures];
If[debugflag==1,Print["StartCalcFutureValues"]];

i=1;
If [debugflag==1,Print["1"]];
sumprob=ConstantArray[0,steps];L=steps;
If[debugflag==1,Print["2"]];
Do[sumprob[[j]]=Re[Total[pdB[[1;;np,j]]]];If[sumprob[[j]]== 0, sumprob[[j]]=10^(-100)],{j,1,steps}];
If[debugflag==1,Print["3"]];
meanpath=ConstantArray[0,steps];

Do[meanpath[[j]]=Total[pdB[[1;;np,j]]*temperatures[[1;;np,j]]]/sumprob[[j]],{j,1,steps}];
If[debugflag==1,Print["4"]];
diffprob=ConstantArray[0.0,steps];
Do[diffprob[[j]] = diffprob[[j]] + pdB[[i,j]]*Abs[(meanpath[[j]]-temperatures[[i,j]])]/sumprob[[j]],{j,1,steps},{i,1,np}];
If[debugflag==1,Print["5"]];
newpassedthresholdforwarddown=ConstantArray[0,{np,steps}];
newpassedthresholdforwardup=ConstantArray[0,{np,steps}];
newpassedthresholdsindown=ConstantArray[0,steps];
newpassedthresholdsinup=ConstantArray[0,steps];
Clear[sigma];

Do[v=meanpath[[j]]-k7;

If[v>0,newpassedthresholdsinup[[j]]=v,newpassedthresholdsinup[[j]]=0];
v=-v;
If[v>0,newpassedthresholdsindown[[j]]=v,newpassedthresholdsindown[[j]]=0],{j,1,steps}];

Do[
Do[ v=temperatures[[i,j]]-k7;

If[v>0,newpassedthresholdforwardup[[i,j]]=v,newpassedthresholdforwardup[[i,j]]=0];
v=-v;
If[v>0,newpassedthresholdforwarddown[[i,j]]=v,newpassedthresholdforwarddown[[i,j]]=0],{j,1,steps}],{i,1,np}];
valueforwarddown=ConstantArray[0,steps];
valueforwardup=ConstantArray[0,steps];
valuesindownd=ConstantArray[0,steps];
valuesinupd=ConstantArray[0,steps];


valsup=ConstantArray[0,{np,steps}];
valsupord = ConstantArray[0,{np,steps}];
indxup=ConstantArray[0,{np,steps}];
temp1 =  ConstantArray[0,np];
lengthsup=ConstantArray[0,steps];
Do[k=1;
Do[If[newpassedthresholdforwardup[[i,j]]>0,indxup[[k,j]]=i;
k=k+1],{i,1,np}];
k=k-1;
temp=Sort[newpassedthresholdforwardup[[indxup[[1;;k,j]],j]]];
valsupord[[1;;k,j]]=Ordering[newpassedthresholdforwardup[[indxup[[1;;k,j]],j]]];
lengthsup[[j]]=k;
valsup[[1;;k,j]]=temp,{j,1,steps}];

valsdown=ConstantArray[0,{np,steps}];
valsdownord = ConstantArray[0,{np,steps}];
lengthsdown=ConstantArray[0,steps];
indxdown = ConstantArray[0,{np,steps}];
Do[k=1;
Do[If[newpassedthresholdforwarddown[[i,j]]>0,indxdown[[k,j]]=i;
k=k+1],{i,1,np}];
k=k-1;
temp=Sort[newpassedthresholdforwarddown[[indxdown[[1;;k,j]],j]]];
valsdownord[[1;;k,j]]=Ordering[newpassedthresholdforwarddown[[indxdown[[1;;k,j]],j]]];
lengthsdown[[j]]=k;
valsdown[[1;;k,j]]=temp,{j,1,steps}];
confcall10=confcall50=confcall60=confcall90=confput10=confput50=confput60=confput90=ConstantArray[0,steps];

Do[nup=lengthsup[[j]];
If[nup>0,indx=Floor[0.1*nup+.5];If[indx<1,indx=1];
confcall10[[j]]=valsup[[indx,j]];
indx = Floor[.5*nup+.5];
confcall50[[j]] = valsup[[indx,j]];
indx = Floor[.6*nup+.5];
confcall60[[j]]=valsup[[indx,j]];
indx=Floor[0.9*nup+0.5];
confcall90[[j]]=valsup[[indx,j]]];
ndown=lengthsdown[[j]];
If[ndown>0,indx=Floor[0.1*ndown+.5];If [indx < 1, indx =1];
confput10[[j]]=valsdown[[indx,j]];
indx = Floor[.5*ndown+.5];
confput50[[j]]=valsdown[[indx,j]];
indx = Floor[.6*ndown+.5];
confput60[[j]] = valsdown[[indx,j]];
indx=Floor[0.9*ndown+0.5];
confput90[[j]]=valsdown[[indx,j]]],{j,1,steps}];


callup = ConstantArray[0,{198*2+1,steps}];
callup2 = ConstantArray[0,{198*2+1,steps}];
callup1 = ConstantArray[0,steps];
calldown = ConstantArray[0,{198*2+1,steps}];
calldown2 = ConstantArray[0,{198*2+1,steps}];
calldown1 = ConstantArray[0,steps];
t1 = ConstantArray[0,steps];
t2 = ConstantArray[0,steps];
p2 = ConstantArray[0,2*198+1];
If[debugflag==1,Print["6"]];
Do[p=.005+.0025*k;If[p>.5,p2[[k]]=1-p,p2[[k]]=p],{k,0,2*198}];
Do[nup = lengthsup[[j]];ndown=lengthsdown[[j]];Do[ p=.005+.0025*k;
If[nup>0,indx =Floor[p*nup+.5];If[indx<1,indx=1];p1=pdB[[valsupord[[indx,j]],j]];callup2[[k+1,j]] = valsup[[indx,j]];callup[[k+1,j]] =p2[[k]]*p1*valsup[[indx,j]],callup[[k+1,j]]=callup2[[k+1,j]] = 0];
t1[[j]]=t1[[j]]+p1*p2[[k]];
If[ndown>0,indx=Floor[p*ndown+.5];If[indx<1,indx=1];p1=pdB[[valsdownord[[indx,j]],j]];calldown2[[k+1,j]]=valsdown[[indx,j]];calldown[[k+1,j]] = p2[[k]]*p1*valsdown[[indx,j]],calldown2[[k+1,j]]=calldown[[k+1,j]]=0];t2[[j]]=t2[[j]]+p1*p2[[k]],{k,0,2*198}],{j,1,steps}];
Clear[temp2];

If[debugflag==1,Print["7"]];
Do[nup = lengthsup[[j]];ndown=lengthsdown[[j]];
If [nup>0,Clear[sumval,temp2];{sumval,temp2} =getIntegrate2[callup[[1;;2*198+1,j]],1,1,2*198+1];callup1[[j]]=sumval/(t1[[j]]+10^(-100))/dis[[j]],callup1[[j]] = 0];
If [ndown>0,Clear[sumval,temp2];{sumval,temp2} = getIntegrate2[calldown[[1;;2*198+1,j]],1,1,2*198+1];calldown1[[j]]=sumval/(t2[[j]]+10^(-100))/dis[[j]],calldown1[[j]]=0],{j,1,steps}];
If[debugflag==1,Print["8"]];
Clear[temp2,confcall,confput];
{confcall,temp2}=getIntegrate2[callup1,1,1,steps];Clear[temp2];{confput,temp2}=getIntegrate2[calldown1,1,1,steps];
            confcall = N[confcall/steps];confput=N[confput/steps];
call2 =N[callup1[[steps]]];put2=N[calldown1[[steps]]];
If[debugflag==1,Print["9"]];
Clear[temp2,callup,calldown,calldown1,callup1,t1,t2,valsupord,valsdownord,valsup,valsdown];


Do[valuesinupd[[j]]=newpassedthresholdsinup[[j]]/dis[[j]];
valuesindownd[[j]]=newpassedthresholdsindown[[j]]/dis[[j]];
nup= lengthsup[[j]];
valueforwardup[[j]]=Re[Total[pdB[[indxup[[1;;nup,j]],j]]*newpassedthresholdforwardup[[indxup[[1;;nup,j]],j]]]/sumprob[[j]]]/dis[[j]];
ndown= lengthsdown[[j]];
valueforwarddown[[j]]=Re[Total[pdB[[indxdown[[1;;ndown,j]],j]]*newpassedthresholdforwarddown[[indxdown[[1;;ndown,j]],j]]]/sumprob[[j]]]/dis[[j]],{j,1,steps}];
If[debugflag==1,Print["10"]];
If[debugflag==1,Print["FinishedCalcFutureValues"]];
{callup2,calldown2,call2,put2,confcall,confput,confcall10,confcall50,confcall60,confcall90,confput10,confput50,confput60,confput90,valueforwardup,valueforwarddown,valuesinupd,valuesindownd,meanpath,diffprob}]

N[1/198]

googlePrices

(* All Rights Reserved - CopyRight 2012, Richard John Belshaw, AGU,AAAS,ASA,IEEE,ACS,ACM*)

ClearAll[googlePrices]; (* Google calls prices from last to first eg {last price,....,earliest price} *)
googlePrices[stockTicker_String,startDate:(_List|_String),endDate:(_List|_String),dataType_String:"Close"]:=Module[{price,volume,exportFormat="csv",newDataType},
(* Importing SeasData from Google 
If[And @@ NumericQ /@ startDate,startDate=DateString[startDate,{"MonthNameShort"," ","Day",",","Year"}],startDate=DateString[startDate,{"MonthNameShort"," ","Day",",","Year"}]];
If[And @@ NumericQ /@ endDate,endDate=DateString[endDate,{"MonthNameShort"," ","Day",",","Year"}],endDate=DateString[endDate,{"MonthNameShort"," ","Day",",","Year"}]];
ds=Import[StringJoin["http://finance.google.com/finance/historical?q=",stockTicker,"&startdate=",startDate,"&enddate=",endDate,"&output=",exportFormat], "Data"]; *)
newDataType=Switch[dataType,"Open"|"open","Open","High"|"high"|"hi"|"Hi","High","Low"|"low"|"Lo"|"lo","Low","Close"|"close","Close",_,dataType];
(* ds=FinancialData[stockTicker,"OHLCV",{startDate,endDate}];
{ds, SeasData}=FinancialData[stockTicker,#,{startDate,endDate}]& /@ {"OHLCV",newDataType};;*)
price=FinancialData[stockTicker,newDataType,{startDate,endDate}];
volume = FinancialData[stockTicker,"Volume",{startDate,endDate}]; {price,volume}]

ClearAll[googlePrices]; (* Google calls prices from last to first eg {last price,....,earliest price} *)
googlePrices[stockTicker_String,startDate:(_List|_String),endDate:(_List|_String),dataType_String:"Close",googleflag_Integer,debugflag_Integer]:=Module[{price,volume,exportFormat="csv",errflag,newDataType,string1,L,ds,date1,vol,pr},
If [googleflag==1,
Off[DateList::ambig];
string1 = StringJoin["http://finance.google.com/finance/historical?q=", stockTicker ,",&startdate=", startDate ,",&enddate=", endDate ,",&output=csv"];
If[debugflag==1,Print[string1]];
errflag =0;
Clear[ds];
ds=URLExecute[string1,VerifySecurityCertificates->True];
If[debugflag==1,Print["*1"]];
If [ds=={},
Print["No Market Data"];
volume=price = ConstantArray[{},Dimensions[ds][[1]]-1];
errflag=1;,
If[Dimensions[ds][[1]]== 0 && Dimensions[ds][[2]]== 0,
Print["No Market Data"];
volume=price = ConstantArray[{},Dimensions[ds][[1]]-1];
errflag=1;]];
If[debugflag==1,Print["*2"]];
If[errflag==0,
If[debugflag==1,Print["*3"]];


date1 = ConstantArray[{},Dimensions[ds][[1]]-1];
vol=pr=ConstantArray[0,Dimensions[ds][[1]]-1];
volume=price = ConstantArray[{},Dimensions[ds][[1]]-1];
If [debugflag==1,Print["*4"]];

L=Length[vol];
Do[vol[[i]]=ds[[i+1]][[6]],{i,1,L}];
vol = Reverse[vol];

(* Importing SeasData from Google 
If[And @@ NumericQ /@ startDate,startDate=DateString[startDate,{"MonthNameShort"," ","Day",",","Year"}],startDate=DateString[startDate,{"MonthNameShort"," ","Day",",","Year"}]];
If[And @@ NumericQ /@ endDate,endDate=DateString[endDate,{"MonthNameShort"," ","Day",",","Year"}],endDate=DateString[endDate,{"MonthNameShort"," ","Day",",","Year"}]];
ds=Import[StringJoin["http://finance.google.com/finance/historical?q=",stockTicker,"&startdate=",startDate,"&enddate=",endDate,"&output=",exportFormat], "Data"]; *)
newDataType=Switch[dataType,"Open"|"open","Open","High"|"high"|"hi"|"Hi","High","Low"|"low"|"Lo"|"lo","Low","Close"|"close","Close",_,dataType];
(* ds=FinancialData[stockTicker,"OHLCV",{startDate,endDate}];
{ds, SeasData}=FinancialData[stockTicker,#,{startDate,endDate}]& /@ {"OHLCV",newDataType};;*)
Switch[newDataType,"Open",Do[pr[[i]]=ds[[i+1]][[2]],{i,1,L}];,"High",Do[pr[[i]]=ds[[i+1]][[3]],{i,1,L}];,"Low",Do[pr[[i]]=ds[[i+1]][[4]],{i,1,L}];,"Close",Do[pr[[i]]=ds[[i+1]][[5]],{i,1,L}];,_,Do[pr[[i]]=ds[[i+1]][[5]],{i,1,L}];];
pr = Reverse[pr];

Do[date1[[i]]=ds[[i+1]][[1]],{i,1,L}];
date1 = Reverse[date1];
Do[price[[i]] = {date1[[i]],pr[[i]]};volume[[i]]={date1[[i]],vol[[i]]};,{i,1,L}];];
,
Off[DateList::ambig];
newDataType=Switch[dataType,"Open"|"open","Open","High"|"high"|"hi"|"Hi","High","Low"|"low"|"Lo"|"lo","Low","Close"|"close","Close",_,dataType];

price=FinancialData[stockTicker,newDataType,{startDate,endDate}];
volume = FinancialData[stockTicker,"Volume",{startDate,endDate}];
If [Length[price]==0 && Length[volume]==0,
Print["No Market Data"];
errflag=1;
];

];
  
If [debugflag==1,Print[price];Print[volume];];
  {price,volume,errflag}]

{dddData,Volume,errflag}=googlePrices["CSC","05/05/14","05/04/16","Close",1,1]

DateListPlot[dddData]

optionPrices

(* All Rights Reserved - CopyRight 2012, Richard John Belshaw, AGU,AAAS,ASA,IEEE,ACS,ACM*)

ClearAll[optionPrices];

optionPrices[directry_String:"C:\\Users\\Chondrally\\Documents",tick1_String:"DDD",tick2_String:"DDD",dataType_String:"Close",YearsBack_:1,StartDate_Integer:0,Legs_List,inflation_,interestRate_,dividend_,ppast_,paths_Integer,IndicatorPaths_Integer,extendflag_Integer:1,catastropheflag_Integer:0,forecastindicatorflag_Integer:0,currencyflag_Integer,SeasonalFlag_Integer:0,SeasonalDays_Integer:20,nodeslayer_List,optionflag_Integer:2,googleflag_Integer,debugflag_Integer:0]:=Module[{enddate,datatype,ds,data,expdate,s0,BDAYS,days,year,T,SpotPrice,infl,r,d,futuresteps,xa, xb, ratios, phaselist, extenlst, intlist, pdflist, outlst, difflist,xa3, xb3,ya3,yb3, ratios3,  extenlst3, intlist3, pdflist3, outlst3, count1,count2,sumup,sumdown,rat1,rat2,pr,percChange,sumv1,intl1,tempd,sumv,intl,netGain,plotPrices,plotpdf,dB, pdB,i,j,count,dis,confcall10,confcall90,confput10,confput90, Tvalforwardup, Tvalforwarddown,valueforwardup,valueforwarddown, temperatures,meanpath,val1,val2,val3,val4,y,m,futurearma,futurearma1,conf01,conf10,conf25,conf50,conf75,stockTicker,conf90,conf99,temp,temp2,temp3,s1,s2,ratio33,ratio50, ratio80,ratio99,vol1,Volume,voldiff,datadiff,pi,indicator,plotFutureCall,plotEMAs,plotFuturePut,plotConfLimits,plotMeanPath,valuesinupd,valuesindownd,coeffs,volatility,vol2,plotVolatility,cubPCR1,SeasData,plotFutureARMA,N1,sv,val0,val5,indicator2,temper2,neg50flag,neg80flag,neg98flag,numpts=8192,sumsame,count3,pr2,sma1,sma3,sma10,sma18,sma18v,ddd,ya,yb,temp4,temp5,temp6,temp7,temp8,temp9,temp10,temp11,plotEMAs2,sma1v,sma3v,sma10v,dB3,pdB3,meanpath3,meanpath10,meanpath18,meanpath3v,meanpath10v,meanpath18v,temperatures3,indicatorspredict,indicatorspredict2,numbersteps,numpts2,data2,meanpath2,meanpath22,indicator3,indicator4,meanpath1,meanpath1v,phasedistpdf3,phasedistpdf,phaseplot,confema310,confema390,confema3v10,confema3v90,delta1,delta2,conf60,confput60,indx1,indx2,confcall60,confcall50,confput50,val6,val7,val8,val9,indxfirst,indxlast,maxval,indicatorpredictplain,indicatorpredict2plain,forecastindicatordays,indxlist,MaxRatio,negFlag,ratio,confcall,confput,VolumePlot,PercentWinPlot,callup,calldown,CallupPlot,CalldownPlot,img,k,kmax,PercentWincallputPlot,callputratio,CallPutRatioPlot,callputratioALL,dt,sumval1,MostProbPerc,threspoint9,threspoint8,threspoint7,threspoint6,threspoint5,threspoint4,imagepoint9,imagepoint8,imagepoint7,imagepoint6,imagepoint5,imagepoint4,dBpoint1,pdBpoint1,totalprob,sumprob,thres1point1,thres1point2,thres1point3,thres1point4,thres1point5,thres1point6,image1point1,image1point2,image1point3,image1point4,image1point5,image1point6,totalprob1,totalprob2,dB2,pdB2,sumprob1,sumprob2,temperatures1,temperatures2,paths1,paths2,timestamp1,timestamp2,EMA200,EMA40,ratioMA,price,StartDate2,call1,put1,call2,put2,Seasonalenddate,SeasonalData1,SeasonalVolume1,YearData,YearData2,YrVolume2,YrData2,YearVolume2,YrData,YrVolume,YearVolume,SeasVolume,actdata,StartDate3,StartDate4,SeasonalData2,position,SeasonalVolume2,YearDateData,SeasonalDateData,DateData,FortyBDAYS,StartDate5,YearDateData2,EMA40a,EMA200a,IntegrateMeanpath3,upData,UpData,L,DownData,downData,downVol,upVol,RSIdata,PlotIntMean3,sgn1,sdev1,sdev2,MeanUp,MeanDown,datatype2,EMAN2,Upper,Lower,Percb,BandWidth,DPOResult,BuySignal,plotRSI,plotMACD,plotBollinger,plotPercb,plotBandWidth,plotDPO,callBS,putBS,DeltaCall,DeltaPut,Gamma2,Vega,ThetaCall,ThetaPut,RhoCall,RhoPut,PercK,percD,percDslow,plotPercK,Momentum,plotMoment,VolEMA2,VolEMA3,VolEMA9,plotVolEMA,RT,plotRT,RTPercPrice,RTPercVol,plotRTPrcPrc,plotRTPrcVol,IntPercPriceRT,IntPercVolRT,plotIntRTPrc,plotIntRTVol,IntRT,plotIntRT,RTpred,plotRTpred,RTPrcpred,RTPrcpred2,intRTPrcpred2,plotintRTPrcpred2, plotRTPrcpred,RTVolpred,intRTVolpred2,plotintRTVolpred,RTVolpred2,futurepath,plotRTVolpred,DPOPred,DPOPred2,plotDPOpred,MACDpred,MACDpred2,plotMACDpred,N3,ratioALLC,minmpe,minval,futureA,futurew1,futurew2,futurew3,futurew4,DPOA,DPOw1,DPOw2,DPOw3,DPOw4,MACDA,MACDw1,MACDw2,MACDw3,MACDw4,RTPrcA,RTPrcw1,RTPrcw2,RTPrcw3,RTPrcw4,RTVolA,RTVolw1,RTVolw2,RTVolw3,RTVolw4,futureA2,futurew12,futurew22,futurew32,futurew42,DPOA2,DPOw12,DPOw22,DPOw32,DPOw42,MACDA2,MACDw12,MACDw22,MACDw32,MACDw42,RTPrcA2,RTPrcw12,RTPrcw22,RTPrcw32,RTPrcw42,RTVolA2,RTVolw12,RTVolw22,RTVolw32,RTVolw42,ACCA,ACCw1,ACCw2,ACCw3,ACCw4,ACCA2,ACCw12,ACCw22,ACCw32,ACCw42,ACCpred,intACCpred,plotintACCpred,EMA3ACC,str,temp1,debugflag2,inneriterations,rho,toler,numpasses,datelisttemp1,datelisttemp2,minrmse,deTrendflag,plotNetForecast1,plotNetForecast2,futurearma3,EMA3,MarketIncrease,MarketDecline,MArketAccumulation,Accumulation,plotAccumulation,plotACCpred,DateData2,DateData3,diffprob,probofMeanPath,flaga,flagb,callfourier,putfourier,futurearma4,callputRATFour,PercWinFour,plotDailyAcc,DailyACCpred,intDailyACCpred,plotintDlyACCpred,DailyAcc,plotDailyACCpred,DACCA,DACCw1,DACCw2,DACCw3,DACCw4,DACCA2,DACCw12,DACCw22,DACCw32,DACCw42,intDPOpred,plotintDPOpred,dwt,dwtpredict,dwtdata,dwd,avg,kelly,tempt,plotDiffprob,uppersdv,lowersdv,sigma,dims,VolumeDataFlag,temp12,Bollingerpredict,FourierRSI,plotFourierRSI,MinAccumulation,MinPercPriceRT,MinPercVolRT,p,odds,kelly2,kellyfourier,busdays,kellyfourier2,plot1,plot2,plot3,strikes,Expiries,OptionCounts,ExpDate,OptionTypes,calla,puta,callb,putb,callc,putc,calld,putd,calle,pute,profit2,plotProfit2,profit,plotProfit,kellys,OverallKellyMP,OverallKellyFourier,leastpurseerr,xa4,xb4,ratios4,extenlst4,intlist4,pdflist4,outlst4,dB4,pdB4,phasedistpdf4,callup4,calldown4,call24,put24,confcall4,confput4,confcall104,confcall504,confcall804,confcall904,confput104,confput504,confput804,confput904,valueforwardup4,valueforwarddown4,valuesinupd4,valuesindownd4,meanpath4,diffprob4,temperatures4,conf014,conf104,conf254,conf504,conf754,conf904,conf994,indxlist4,ratioALLC4,sumval14,ratio334,ratio504,ratio804,ratio994,coeffs1,errflag,conffp10,conffp90,conffp50,dwtpredict2,temp20,temp21,plotFutureARMA2,futurepath2},




(*this code simply sets all the input text fields to blank upon pressing the calculateplots button *)
timestamp1 = DateString[];
Print["timestamp1 = ",timestamp1];
deTrendflag=1;
If [tick2 == "",stockTicker = tick1, stockTicker = tick2];
debugflag2=1;
strikes = ConstantArray[0,4];
Expiries=ConstantArray["",4];
OptionCounts = ConstantArray[0,4];
OptionTypes = ConstantArray["",4];
strikes = Legs[[1]];
Expiries = Legs[[2]];
OptionCounts=Legs[[3]];
OptionTypes=Legs[[4]];
busdays=ConstantArray[0,4];
Do[
If [StringLength[Expiries[[i]]]>0,
busdays[[i]]=Length[Cases[DayName /@ Table[DatePlus[Take[DateList[],3],i],{i,0,DayCount[Take[DateList[],3],Take[DateList[Expiries[[i]]],3]]}],Except[Saturday|Sunday]]];,busdays[[i]]=0;
];,{i,1,4}];
futuresteps = Max[busdays];
Do[If[busdays[[i]]== futuresteps, ExpDate=Expiries[[i]]];,{i,1,4}];
(*get the expiration date,or final date for forecasting to for the option or the forecast*)
expdate=ExpDate;
(* get the last days price,or volume value *)


(*this code just gets todays date in a particular format mm/dd/yyyy*)
(* a special matlab function that computes the business days between todays date and the expiration date *)

BDAYS=futuresteps;

(*compute the length of this array to get the total number of such days*)
days=futuresteps;
(*get the number of business days in the current year*)
year=Length[Cases[DayName /@ Table[DatePlus[{2013,1,1},i],{i,0,DayCount[{2013,1,1},{2013,12,31}]}],Except[Saturday|Sunday]]]-9;
(*ratio of number of business days till expiration to total number of business days in current year*)
Off[DateList::ambig];
enddate=DateString[{"Month", "/","Day","/","Year"}];
FortyBDAYS =Floor[N[(SeasonalDays+2)/year*365.0+.999]];
StartDate3=DateString[DatePlus[enddate,-365*YearsBack+1-StartDate],{"Month","/","Day","/","Year"}];

If[StartDate==0,If[SeasonalFlag==1,StartDate2 = DateString[DatePlus[StartDate3,-FortyBDAYS],{"MonthName","/","Day","/","Year"}];
StartDate4=DateString[DatePlus[enddate,-FortyBDAYS],{"MonthName","/","Day","/","Year"}];Seasonalenddate =StartDate3;StartDate5=StartDate2,StartDate5=StartDate3;StartDate2=StartDate3;StartDate4=StartDate3]];

If [StartDate >0,StartDate5=DateString[DatePlus[enddate,-StartDate],{"MonthName","/","Day","/","Year"}];StartDate2=DateString[DatePlus[enddate,-StartDate],{"MonthName","/","Day","/","Year"}];StartDate4=DateString[DatePlus[enddate,-StartDate],{"MonthName","/","Day","/","Year"}];
If[debugflag==1,Print[enddate,StartDate2,StartDate3,StartDate4]];];
(*this code gets whether we are working with price SeasData or volume SeasData ie.datatype is either'hi','open','lo','close' or'vol'*)
datatype=Switch[dataType,"Open"|"open","Open","High"|"high"|"hi"|"Hi","High","Low"|"low"|"Lo"|"lo","Low","Close"|"close","Close",_,dataType];
(*this code sets the number of paths (a) to forecast to be at least 32768 if volume time series is chosen*)(*and the number of paths (a) to calculate is set to 16384*)

(*get the stock ticker symbol from the text input fieldd*)
(*get one years worth of SeasData,either volume or price SeasData*)


(* put it into yesterdays price or volume input field for user viewing, priceVolumeInputField=ToString[s0];*)


(*get the strike price from the input text field*)

SpotPrice=0; (* 35.5 *)
(*get the inflation rate from the input text field*)
infl=inflation; (* 0.05 *)
(*get the risk free interest rate from the input text field*)
r=interestRate; (* 0.03 *)
(*get the continuous dividend rate from the input text field*)
d=dividend; (* 0.0 *)

(*set the number of futuresteps to calculate to be the number of business days until expiration date*)
T=N[futuresteps/year];
forecastindicatordays = futuresteps;
dt =N[T/futuresteps];
j=3;
If[debugflag==1,Print["futuresteps = ",futuresteps]];
dis=ConstantArray[0.0,futuresteps];
dis[[1]]=1.0;
dis[[2]]=N[(1.0+(r+infl-d)*dt)];
If[debugflag==1,Print["dis[[1]]= ",dis[[1]],"  ,dis[[2]] = ",dis[[2]]]];
While[j≤futuresteps,dis[[j]]=dis[[j-1]]*dis[[2]];
j=j+1];

If [SeasonalFlag==1,{SeasonalData1,SeasonalVolume1,errflag}=googlePrices[stockTicker,StartDate2,Seasonalenddate,datatype,googleflag,debugflag];
If[errflag==1,Print["No Market Data";];,return;];
{SeasonalData2,SeasonalVolume2,errflag}=googlePrices[stockTicker,StartDate4,enddate,datatype,googleflag,debugflag];

If[errflag==1,Print["No Market Data";];,return;];
];

If[debugflag==1,Print[StartDate3,enddate];];
{YearData,YearVolume,errflag}=googlePrices[stockTicker,StartDate3,enddate,datatype,googleflag,debugflag];
If[errflag==1,Print["No Market Data";];,return;];
If [debugflag==1,
Print[Dimensions[YearData],Dimensions[YearVolume]];];
{YearData2,YearVolume2,errflag}=googlePrices[stockTicker,StartDate5,enddate,datatype,googleflag,debugflag];
If[errflag==1,Print["No Market Data";];,return;];

If [Length[YearData]>240,
If[debugflag==1,Print["*0, ",Length[YearData],YearData]];
If[SeasonalFlag==1,
SeasData =Join[Transpose[SeasonalData1][[2]],Transpose[SeasonalData2][[2]]];SeasVolume = Join[Transpose[SeasonalVolume1][[2]],Transpose[SeasonalVolume2][[2]]];SeasonalDateData = Join[Transpose[SeasonalData1][[1]],Transpose[SeasonalData2][[1]]];]
Clear[VolumeDataFlag];
VolumeDataFlag=0;
If[Length[YearVolume]== 0||Mean[Transpose[YearVolume][[2]]]<10,
Print["No Volume Data"];
VolumeDataFlag=1;
];

YrData = Transpose[YearData2][[2]];
YrData2=Transpose[YearData][[2]];
DateData2=Transpose[YearData][[1]];
YrVolume = Transpose[YearVolume][[2]];
Clear[temp1,temp2,temp3,temp4];
temp1 = matlabFind1[YrVolume,Greater,0.0];
temp2 = matlabFind1[YrData,Greater,0.0];
temp4=Intersection[temp1,temp2];
If[debugflag==1,Print[YrData2];Print[DateData2];Print[YrVolume];];

datelisttemp1=temp4;

If[debugflag==1,Print["**********datelistemp1=",datelisttemp1,Length[YrData]]];



YrVolume2=Transpose[YearVolume][[2]];
Clear[temp1,temp2,temp3,temp4];
temp1 = matlabFind1[YrVolume2,GreaterEqual,0.0];
temp2 = matlabFind1[YrData2,Greater,0.0];
temp4=Intersection[temp1,temp2];
datelisttemp2 = temp4;
If[debugflag==1,Print["***********datelisttemp2=",datelisttemp2,Length[YrData2]]];


Clear[temp1,temp2,temp3,temp4];
YearDateData = Transpose[YearData2][[1]];
YearDateData2=Transpose[YearData][[1]];
paths1 = Floor[numpts*252/2+.5];
If[debugflag==1,Print[paths1]];
s0=YrData[[-1]];
SpotPrice=s0;
Do[If[strikes[[i]]==0,strikes[[i]]=s0];,{i,1,4}];
If[SeasonalFlag==1,DateData=SeasonalDateData;Volume =SeasVolume; actdata = SeasData, DateData=YearDateData;Volume = YrVolume2; actdata=YrData2];
If[debugflag==1,Print["*1"]];

RSIdata = getRSI[YrData2,17]; 
If[debugflag==1,Print["*2"]];



BuySignal = getMACD[YrData2,26,12,9];
If[debugflag==1,Print["*3"]];

DPOResult = getDPO[YrData2,20];
If[debugflag==1,Print["*4"]];
Momentum = getMomentum[YrData2,20];
Clear[temp2];
{EMAN2,Upper,Lower,Percb,BandWidth}=getBollinger[YrData2,20,2.0];
Clear[Bollingerpredict];
If [debugflag==1,Print["*5a"]];
Clear[temp,temp1];
temp1 = Length[BandWidth];
If [debugflag==1,Print["*5aa"]];
temp = BandWidth[[50;;temp1]];
If [debugflag==1,Print["*5ab"]];
{plot2,Bollingerpredict} =  MusicFinal[temp,100,BandWidth[[-1]],Length[temp],0,debugflag];

If [debugflag==1,Print["*5ac"]];
BandWidth = Join[temp,Flatten[Bollingerpredict[[1,1;;100]]]];

If[debugflag==1,Print["*5b"]];

{PercK,percD,percDslow} = getStochastics[YrData2,14];
If[debugflag==1,Print["*6"]];


{VolEMA2,VolEMA3,VolEMA9}=getVolumeEMA[YrVolume2,2,3,5];,
VolEMA2=VolEMA3=VolEMA9=ConstantArray[0,Length[actdata]]];
If[debugflag==1,Print["*8"]];
{RT,RTPercPrice,RTPercVol,IntPercPriceRT,IntPercVolRT,IntRT,Accumulation,DailyAcc,MinAccumulation,MinPercPriceRT,MinPercVolRT}=getRT[YrData2,YrVolume2,debugflag];
If[debugflag==1,Print["*9"]];
If [Length[Accumulation]>2,
EMA3ACC = ConstantArray[0.0,Length[Accumulation]-2];
EMA3ACC[[1]]=N[ Total[Accumulation[[1;;3]]]/8];
Do[EMA3ACC[[i+1]]=N[1/2*Total[Accumulation[[i+1;;i+3]]]/3+1/2*EMA3ACC[[i]]],{i,1,Length[Accumulation]-3}];
,
EMA3ACC = ConstantArray[0,0];];

If[ currencyflag == 0,
voldiff = ConstantArray[0,Length[Volume]]];
datadiff = ConstantArray[0,Length[actdata]];
EMA3 = ConstantArray[0,Length[YrData2]-2];

Do[datadiff[[i]] = actdata[[i]],{i,1,Length[actdata]}];
If[debugflag==1,Print["datadiff=",datadiff]];
If[currencyflag ==0,
Do[voldiff[[i]] = Volume[[i]],{i,1,Length[Volume]}]];
temp2 = YrData[[-1]];
If [SeasonalFlag==1,temp3 = SeasData[[40]]; actdata[[1;;40]]= actdata[[1;;40]] -temp3+temp2;];

pi = ArcTan[1,1]*4;

indicator =N[datadiff];
If[debugflag==1,Print["*1"]];
If [currencyflag == 0,
temp = Max[Abs[voldiff]];
If[temp==0.0, temp=1.0];
indicator2 =N[voldiff/temp*20.],
indicator2 = RandomReal[{-.01,.01},Length[actdata]]];
If[debugflag==1,Print["*2"]];

If [forecastindicatorflag==1,
numbersteps = forecastindicatordays,numbersteps=0];
sma1 = ConstantArray[0,Length[actdata]+numbersteps];
sma3 = ConstantArray[0,Length[actdata]+numbersteps];
sma10 = ConstantArray[0,Length[actdata]+numbersteps];
sma18 = ConstantArray[0,Length[actdata]+numbersteps];
sma1v = ConstantArray[0,Length[actdata]+numbersteps];
sma3v = ConstantArray[0,Length[actdata]+numbersteps];
sma10v = ConstantArray[0,Length[actdata]+numbersteps];
sma18v = ConstantArray[0,Length[actdata]+numbersteps];

If[debugflag==1,Print["*^1"]];

Do [ sma1[[i+1]]= N[indicator[[i]]],{i,1,Length[indicator]}];
EMA3[[1]]=Total[YrData2[[1;;3]]]/3;
Do[EMA3[[i+1]]=N[1/2*Total[YrData2[[i+1;;i+3]]]/3+1/2*EMA3[[i]]],{i,1,Length[YrData2]-3}];
Do [ sma3[[i+3]]= N[1/2*Total[indicator[[i;;i+2]]/3]+ 1/2*sma3[[i-1+3]]],{i,1,Length[indicator]-2}];
Do[sma10[[i+9]] =N[ 2/10*Total[indicator[[i;;i+8]]/9]+ 8/10*sma10[[i-1+9]]],{i,1,Length[indicator]-8}];
Do[sma18[[i+18]] = N[2/19*Total[indicator[[i;;i+17]]/18]+17/19*sma18[[i-1+18]]],{i,1,Length[indicator]-17}];
If[VolumeDataFlag==0,
Do [ sma1v[[i+1]]= N[indicator2[[i]]],{i,1,Length[indicator2]}];
Do [ sma3v[[i+3]]= N[1/2*Total[indicator2[[i;;i+2]]/3] + 1/2*sma3v[[i-1+3]]],{i,1,Length[indicator2]-2}];
Do[sma10v[[i+9]] =N[ 2/10*Total[indicator2[[i;;i+8]]/9] + 8/10*sma10v[[i-1+9]]],{i,1,Length[indicator2]-8}];
Do[sma18v[[i+18]] = N[2/19*Total[indicator2[[i;;i+17]]/18]+17/19*sma18v[[i-1+18]]],{i,1,Length[indicator2]-17}];
];
If [forecastindicatorflag==1,
meanpath1 = ConstantArray[0,numbersteps];
meanpath1v = ConstantArray[0,numbersteps];
meanpath2 = ConstantArray[0,numbersteps];
meanpath22 = ConstantArray[0,numbersteps];
meanpath3 = ConstantArray[0,numbersteps];
meanpath10 = ConstantArray[0,numbersteps];
meanpath18= ConstantArray[0,numbersteps];
meanpath3v = ConstantArray[0,numbersteps];
meanpath10v = ConstantArray[0,numbersteps];
meanpath18v = ConstantArray[0,numbersteps];
numpts2 =8192;
indicator3 = sma3[[4;;Length[actdata]]];
indicator4 = sma3v[[4;;Length[actdata]]];
(*delta1 =10*Max[Abs[indicator3]];
If [delta1 == 0,delta1 = 500];
indicator3 = indicator3 + delta1;
delta2 = 10*Max[Abs[indicator4]];
If [delta2 == 0,delta2 = 500];
indicator4 = indicator4+delta2;*)
If[debugflag==1,Print["*****1,indicator3=",indicator3]];
Clear[temp1,temp2];
{coeffs,temp1,temp2}=getPercentErrorLinear[indicator3,debugflag];
temp1 = temp1 -Min[temp1]+100;
{xa3, xb3, ratios3, extenlst3, intlist3, pdflist3, outlst3} = getData[SeasonalFlag,temp1,numpts2,extendflag,debugflag];
If[debugflag==1,Print["*****2"]];
If[debugflag==1,Print[Dimensions[ratios3],Dimensions[intlist3],Dimensions[pdflist3],Dimensions[outlst3]]];
{dB3, pdB3,phasedistpdf3} = generateMagPhase[ratios3, intlist3,pdflist3,outlst3, xa3, xb3, IndicatorPaths,numbersteps,1.0,debugflag];
If[debugflag==1,Print["*****3"]];
temperatures3 = generateTemperatures[dB3,indicator3[[-1]],coeffs];
If[debugflag==1,Print["*****4"]];
Do[ meanpath2[[j]] = Total[pdB3[[1;;IndicatorPaths,j]]*temperatures3[[1;;IndicatorPaths,j]]]/(10^(-100)+Total[pdB3[[1;;IndicatorPaths,j]]]),{j,1,numbersteps}];
If[debugflag==1,Print["*****4a"]];
Clear[temp1,temp2,temp3];
{temp1,temp2,temp3}=getPercentErrorLinear[meanpath2[[1;;numbersteps]],debugflag];
negFlag=0;If [N[Sum[temp1[[1]]*i+temp1[[2]],{i,1,numbersteps}]/numbersteps]<indicator3[[-1]],negFlag=1];
{conf01,conf10,confema310,conf50,confema390,conf90,conf99,indxlist}= calculateConfLevels[temperatures3,pdB3,numbersteps,dis,negFlag,1];
If[debugflag==1,Print["*****5"]];
Clear[temp1,temp2];
{coeffs,temp1,temp2}=getPercentErrorLinear[indicator4,debugflag];
temp1 = temp1 -Min[temp1]+100;

{xa3, xb3, ratios3, extenlst3, intlist3, pdflist3, outlst3} = getData[SeasonalFlag,temp1,numpts2,extendflag,debugflag];

dB3 = ConstantArray[0,{IndicatorPaths,numbersteps}];
    pdB3 = ConstantArray[0,{IndicatorPaths,numbersteps}];
temperatures3 = ConstantArray[0,{IndicatorPaths,numbersteps}];

phasedistpdf3 = ConstantArray[0,Length[ratios]];
If[VolumeDataFlag==0,
If[debugflag==1,Print[Dimensions[ratios3],Dimensions[intlist3],Dimensions[pdflist3],Dimensions[outlst3]]];
{dB3, pdB3,phasedistpdf3} = generateMagPhase[ratios3, intlist3,pdflist3,outlst3, xa3, xb3, IndicatorPaths, numbersteps,1.0,debugflag];
temperatures3 = generateTemperatures[dB3,indicator4[[-1]],coeffs];
Do[ meanpath22[[j]] = Total[pdB3[[1;;IndicatorPaths,j]]*temperatures3[[1;;IndicatorPaths,j]]]/(10^(-100)+Total[pdB3[[1;;IndicatorPaths,j]]]),{j,1,numbersteps}];
Clear[temp1,temp2,temp3];
{temp1,temp2,temp3}=getPercentErrorLinear[meanpath22[[1;;numbersteps]],debugflag];
negFlag=0;If[N[Sum[temp1[[1]]*i+temp1[[2]],{i,1,numbersteps}]/numbersteps]<indicator4[[-1]], negFlag=1];
{conf01,conf10,confema3v10,conf50,confema3v90,conf90,conf99,indxlist}= calculateConfLevels[temperatures3,pdB3,numbersteps,dis,negFlag,1];
,conf01=conf10=confema3v10=conf50= confema3v90=conf90=conf99=indxlist=meanpath22=ConstantArray[0,futuresteps];
temperatures3 = dB3=pdB3=ConstantArray[0,{paths,futuresteps}];];
Clear[pdB3,ratios3,extenlst3,intlist3,ratio,sumval1,indxlist,pdflist3,outlst3,xa3,xb3,ya3,yb3,dB3,temperatures3,conf01,conf10,conf50,conf90,conf99];


If[debugflag==1,Print["*****6"]];
(*confema310 = confema310 - delta1;
confema390 = confema390-delta1;
confema3v10 = confema3v10 - delta2;
confema3v90 = confema3v90 - delta2;
meanpath2 = meanpath2-delta1;

meanpath22 = meanpath22-delta2;*)

indicator3 = sma3[[1;;Length[actdata]]];
indicator3 =Join[indicator3,meanpath2];
indicator4 = sma3v[[1;;Length[actdata]]];
indicator4 = Join[indicator4,meanpath22];


sma3 = indicator3;
Do[sma10[[i+2]] =N[1/2*Total[indicator3[[i;;i+2]]]/3 + 1/2*sma10[[i-1+2]]],{i,Length[actdata]-1,Length[indicator3]-2}];
Do[sma18[[i+5]] = N[2/7*Total[indicator3[[i;;i+5]]]/6+5/7*sma18[[i-1+5]]],{i,Length[actdata]-16,Length[indicator3]-5}];

sma3v = indicator4;


Do[sma10v[[i+2]] =N[1/2*Total[indicator4[[i;;i+2]]]/3 + 1/2*sma10v[[i-1+2]]],{i,Length[actdata]-1,Length[indicator4]-2}];
Do[sma18v[[i+5]] = N[2/7*Total[indicator4[[i;;i+5]]]/6+5/7*sma18v[[i-1+5]]],{i,Length[actdata]-16,Length[indicator4]-5}];

meanpath3 = sma3[[Length[actdata]+1;;Length[actdata]+numbersteps]];
meanpath10=sma10[[Length[actdata]+1;;Length[actdata]+numbersteps]];
meanpath18 = sma18[[Length[actdata]+1;;Length[actdata]+numbersteps]];


meanpath3v = sma3v[[Length[actdata]+1;;Length[actdata]+numbersteps]];

meanpath10v = sma10v[[Length[actdata]+1;;Length[actdata]+numbersteps]];
meanpath18v = sma18v[[Length[actdata]+1;;Length[actdata]+numbersteps]];
];
Clear[temp1,temp2];
(*{temp1,temp2}=getIntegrate2[sma3[[1;;Length[actdata]]],1,1,Length[actdata]];
sma3 = sma3/(temp1/Length[actdata])*20;

If[debugflag==1,Print["sma3=",sma3]];
{temp1,temp2}=getIntegrate2[sma10[[1;;Length[actdata]]],1,1,Length[actdata]];
sma10 = sma10/(temp1/Length[actdata])*20;
{temp1,temp2}=getIntegrate2[sma18[[1;;Length[actdata]]],1,1,Length[actdata]];
sma18 = sma18/(temp1/Length[actdata])*20;
{temp1,temp2}=getIntegrate2[sma3v[[1;;Length[actdata]]],1,1,Length[actdata]];
sma3v = sma3v/(temp1/Length[actdata])*20;
{temp1,temp2}=getIntegrate2[sma10v[[1;;Length[actdata]]],1,1,Length[actdata]];
sma10v = sma10v/(temp1/Length[actdata])*20;
{temp1,temp2}=getIntegrate2[sma18v[[1;;Length[actdata]]],1,1,Length[actdata]];
sma18v = sma18v/(temp1/Length[actdata])*20;*)
(*sma10 = sma10[[1;;Length[actdata]]]/(10^(-100)+Max[Abs[sma10[[1;;Length[actdata]]]]]*20);
sma18 = sma18[[1;;Length[actdata]]]/(10^(-100)+Max[Abs[sma18[[1;;Length[actdata]]]]]*20);
sma18v = sma18v[[1;;Length[actdata]]]/(10^(-100)+Max[Abs[sma18v[[1;;Length[actdata]]]]]*20);
sma3v = sma3v[[1;;Length[actdata]]]/(10^(-100)+Max[Abs[sma3v[[1;;Length[actdata]]]]]*20);
sma10v = sma10v[[1;;Length[actdata]]]/(10^(-100)+Max[Abs[sma10v[[1;;Length[actdata]]]]]*20);*)
sma3 = sma3[[1;;Length[actdata]]];
sma10=sma10[[1;;Length[actdata]]];
sma18=sma18[[1;;Length[actdata]]];
sma3v =sma3v[[1;;Length[actdata]]];
sma10v=sma10v[[1;;Length[actdata]]];
sma18v = sma18v[[1;;Length[actdata]]];


(*read into paths variable number of paths to calculate into future for many worlds probabilistic analysis..... ie.monte carlo*)
(*set the number of points in the pdf to be 8192,for interpolation, numpts=8192;*)
(*do the interpolation,and get the pdf and x array and phaselist and difflist*)
Clear[temp1,temp2,coeffs1];
{coeffs1,temp1,temp2}=getPercentErrorLinear[actdata,debugflag];
temp1 = temp1 -Min[temp1]+100;
{xa, xb, ratios,  extenlst, intlist, pdflist, outlst} = getData[SeasonalFlag,temp1, numpts,extendflag,debugflag];

count1=0;count2=0;sumup=1;sumdown=1;sumsame =1; count3=0;
ddd = year;
If [Length[ratios]<year,
ddd = Length[ratios]];
Do[If [ratios[[i]]==1,count3 = count3+1];
If[ratios[[-i]]> 1,count1=count1+1;sumup=sumup*ratios[[-i]],If[ratios[[-i]]<1,count2=count2+1;sumdown=sumdown*ratios[[-i]]]],{i,1,ddd}];
(*rat1 is the geometric mean of ratios of number of up days in past sequence*)
If [count1 ==0, rat1 = 0,
rat1 = sumup^(1/count1)//N];
MeanUp =( rat1-1)//N;
(*rat2 is the geometric mean of ratios of number of down days in past sequence*)
If [count2==0,rat2=0,
rat2 = sumdown^(1/count2)//N];
MeanDown = (1-rat2)//N;

(*pr is probability of an up day in sequence compared to total number of days in sorted ratiolist*)
If [count1+count2+count3==0,pr=0;pr2=0,
pr = count1/(count1+count2+count3);
pr2 = count2/(count1+count2+count3)];
(*output these values for user viewing and compute the percentage increase or decrease out of 100 based on price or volume actdata from start of actdata to end of actdata (actdata(1))*)
percChange=100*actdata[[-1]]/actdata[[-ddd]]-100;
sdev1 =0;
sdev2 =0;
Do[If[ratios[[i]]>1, sdev1 = sdev1 + (ratios[[i]]-MeanUp)^2]; If [ratios[[i]]<1, sdev2 = sdev2 +(ratios[[i]]-MeanDown)^2],{i,1,ddd}];
sdev1 = Sqrt[sdev1/(count1-1)];
sdev2 = Sqrt[sdev2/(count2-1)];





(*set the focus to axes5*) (*erase previous actdata from axes*)
(*plot the price or volume actdata*)

(*plot the pdf,against its x axis values*)

If [debugflag==1,Print["***1"]];
indx1 =matlabFind1[outlst,GreaterEqual, 0.9];
indx2 = matlabFind1[outlst,LessEqual,1.1];
indxfirst = indx1[[1]];
indxlast = indx2[[-1]];
If[debugflag==1,Print["***1a"]];
 {sumv1,intl1}=getIntegrate2[pdflist[[indxfirst;;indxlast]],1,1,indxlast-indxfirst+1];
If[debugflag==1,Print["***1b"]];
tempd=pdflist[[indxfirst;;indxlast]]*outlst[[indxfirst;;indxlast]]/sumv1;
If[debugflag==1,Print["***1c"]];
{sumv,intl}=getIntegrate2[tempd,1,1,indxlast-indxfirst+1];
If[debugflag==1,Print["***1d"]];
Clear[indx1,indx2];

indx1 = matlabFind1[outlst,GreaterEqual,0.95];
If[debugflag==1,Print["***1e"]];
indx2 = matlabFind1[outlst,LessEqual,1.05];
indxfirst = indx1[[1]];
indxlast = indx2[[-1]];
If[debugflag==1,Print["***1f"]];
Clear[indx1];
indx1 = Reverse[Sort[pdflist[[indxfirst;;indxlast]]]];
maxval= indx1[[7]];
If[debugflag==1,Print["***2"]];
(*compute the theoretical net gain and output it for user viewing,similarly output the expected value of the pdf*)
If [rat1==0||rat2==0,netGain=percChange,
netGain=(rat1^(pr*year)*rat2^(pr2*year)-1)*100];
If [debugflag==1,Print["***2a"]];
(*plot the pdf,against its x axis values*)
plotpdf=ListLinePlot[Transpose[{outlst[[indxfirst;;indxlast]],pdflist[[indxfirst;;indxlast]]}],Filling-> Axis,PlotRange-> {{.95,1.05},{0,maxval}},PlotLabel->"Probability Distribution",GridLines->Automatic,AxesLabel->{"price ratios","relative prob"}];
(*clear the rest of the plots just for now*)
If [debugflag==1,Print["***2b"]];
(*get the ratio probability ppast of number of phase points to calculate versus generic phase from the long distribution phaselistpdf2.*) 
(*generate the magnitude and phase actdata,along with the probabilities of each ratio*)
If [catastropheflag==1,paths2 =paths1,paths2 = paths];
{dB, pdB,phasedistpdf} = generateMagPhase[ratios, intlist,pdflist,outlst, xa, xb, paths2, futuresteps,ppast,debugflag];
temperatures = generateTemperatures[dB,s0,coeffs1];
If[debugflag==1,Print["Finished generating temperatures"]];
If[catastropheflag==1,
If[debugflag==1,Print[Dimensions[ratios],Dimensions[intlist],Dimensions[pdflist],Dimensions[outlst]]];

totalprob1 = ConstantArray[0,{paths1,futuresteps}];

sumprob1 = ConstantArray[0,futuresteps];
temp4 = ConstantArray[0,futuresteps];
If[debugflag==1,Print["Started generating getMultiply2"]];
Do[temp4 = getMultiply2[pdB[[i,1;;futuresteps]],1,1,futuresteps];totalprob1[[i,1;;futuresteps]] =temp4,{i,1,paths1}];
If[debugflag==1,Print["Finished generating getMultiply2"]];
Do[sumprob1[[j]] = Total[ totalprob1[[1;;paths1,j]]];If[sumprob1[[j]]==0,sumprob1[[j]]=1.0];totalprob1[[1;;paths1,j]] =N[totalprob1[[1;;paths1,j]]/paths1/sumprob1[[j]]],{j,1,futuresteps}];

If[debugflag==1,Print["Finished generating probabilities"]];
threspoint9 =threspoint8=threspoint7=threspoint6=threspoint5=threspoint4=thres1point1=thres1point2=thres1point3=thres1point4=thres1point5=thres1point6= ConstantArray[0,futuresteps];
Do[ If[temperatures[[i,j]]≤  .9*s0,threspoint9[[j]] = threspoint9[[j]]+totalprob1[[i,j]]];

If[temperatures[[i,j]]≤  .8*s0,threspoint8[[j]] = threspoint8[[j]]+totalprob1[[i,j]]];

If[temperatures[[i,j]]≤  .7*s0,threspoint7[[j]] = threspoint7[[j]]+totalprob1[[i,j]]];
If[temperatures[[i,j]]≤  .6*s0,threspoint6[[j]] = threspoint6[[j]]+totalprob1[[i,j]]];
If[temperatures[[i,j]]≤  .5*s0,threspoint5[[j]] = threspoint5[[j]]+totalprob1[[i,j]]];
If[temperatures[[i,j]]≤  .4*s0,threspoint4[[j]] = threspoint4[[j]]+totalprob1[[i,j]]];
If[temperatures[[i,j]]≥   1.1*s0,thres1point1[[j]] = thres1point1[[j]]+totalprob1[[i,j]]];
If[temperatures[[i,j]]≥   1.2*s0,thres1point2[[j]] = thres1point2[[j]]+totalprob1[[i,j]]];
If[temperatures[[i,j]]≥   1.3*s0,thres1point3[[j]] = thres1point3[[j]]+totalprob1[[i,j]]];
If[temperatures[[i,j]]≥   1.4*s0,thres1point4[[j]] = thres1point4[[j]]+totalprob1[[i,j]]];
If[temperatures[[i,j]]≥   1.5*s0,thres1point5[[j]] = thres1point5[[j]]+totalprob1[[i,j]]];
If[temperatures[[i,j]]≥   1.6*s0,thres1point6[[j]] = thres1point6[[j]]+totalprob1[[i,j]]];
,{i,1,paths1},{j,1,futuresteps}];
Clear[totalprob1,sumprob1,temperatures1,dB2,pdB2];
If [debugflag==1,Print["Finished thresholds"]];
];

If[catastropheflag==1,
({{Clear[temp1,temp2,temp3,temp5,temp6,temp7,temp9];
temp2=temp3=temp5=temp6=temp7=temp9 = ConstantArray[{},futuresteps];
{temp1,threspoint9}=getIntegrate2[threspoint9,1,1,Length[threspoint9]];
{temp1,threspoint8}=getIntegrate2[threspoint8,1,1,Length[threspoint8]];

{temp1,threspoint7}=getIntegrate2[threspoint7,1,1,Length[threspoint7]];

{temp1,threspoint6}=getIntegrate2[threspoint6,1,1,Length[threspoint6]];

{temp1,threspoint5}=getIntegrate2[threspoint5,1,1,Length[threspoint5]];

{temp1,threspoint4}=getIntegrate2[threspoint4,1,1,Length[threspoint4]];


{temp1,thres1point1}=getIntegrate2[thres1point1,1,1,Length[thres1point1]];
{temp1,thres1point2}=getIntegrate2[thres1point2,1,1,Length[thres1point2]];

{temp1,thres1point3}=getIntegrate2[thres1point3,1,1,Length[thres1point3]];

{temp1,thres1point4}=getIntegrate2[thres1point4,1,1,Length[thres1point4]];

{temp1,thres1point5}=getIntegrate2[thres1point5,1,1,Length[thres1point5]];

{temp1,thres1point6}=getIntegrate2[thres1point6,1,1,Length[thres1point6]];



Do [temp2[[j]] = {j,threspoint9[[j]]};
temp3[[j]]={j,threspoint8[[j]]};temp5[[j]] = {j,threspoint7[[j]]};temp6[[j]]= {j,threspoint6[[j]]};temp7[[j]]= {j,threspoint5[[j]]};temp9[[j]]= {j,threspoint4[[j]]},{j,1,futuresteps}];
imagepoint9 =  ListLinePlot[temp2,Joined-> True,GridLines ->Automatic,PlotRange-> {0,Max[threspoint9]},PlotStyle->Blue,PlotLabel-> "Cum.Probability of less than .9 of initial price"];

imagepoint8 =  ListLinePlot[temp3,Joined-> True,GridLines ->Automatic,PlotRange-> {0,Max[threspoint8]},PlotStyle->Blue,PlotLabel-> "Cum.Probability of less than .8 of initial price"];
imagepoint7 =  ListLinePlot[temp5,Joined-> True,GridLines ->Automatic,PlotRange-> {0,Max[threspoint7]},PlotStyle->Blue,PlotLabel-> "Cum.Probability of less than .7 of initial price"];
imagepoint6 =  ListLinePlot[temp6,Joined-> True,GridLines ->Automatic,PlotRange-> {0,Max[threspoint6]},PlotStyle->Blue,PlotLabel-> "Cum.Probability of less than .6 of initial price"];
imagepoint5 =  ListLinePlot[temp7,Joined-> True,GridLines ->Automatic,PlotRange-> {0,Max[threspoint5]},PlotStyle->Blue,PlotLabel-> "Cum.Probability of less than .5 of initial price"];
imagepoint4 =  ListLinePlot[temp9,Joined-> True,GridLines ->Automatic,PlotRange-> {0,Max[threspoint4]},PlotStyle->Blue,PlotLabel-> "Cum.Probability of less than .4 of initial price"];
Do [temp2[[j]] = {j,thres1point1[[j]]};
temp3[[j]]={j,thres1point2[[j]]};temp5[[j]] = {j,thres1point3[[j]]};temp6[[j]]= {j,thres1point4[[j]]};temp7[[j]]= {j,thres1point5[[j]]};temp9[[j]]= {j,thres1point6[[j]]},{j,1,futuresteps}];
image1point1 =  ListLinePlot[temp2,Joined-> True,GridLines ->Automatic,PlotRange-> {0,Max[thres1point1]},PlotStyle->Blue,PlotLabel-> "Cum.Probability of greater than 1.1 of initial price"];

image1point2 =  ListLinePlot[temp3,Joined-> True,GridLines ->Automatic,PlotRange-> {0,Max[thres1point2]},PlotStyle->Blue,PlotLabel-> "Cum.Probability of greater than 1.2 of initial price"];
image1point3 =  ListLinePlot[temp5,Joined-> True,GridLines ->Automatic,PlotRange-> {0,Max[thres1point3]},PlotStyle->Blue,PlotLabel-> "Cum.Probability of greater than 1.3 of initial price"];
image1point4 =  ListLinePlot[temp6,Joined-> True,GridLines ->Automatic,PlotRange-> {0,Max[thres1point4]},PlotStyle->Blue,PlotLabel-> "Cum.Probability of greater than 1.4 of initial price"];
image1point5 =  ListLinePlot[temp7,Joined-> True,GridLines ->Automatic,PlotRange-> {0,Max[thres1point5]},PlotStyle->Blue,PlotLabel-> "Cum.Probability of greater than 1.5 of initial price"];
image1point6 =  ListLinePlot[temp9,Joined-> True,GridLines ->Automatic,PlotRange-> {0,Max[thres1point6]},PlotStyle->Blue,PlotLabel-> "Cum.Probability of greater than 1.6 of initial price"];}, {\[Placeholder]}})
];
Clear[coeffs,volatility,vol2];
{coeffs,volatility,vol2}=getPercentErrorCubic[YrData2,{{}}];
Clear[cubPCR1];
cubPCR1=ConstantArray[0.0,Length[YrData2]];
Do [  cubPCR1[[j]] =N[coeffs[[1]]*j^3+coeffs[[2]]*j^2+coeffs[[3]]*j+coeffs[[4]]],{j,1,Length[YrData2]}];

If [forecastindicatorflag ==1,
Clear[temp2 , temp3,temp5,temp6,temp7,temp9,temp10,temp11,DateData3];
temp2 = temp3=temp5=temp6=temp7=temp9=temp10=temp11=ConstantArray[0.0,{numbersteps,2}];
DateData3=ConstantArray[DateData2[[-1]],numbersteps];
If[debugflag==1,Print[DateData2]];
Do[DateData3[[j]]=DatePlus[DateData2[[-1]],(Floor[j/5])*7+(j-Floor[j/5]*5)],{j,1,numbersteps}];
If[debugflag==1,Print[DateData3]];


temp2[[All,1]] = DateData3[[1;;numbersteps]];
      temp3[[All,1]]=DateData3[[1;;numbersteps]];
 temp5[[All,1]]=DateData3[[1;;numbersteps]];
 temp6[[All,1]]=DateData3[[1;;numbersteps]];
 temp7[[All,1]]=DateData3[[1;;numbersteps]];
 temp9[[All,1]]= DateData3[[1;;numbersteps]];
 temp10[[All,1]]= DateData3[[1;;numbersteps]];
 temp11[[All,1]]= DateData3[[1;;numbersteps]];
Do [temp2[[j,2]]=confema310[[j]];temp3[[j,2]]=confema390[[j]];temp5[[j,2]]=meanpath3[[j]];temp6[[j,2]]=meanpath10[[j]];temp7[[j,2]]=meanpath18[[j]];temp9[[j,2]]=meanpath3v[[j]];temp10[[j,2]]=meanpath10v[[j]];temp11[[j,2]]=meanpath18v[[j]],{j,1,numbersteps}]

If[debugflag==1,Print[temp2[[All,1]],temp2[[All,2]]]];
indicatorspredict = DateListPlot[{temp5,temp2,temp3,temp6,temp7},Joined-> True,GridLines ->Automatic,PlotStyle->{Magenta,Darker [Cyan],Darker[ Cyan],Green,Blue},PlotLabel-> "Price Moving Average Forecast,\n 3(Magenta),9(Green),18(Blue);50% conf limits Cyan"];

indicatorpredictplain =DateListPlot[{temp5,temp6,temp7},Joined-> True,PlotRange-> Automatic,GridLines ->Automatic,PlotStyle->{Magenta,Green,Blue},PlotLabel-> "Price Delta Forecast,\n 3magenta,9Green,18Blue"];

indicatorpredict2plain =DateListPlot[{temp9,temp10,temp11},Joined-> True,PlotRange-> Automatic,GridLines ->Automatic,PlotStyle->{Magenta,Green,Blue},PlotLabel-> "Volume Delta Forecast,\n 3magenta,9Green,18Blue"];

Do [temp2[[j,2]]=confema3v10[[j]];temp3[[j,2]]=confema3v90[[j]],{j,1,numbersteps}];

If[debugflag==1,Print[temp2[[All,1]],temp2[[All,2]]]];
indicatorspredict2 =DateListPlot[{temp9,temp2,temp3,temp10,temp11},Joined-> True,GridLines ->Automatic,PlotStyle->{Magenta,Darker[Cyan],Darker[Cyan],Green,Blue},PlotLabel-> "Volume Moving Average Forecast,\n 3(magenta),9(Green),18(Blue);50% conf limits Cyan"];

Clear[temp,IntegrateMeanpath3];
IntegrateMeanpath3 = ConstantArray[0.0,Length[meanpath3]];
{temp,IntegrateMeanpath3} = getIntegrate2[meanpath3,1,1,Length[meanpath3]];
IntegrateMeanpath3=IntegrateMeanpath3 + (EMA3[[-1]]+IntegrateMeanpath3[[1]]);
PlotIntMean3 = ListLinePlot[IntegrateMeanpath3,Joined-> True,GridLines-> Automatic,PlotRange-> Automatic,PlotStyle-> Blue,PlotLabel-> "Integrated 3 day predicted EMA"];



];

(*Do[ temp8[[j]] = {j,phasedistpdf[[j]]},{j,1,Length[phasedistpdf]}];

phaseplot = ListPlot[temp8,PlotStyle->Directive[Blue],PlotRange-> Automatic,PlotLabel->{"Phase distribution by delta day from present"}];
*)

(*calculate the option plot values and confidence limits and most probable path into the future*)


{callup,calldown,call2,put2,confcall,confput,confcall10,confcall50,confcall60,confcall90,confput10,confput50,confput60,confput90, valueforwardup, valueforwarddown,valuesinupd,valuesindownd,meanpath,diffprob} = calculateFutureValues[YrData2,temperatures, pdB,interestRate, s0, SpotPrice,dis, T,debugflag]; 

Clear[temp1,temp2,temp3];
           {temp1,temp2}=getIntegrate2[meanpath,1,1,futuresteps];
           {temp3,temp2}=getIntegrate2[diffprob,1,1,futuresteps];
           probofMeanPath = N[temp3/temp1];

Clear[lowersdv,uppersdv,temp1,temp2];
lowersdv = uppersdv=ConstantArray[0,futuresteps];temp1=temp2=0;
Do[Do[If[temperatures[[i,j]]≥ meanpath[[j]],uppersdv[[j]]=uppersdv[[j]]+Abs[temperatures[[i,j]]-meanpath[[j]]];temp1 = temp1+1;lowersdv[[j]]=lowersdv[[j]]+Abs[meanpath[[j]]-temperatures[[i,j]]];temp2 = temp2+1;],{i,1,paths}]; If[temp2>0,lowersdv[[j]]=-N[lowersdv[[j]]/(temp2)],lowersdv[[j]]=0];If[temp1>0,uppersdv[[j]]=N[uppersdv[[j]]/(temp1)],uppersdv[[j]]=0];,{j,1,futuresteps}];


If [optionflag==-1,
Clear[temp1,data2];
data2 = ConstantArray[0.0,Length[datelisttemp2]];
Do[ data2[[j]]=YrData2[[datelisttemp2[[j]]]],{j,1,Length[datelisttemp2]}];

Clear[dwt,dwd,dwtpredict,dwtdata];
dwd=DiscreteWaveletTransform[RandomReal[1,{futuresteps}],BiorthogonalSplineWavelet[],5];

dwt = DiscreteWaveletTransform[data2,BiorthogonalSplineWavelet[], 5,Padding->0.0];
Clear[temp1,temp2,temp3,temp4,temp5,temp6,temp7];

temp2=8;
temp6={};
While[temp2<futuresteps,temp2=temp2+8];
temp7=ConstantArray[0,10];
 Do[

Clear[temp3];
temp3 =Normal[dwd][[i,2]];
temp4 =Length[temp3];
temp5=Normal[dwt][[i,2]];

Clear[temp1,dwtpredict,dwtpredict2];
dwtpredict = ConstantArray[0,{3,temp4}];
{plot2,dwtpredict2}=  MusicFinal[temp5,temp4 ,temp5[[-1]],55,0,debugflag];
dwtpredict =Flatten[ dwtpredict2[[1,All]]];

temp5=dwd["WaveletIndex"][[i]];
temp6=Append[temp6,temp5-> dwtpredict[[1;;temp4]]];
temp7[[i]]=Length[temp3]+temp4;
,{i,1,10}];

dims = dwd["DataDimensions"];

Clear[temp1];

temp1=DiscreteWaveletData[temp6,dwt["Wavelet"],dwt["Transform"],{futuresteps}];

futurepath= {InverseWaveletTransform[temp1],ConstantArray[0,futuresteps],ConstantArray[0,futuresteps]};

Clear[temp1];
temp1 = data2[[-1]]-futurepath[[1,1]];
Do[ futurepath[[1,j]]=futurepath[[1,j]]+temp1;,{j,1,futuresteps}];



];
If [optionflag>-1,
If[debugflag==1,Print["Start of futurearma"]];

data2 = ConstantArray[0.0,Length[datelisttemp2]];
If[Length[datelisttemp2]>0,
Do[ data2[[j]]=YrData2[[datelisttemp2[[j]]]],{j,1,Length[datelisttemp2]}];
Clear[minmpe,minrmse,futurepath];
toler = N[10^(-3)];
rho = 1.005;
inneriterations=7;
];
numpasses=27;
SetDirectory[directry]
If[optionflag==0,
Get["outoptions2.txt"];
];
If[Length[datelisttemp2]>0,
If [optionflag==1,
Clear[futureA,futurew1,futurew2,futurew3,futurew4];
{minrmse,minmpe,futurepath2,futureA,futurew1,futurew2,futurew3,futurew4}=NeuralNet1[data2,nodeslayer,inneriterations,rho,toler,numpasses,futuresteps,{},{},{},{},1.0,optionflag,deTrendflag,debugflag];
futurepath = {futurepath2,ConstantArray[0,futuresteps],ConstantArray[0,futuresteps]};
];

If[optionflag==0,
Clear[futureA2,futurew12,futurew22,futurew32,futurew42];

{minrmse,minmpe,futurepath2,futureA2,futurew12,futurew22,futurew32,futurew42}=
NeuralNet1[data2,nodeslayer,inneriterations,rho,toler,numpasses,futuresteps,futurew1,futurew2,futurew3,futurew4,futureA,optionflag,deTrendflag,debugflag];
futurepath = {futurepath2,ConstantArray[0,futuresteps],ConstantArray[0,futuresteps]};
];
If[debugflag==1&&optionflag<2,Print["minmpe = " , minmpe,"   minrmse=",minrmse]];


Clear[futureA2,futurew12,futurew22,futurew32,futurew42];
If[debugflag==1,Print["optionflag=",optionflag];];
If [optionflag==2,
Clear[temp1,futurepath];
{plot1,futurepath} =  MusicFinal[data2,futuresteps ,data2[[-1]],55,0,debugflag];
If [debugflag==1,Print["futurepath =",futurepath];];
If [debugflag==1,Print["futuresteps=",futuresteps," , Length futurepath=",Length[Flatten[futurepath[[1,All]]]]]];
Clear[temp1,temp2,coeffs];
{coeffs,temp1,temp2}=getPercentErrorLinear[Flatten[futurepath[[1,All]]],debugflag];
{xa4, xb4, ratios4, extenlst4, intlist4, pdflist4, outlst4} = getData[SeasonalFlag,data2,Length[data2],extendflag,debugflag];
If[debugflag==1,Print["******2"]];
If[debugflag==1,Print[Dimensions[ratios3],Dimensions[intlist3],Dimensions[pdflist3],Dimensions[outlst3]]];
{dB4, pdB4,phasedistpdf4} = generateMagPhase[ratios4, intlist4,pdflist4,outlst4, xa4, xb4, IndicatorPaths,futuresteps,1.0,debugflag];
If[debugflag==1,Print["******3"]];
temperatures4 = generateTemperatures[dB4,data2[[-1]],coeffs];

{conf014,conf104,conf254,conf504,conf754,conf904,conf994,indxlist4,ratioALLC4,sumval14,ratio334,ratio504,ratio804,ratio994} = calculateConfLevels[temperatures4,pdB4,data2[[-1]],dis,negFlag,0];
conffp10 = conf104;
conffp90 = conf904;
conffp50 = conf504;
Clear[conf014,conf104,conf254,conf504,conf754,conf904,conf994,indxlist4,ratioALLC4,sumval14,ratio334,ratio504,ratio804,ratio994];
];

If[optionflag==3,
Clear[futurepath];
Clear[dwd,dwt,dwtpredict,dwtdata];
dwd=DiscreteWaveletTransform[RandomReal[1,futuresteps],BiorthogonalSplineWavelet[],5];

dwt = DiscreteWaveletTransform[data2,BiorthogonalSplineWavelet[], 5,Padding->0.0];
Clear[temp1,temp2,temp3,temp4,temp5,temp6,temp7];

temp2=8;
temp6={};
While[temp2<futuresteps,temp2=temp2+8];
temp7=ConstantArray[0,10];
 Do[

Clear[temp3];
temp3 =Normal[dwd][[i,2]];
temp4 =Length[temp3];
temp5=Normal[dwt][[i,2]];

Clear[temp1,dwtpredict2,dwtpredict];
dwtpredict = ConstantArray[0,{3,temp4}];
{plot2,dwtpredict2} =  MusicFinal[temp5,temp4 ,temp5[[-1]],55,0,debugflag];
dwtpredict = Flatten[dwtpredict2[[1,All]]];

temp5=dwd["WaveletIndex"][[i]];
temp6=Append[temp6,temp5-> dwtpredict[[1;;temp4]]];
temp7[[i]]=Length[temp3]+temp5;
,{i,1,10}];

dims = dwd["DataDimensions"];

Clear[temp1];

temp1=DiscreteWaveletData[temp6,dwt["Wavelet"],dwt["Transform"],{futuresteps}];
Clear[futurepath];
futurepath= {InverseWaveletTransform[temp1],ConstantArray[0,futuresteps],ConstantArray[0,futuresteps]};];


];
If [debugflag==1,Print["futurepath =",futurepath];];
If [Length[data2]>0,
Clear[temp1];
temp1 = data2[[-1]]-futurepath[[1,1]];
Do[ futurepath[[1,j]]=futurepath[[1,j]]+temp1;,{j,1,futuresteps}];

];
If [debugflag==1,Print["futurepath =",futurepath];];

calla = ConstantArray[0,{4,futuresteps}];
puta = ConstantArray[0,{4,futuresteps}];



profit = ConstantArray[0,futuresteps];


kellys=ConstantArray[0,4];
calld=ConstantArray[0,{4,futuresteps}];
putd=ConstantArray[0,{4,futuresteps}];
Do[If[Abs[OptionCounts[[i]]]>0,Do[If[meanpath[[j]]≥ strikes[[i]],calld[[i,j]] = (meanpath[[j]]-strikes[[i]])/dis[[j]];];
If[meanpath[[j]]≤ strikes[[i]],putd[[i,j]]=(strikes[[i]]-meanpath[[j]])/dis[[j]];];
,{j,1,busdays[[i]]}];];,{i,1,4}];
profit2 = ConstantArray[0,futuresteps];
Do[If[Abs[OptionCounts[[i]]]>0,If[busdays[[i]]>0,Do[ If [(OptionTypes[[i]]=="Call"||OptionTypes[[i]]=="call" ||OptionTypes[[i]]=="CALL"),profit2[[j]]=profit2[[j]]+OptionCounts[[i]]*100*calld[[i,j]];];
If[(OptionTypes[[i]]=="Put"||OptionTypes[[i]]=="put"||OptionTypes[[i]]=="PUT"),profit2[[j]]=profit2[[j]]+OptionCounts[[i]]*100*putd[[i,j]];];
,{j,1,busdays[[i]]}];If [(OptionTypes[[i]]=="Call"||OptionTypes[[i]]=="call" ||OptionTypes[[i]]=="CALL"),If[OptionCounts[[i]]>0,odds=N[Sum[calld[[i,j]],{j,1,busdays[[i]]}]/(10^(-100)+Sum[putd[[i,j]],{j,1,busdays[[i]]}])];,If[OptionCounts[[i]]<0,odds=N[Sum[putd[[i,j]],{j,1,busdays[[i]]}]/(10^(-100)+Sum[calld[[i,j]],{j,1,busdays[[i]]}])];,odds=0]];p=N[odds/(odds+1)];
If[p≥0&&p≤1,
kellys[[i]]=N[.92*(p*(odds-1)-(1-p))/(10^(-100)+odds-1)];
,
kellys[[i]]=0.0;
];
If[kellys[[i]]<0,kellys[[i]]=0.0]];If[(OptionTypes[[i]]=="Put"||OptionTypes[[i]]=="put"||OptionTypes[[i]]=="PUT"),If[OptionCounts[[i]]>0,odds=N[Sum[putd[[i,j]],{j,1,busdays[[i]]}]/(10^(-100)+Sum[calld[[i,j]],{j,1,busdays[[i]]}])];,If[OptionCounts[[i]]<0,odds=N[Sum[calld[[i,j]],{j,1,busdays[[i]]}]/(10^(-100)+Sum[putd[[i,j]],{j,1,busdays[[i]]}])];,odds=0;]];p=N[odds/(odds+1)];If[p≥ 0&&p≤1,kellys[[i]]=N[.92*(p*(odds-1)-(1-p))/(10^(-100)+odds-1)];,kellys[[i]]=0.0;];

If[kellys[[i]]<0,kellys[[i]]=0.0]]]];,{i,1,4}];

OverallKellyMP = Sum[kellys[[i]],{i,1,4}]-kellys[[1]]*kellys[[2]]-kellys[[1]]*kellys[[3]]-kellys[[1]]*kellys[[4]]-kellys[[2]]*kellys[[3]]-kellys[[2]]*kellys[[4]]-kellys[[3]]*kellys[[4]]+kellys[[1]]*kellys[[2]]*kellys[[3]]+kellys[[1]]*kellys[[2]]*kellys[[4]]+kellys[[1]]*kellys[[3]]*kellys[[4]]+kellys[[2]]*kellys[[3]]*kellys[[4]]-kellys[[1]]*kellys[[2]]*kellys[[3]]*kellys[[4]];
Clear[kellys,calld,putd];
kellys=ConstantArray[0,4];
calld=ConstantArray[0,{4,futuresteps}];
putd=ConstantArray[0,{4,futuresteps}];
Do[If[Abs[OptionCounts[[i]]]>0,Do[If[futurepath[[1,j]]≥ strikes[[i]],calld[[i,j]] = (futurepath[[1,j]]-strikes[[i]])/dis[[j]];];
If[futurepath[[1,j]]≤ strikes[[i]],putd[[i,j]]=(strikes[[i]]-futurepath[[1,j]])/dis[[j]];];
,{j,1,busdays[[i]]}];];,{i,1,4}];
profit = ConstantArray[0,futuresteps];
Do[If[Abs[OptionCounts[[i]]]>0,If[busdays[[i]]>0,Do[ If [(OptionTypes[[i]]=="Call"||OptionTypes[[i]]=="call" ||OptionTypes[[i]]=="CALL"),profit[[j]]=profit[[j]]+OptionCounts[[i]]*100*calld[[i,j]];];
If[(OptionTypes[[i]]=="Put"||OptionTypes[[i]]=="put"||OptionTypes[[i]]=="PUT"),profit[[j]]=profit[[j]]+OptionCounts[[i]]*100*putd[[i,j]];];
,{j,1,busdays[[i]]}];If [(OptionTypes[[i]]=="Call"||OptionTypes[[i]]=="call" ||OptionTypes[[i]]=="CALL"),If[OptionCounts[[i]]>0,odds=N[Sum[calld[[i,j]],{j,1,busdays[[i]]}]/(10^(-100)+Sum[putd[[i,j]],{j,1,busdays[[i]]}])];,If[OptionCounts[[i]]<0,odds=N[Sum[putd[[i,j]],{j,1,busdays[[i]]}]/(10^(-100)+Sum[calld[[i,j]],{j,1,busdays[[i]]}])];,odds=0]];p=N[odds/(odds+1)];

If[p≥0&&p≤1,kellys[[i]]=N[.92*(p*(odds-1)-(1-p))/(10^(-100)+odds-1)];,kellys[[i]]=0.0;];

If[kellys[[i]]<0,kellys[[i]]=0.0]];If[(OptionTypes[[i]]=="Put"||OptionTypes[[i]]=="put"||OptionTypes[[i]]=="PUT"),If[OptionCounts[[i]]>0,odds=N[Sum[putd[[i,j]],{j,1,busdays[[i]]}]/(10^(-100)+Sum[calld[[i,j]],{j,1,busdays[[i]]}])];,If[OptionCounts[[i]]<0,odds=N[Sum[calld[[i,j]],{j,1,busdays[[i]]}]/(10^(-100)+Sum[putd[[i,j]],{j,1,busdays[[i]]}])];,odds=0;]];p=N[odds/(odds+1)];

If[p≥0&&p≤1,kellys[[i]]=N[.92*(p*(odds-1)-(1-p))/(10^(-100)+odds-1)];,kellys[[i]]=0.0;];

If[kellys[[i]]<0,kellys[[i]]=0.0]]]];,{i,1,4}];

OverallKellyFourier = Sum[kellys[[i]],{i,1,4}]-kellys[[1]]*kellys[[2]]-kellys[[1]]*kellys[[3]]-kellys[[1]]*kellys[[4]]-kellys[[2]]*kellys[[3]]-kellys[[2]]*kellys[[4]]-kellys[[3]]*kellys[[4]]+kellys[[1]]*kellys[[2]]*kellys[[3]]+kellys[[1]]*kellys[[2]]*kellys[[4]]+kellys[[1]]*kellys[[3]]*kellys[[4]]+kellys[[2]]*kellys[[3]]*kellys[[4]]-kellys[[1]]*kellys[[2]]*kellys[[3]]*kellys[[4]];



Clear[data2];
Clear[DPOPred2];
If[debugflag==1,Print["Start of DPOPred"]];
data2 = ConstantArray[0.0,Length[DPOResult]-50+1];

Do[ data2[[j-49]] =DPOResult[[j]] ,{j,50,Length[DPOResult]}];
Clear[DPOPred2,minmpe,minrmse];
If[optionflag==1,
Clear[DPOA,DPOw1,DPOw2,DPOw3,DPOw4];
{minrmse,minmpe,DPOPred2,DPOA,DPOw1,DPOw2,DPOw3,DPOw4}=
NeuralNet1[data2,nodeslayer,inneriterations,rho,toler,numpasses,50,{},{},{},{},1.0,optionflag,deTrendflag,debugflag];
];
If[optionflag==0,
Clear[DPOA2,DPOw12,DPOw22,DPOw32,DPOw42];
{minrmse,minmpe,DPOPred2,DPOA2,DPOw12,DPOw22,DPOw32,DPOw42}=NeuralNet1[data2,nodeslayer,inneriterations,rho,toler,numpasses,50,DPOw1,DPOw2,DPOw3,DPOw4,DPOA,optionflag,deTrendflag,debugflag];
];
If[debugflag==1&&optionflag<2,Print["minmpe = " , minmpe,"   minrmse=",minrmse]];

If[optionflag==2,
Clear[temp1];
{plot2,temp1} =  MusicFinal[data2,50 ,data2[[-1]],55,0,debugflag];
DPOPred2=Flatten[temp1[[1,All]]];
];
If[optionflag==3,
Clear[dwt,dwd,dwtpredict,dwtdata];
dwd=DiscreteWaveletTransform[RandomReal[1,50],BiorthogonalSplineWavelet[],5];

dwt = DiscreteWaveletTransform[data2,BiorthogonalSplineWavelet[], 5,Padding->0.0];
Clear[temp1,temp2,temp3,temp4,temp5,temp6,temp7];

temp2=8;
temp6={};
While[temp2<50,temp2=temp2+8];
temp7=ConstantArray[0,10];
 Do[

Clear[temp3];
temp3 =Normal[dwd][[i,2]];
temp4 =Length[temp3];
temp5=Normal[dwt][[i,2]];

Clear[temp1,dwtpredict,dwtpredict2];
dwtpredict = ConstantArray[0,{3,temp4}];
{plot2,dwtpredict2}=  MusicFinal[temp5,temp4 ,temp5[[-1]],55,0,debugflag];
dwtpredict=Flatten[dwtpredict2[[1,All]]];
temp5=dwd["WaveletIndex"][[i]];
temp6=Append[temp6,temp5-> dwtpredict[[1;;temp4]]];
temp7[[i]]=Length[temp3]+temp5;
,{i,1,10}];

dims = dwd["DataDimensions"];

Clear[temp1];

temp1=DiscreteWaveletData[temp6,dwt["Wavelet"],dwt["Transform"],{50}];

DPOPred2= InverseWaveletTransform[temp1];

];


If [Length[data2]>0,
Clear[temp1];
temp1 = data2[[-1]]-DPOPred2[[1]];
Do[DPOPred2[[j]]=DPOPred2[[j]]+temp1;,{j,1,50}];

];

Clear[temp1];
{temp1,intDPOpred}=getIntegrate2[DPOPred2,1,1,Length[DPOPred2]];


Clear[DailyACCpred];
Clear[data2];
If[debugflag==1,Print["Start of DailyACCPred"]];
If[Length[DailyAcc]>0,
data2 = ConstantArray[0.0,Length[DailyAcc]];

Do[ data2[[j]] =DailyAcc[[j]] ,{j,1,Length[DailyAcc]}];
Clear[DailyACCpred,minmpe,minrmse];
If[optionflag==1,
Clear[DACCA,DACCw1,DACCw2,DACCw3,DACCw4];
{minrmse,minmpe,DailyACCpred,DACCA,DACCw1,DACCw2,DACCw3,DACCw4}=
NeuralNet1[data2,nodeslayer,inneriterations,rho,toler,numpasses,90,{},{},{},{},1.0,optionflag,deTrendflag,debugflag];
];
If[optionflag==0,
Clear[DACCA2,DACCw12,DACCw22,DACCw32,DACCw42];
{minrmse,minmpe,DailyACCpred,DACCA2,DACCw12,DACCw22,DACCw32,DACCw42}=NeuralNet1[data2,nodeslayer,inneriterations,rho,toler,numpasses,90,DACCw1,DACCw2,DACCw3,DACCw4,DACCA,optionflag,deTrendflag,debugflag];
];
If[debugflag==1&&optionflag<2,Print["minmpe = " , minmpe,"   minrmse=",minrmse]];

If[optionflag==2,
Clear[temp1];
{plot2,temp1} =  MusicFinal[data2,90 ,data2[[-1]],55,0,debugflag];
DailyACCpred=Flatten[temp1[[1,All]]];
];
If[optionflag==3,
Clear[dwt,dwd,dwtpredict,dwtdata];
dwd=DiscreteWaveletTransform[RandomReal[1,90],BiorthogonalSplineWavelet[],5];

dwt = DiscreteWaveletTransform[data2,BiorthogonalSplineWavelet[], 5,Padding->0.0];
Clear[temp1,temp2,temp3,temp4,temp5,temp6,temp7];

temp2=8;
temp6={};
While[temp2<90,temp2=temp2+8];
temp7=ConstantArray[0,10];
 Do[

Clear[temp3];
temp3 =Normal[dwd][[i,2]];
temp4 =Length[temp3];
temp5=Normal[dwt][[i,2]];

Clear[temp1,dwtpredict,dwtpredict2];
dwtpredict = ConstantArray[0,{3,temp4}];
{plot2,dwtpredict2}=  MusicFinal[temp5,temp4 ,temp5[[-1]],55,0,debugflag];
dwtpredict=Flatten[dwtpredict2[[1,All]]];
temp5=dwd["WaveletIndex"][[i]];
temp6=Append[temp6,temp5-> dwtpredict[[1;;temp4]]];
temp7[[i]]=Length[temp3]+temp5;
,{i,1,10}];

dims = dwd["DataDimensions"];

Clear[temp1];

temp1=DiscreteWaveletData[temp6,dwt["Wavelet"],dwt["Transform"],{90}];
DailyACCpred= InverseWaveletTransform[temp1];
];
If [Length[data2]>0,
Clear[temp1];
temp1 = data2[[-1]]-DailyACCpred[[1]];
Do[DailyACCpred[[j]]=DailyACCpred[[j]]+temp1;,{j,1,90}];

];

Clear[temp1];
{temp1,intDailyACCpred} = getIntegrate2[DailyACCpred,1,1,Length[DailyACCpred]];
,
DailyACCpred=ConstantArray[0,1];
intDailyACCpred =ConstantArray[0,1];];





Clear[MACDpred2];
Clear[data2];
If[debugflag==1,Print["Start of MACDpred"]];
data2 = ConstantArray[0.0,Length[BuySignal]-50+1];

Do[ data2[[j-49]] =BuySignal[[j]] ,{j,50,Length[BuySignal]}];

Clear[MACDpred2,minmpe,minrmse];
If[optionflag==1,
Clear[MACDA,MACDw1,MACDw2,MACDw3,MACDw4];
{minrmse,minmpe,MACDpred2,MACDA,MACDw1,MACDw2,MACDw3,MACDw4}=NeuralNet1[data2,nodeslayer,inneriterations,rho,toler,numpasses,90,{},{},{},{},1.0,optionflag,deTrendflag,debugflag];
];

If[optionflag==0,
Clear[MACDA2,MACDw12,MACDw22,MACDw32,MACDw42];
{minrmse,minmpe,MACDpred2,MACDA2,MACDw12,MACDw22,MACDw32,MACDw42}=NeuralNet1[data2,nodeslayer,inneriterations,rho,toler,numpasses,90,MACDw1,MACDw2,MACDw3,MACDw4,MACDA,optionflag,deTrendflag,debugflag];
];

If[debugflag==1&&optionflag<2,Print["minmpe = " , minmpe,"   minrmse=",minrmse]];
If[optionflag==2,
Clear[temp1];
{plot2,temp1} =  MusicFinal[data2,90 ,data2[[-1]],55,0,debugflag];
MACDpred2=Flatten[temp1[[1,All]]];
];
If[optionflag==3,
Clear[dwt,dwd,dwtpredict,dwtdata];
dwd=DiscreteWaveletTransform[RandomReal[1,90],BiorthogonalSplineWavelet[],5];

dwt = DiscreteWaveletTransform[data2,BiorthogonalSplineWavelet[], 5,Padding->0.0];
Clear[temp1,temp2,temp3,temp4,temp5,temp6,temp7];

temp2=8;
temp6={};
While[temp2<90,temp2=temp2+8];
temp7=ConstantArray[0,10];
 Do[

Clear[temp3];
temp3 =Normal[dwd][[i,2]];
temp4 =Length[temp3];
temp5=Normal[dwt][[i,2]];

Clear[temp1,dwtpredict,dwtpredict2];
dwtpredict = ConstantArray[0,{3,temp4}];
{plot2,dwtpredict2} =  MusicFinal[temp5,temp4 ,temp5[[-1]],55,0,debugflag];
dwtpredict = Flatten[dwtpredict2[[1,All]]];
temp5=dwd["WaveletIndex"][[i]];
temp6=Append[temp6,temp5-> dwtpredict[[1;;temp4]]];
temp7[[i]]=Length[temp3]+temp5;
,{i,1,10}];

dims = dwd["DataDimensions"];

Clear[temp1];

temp1=DiscreteWaveletData[temp6,dwt["Wavelet"],dwt["Transform"],{90}];
MACDpred2= InverseWaveletTransform[temp1];
];
If [Length[data2]>0,
Clear[temp1];
temp1 = data2[[-1]]-MACDpred2[[1]];
Do[MACDpred2[[j]]=MACDpred2[[j]]+temp1;,{j,1,90}];

];


Clear[ACCpred];
Clear[data2];
If[debugflag==1,Print["Start of ACCpred"]];
If[Length[Accumulation]>0,
data2 = ConstantArray[0.0,Length[Accumulation]];

Do[ data2[[j]] =Accumulation[[j]] ,{j,1,Length[Accumulation]}];
data2 = data2 - Min[Accumulation]+100;

Clear[ACCpred,minmpe,minrmse];
If[optionflag==1,
Clear[ACCA,ACCw1,ACCw2,ACCw3,ACCw4];
{minrmse,minmpe,ACCpred,ACCA,ACCw1,ACCw2,ACCw3,ACCw4}=NeuralNet1[data2,nodeslayer,inneriterations,rho,toler,numpasses,90,{},{},{},{},1.0,optionflag,deTrendflag,debugflag];
];
If [optionflag==0,
Clear[ACCA2,ACCw12,ACCw22,ACCw32,ACCw42];
{minrmse,minmpe,ACCpred,ACCA2,ACCw12,ACCw22,ACCw32,ACCw42}=NeuralNet1[data2,nodeslayer,inneriterations,rho,toler,numpasses,90,ACCw1,ACCw2,ACCw3,ACCw4,ACCA,optionflag,deTrendflag,debugflag];
];

If[debugflag==1&&optionflag<2,Print["minmpe = " , minmpe,"   minrmse=",minrmse]];
If[optionflag==2,
Clear[temp1];
{plot3,temp1} =  MusicFinal[data2,numbersteps ,data2[[-1]],55,0,debugflag];
ACCpred=Flatten[temp1[[1,All]]];
];
If[optionflag==3,
Clear[dwt,dwd,dwtpredict,dwtdata];
dwd=DiscreteWaveletTransform[RandomReal[1,90],BiorthogonalSplineWavelet[],5];

dwt = DiscreteWaveletTransform[data2,BiorthogonalSplineWavelet[], 5,Padding->0.0];
Clear[temp1,temp2,temp3,temp4,temp5,temp6,temp7];

temp2=8;
temp6={};
While[temp2<90,temp2=temp2+8];
temp7=ConstantArray[0,10];
 Do[

Clear[temp3];
temp3 =Normal[dwd][[i,2]];
temp4 =Length[temp3];
temp5=Normal[dwt][[i,2]];

Clear[temp1,dwtpredict,dwtpredict2];
dwtpredict = ConstantArray[0,{3,temp4}];
{plot2,dwtpredict2} =  MusicFinal[temp5,temp4 ,temp5[[-1]],55,0,debugflag];
dwtpredict=Flatten[dwtpredict2[[1,All]]];
temp5=dwd["WaveletIndex"][[i]];
temp6=Append[temp6,temp5-> dwtpredict[[1;;temp4]]];
temp7[[i]]=Length[temp3]+temp5;
,{i,1,10}];

dims = dwd["DataDimensions"];

Clear[temp1];

temp1=DiscreteWaveletData[temp6,dwt["Wavelet"],dwt["Transform"],{90}];
ACCpred= InverseWaveletTransform[temp1];
];
If [Length[data2]>0,
Clear[temp1];


Accumulation = Accumulation-Min[Accumulation]+MinAccumulation;
ACCpred = ACCpred -ACCpred[[1]]+Accumulation[[-1]];
Clear[temp1,temp2,coeffs];
{coeffs,temp1,temp2}=getPercentErrorLinear[Accumulation,debugflag];
{xa4, xb4, ratios4, extenlst4, intlist4, pdflist4, outlst4} = getData[SeasonalFlag,data2,numpts2,extendflag,debugflag];
If[debugflag==1,Print["******2"]];
If[debugflag==1,Print[Dimensions[ratios3],Dimensions[intlist3],Dimensions[pdflist3],Dimensions[outlst3]]];
{dB4, pdB4,phasedistpdf4} = generateMagPhase[ratios4, intlist4,pdflist4,outlst4, xa4, xb4, IndicatorPaths,numbersteps,1.0,debugflag];
If[debugflag==1,Print["******3"]];
temperatures4 = generateTemperatures[dB4,Accumulation[[-1]],coeffs];

{conf014,conf104,conf254,conf504,conf754,conf904,conf994,indxlist4,ratioALLC4,sumval14,ratio334,ratio504,ratio804,ratio994} = calculateConfLevels[temperatures4,pdB4,Accumulation[[-1]],dis,negFlag,0];
{callup4,calldown4,call24,put24,confcall4,confput4,confcall104,confcall504,confcall804,confcall904,confput104,confput504,confput804,confput904, valueforwardup4, valueforwarddown4,valuesinupd4,valuesindownd4,meanpath4,diffprob4} = calculateFutureValues[Accumulation,temperatures4, pdB4,interestRate,Accumulation[[-1]], Accumulation[[-1]],dis, T,debugflag]; 

If [debugflag==1,Print["Accpred : ",conf504]];
Clear[conf014,conf254,conf754,conf994,indxlist4,ratioALLC4,sumval14,ratio334,ratio504,ratio804,ratio994,callup4,calldown4,call24,put24,confcall4,confput4,confcall104,confcall504,confcall804,confcall904,confput104,confput504,confput804,confput904, valueforwardup4, valueforwarddown4,valuesinupd4,valuesindownd4,diffprob4];

,meanpath4=conf504=conf104=conf904=ConstantArray[0,1];];


Clear[temp1];
{temp1,intACCpred} = getIntegrate2[ACCpred,1,1,Length[ACCpred]];
,
ACCpred=ConstantArray[0,1];
intACCpred=ConstantArray[0,1];];





Clear[data2];Clear[RTPrcpred2];
If[debugflag==1,Print["Start of RTPrcpred"]];
If[Length[RT]>0,
data2 = ConstantArray[0.0,Length[RT]];
Do[ data2[[j]] =RTPercPrice[[j]] ,{j,1,Length[RT]}];
Clear[RTPrcpred2,minrmse,minmpe];
If[optionflag==1,
Clear[RTPrcA,RTPrcw1,RTPrcw2,RTPrcw3,RTPrcw4];
{minrmse,minmpe,RTPrcpred2,RTPrcA,RTPrcw1,RTPrcw2,RTPrcw3,RTPrcw4}=NeuralNet1[data2,nodeslayer,inneriterations,rho,toler,numpasses,90,{},{},{},{},1.0,optionflag,deTrendflag,debugflag];
];
If[optionflag==0,
Clear[RTPrcA2,RTPrcw12,RTPrcw22,RTPrcw32,RTPrcw42];
{minrmse,minmpe,RTPrcpred2,RTPrcA2,RTPrcw12,RTPrcw22,RTPrcw32,RTPrcw42}=NeuralNet1[data2,nodeslayer,inneriterations,rho,toler,numpasses,90,RTPrcw1,RTPrcw2,RTPrcw3,RTPrcw4,RTPrcA,optionflag,deTrendflag,debugflag];
];

If[debugflag==1&&optionflag<2,Print["minmpe = " , minmpe,"   minrmse=",minrmse]];
If[optionflag==2,
Clear[temp1];
{plot2,temp1}=  MusicFinal[data2,90 ,data2[[-1]],55,0,debugflag];
RTPrcpred2=Flatten[temp1[[1,All]]];
];
If[optionflag==3,
Clear[dwt,dwd,dwtpredict,dwtdata];
dwd=DiscreteWaveletTransform[RandomReal[1,90],BiorthogonalSplineWavelet[],5];

dwt = DiscreteWaveletTransform[data2,BiorthogonalSplineWavelet[], 5,Padding->0.0];
Clear[temp1,temp2,temp3,temp4,temp5,temp6,temp7];

temp2=8;
temp6={};
While[temp2<90,temp2=temp2+8];
temp7=ConstantArray[0,10];
 Do[

Clear[temp3];
temp3 =Normal[dwd][[i,2]];
temp4 =Length[temp3];
temp5=Normal[dwt][[i,2]];

Clear[temp1,dwtpredict,dwtpredict2];

{plot2,dwtpredict2} =  MusicFinal[temp5,temp4 ,temp5[[-1]],55,0,debugflag];
dwtpredict=Flatten[dwtpredict2[[1,All]]];
temp5=dwd["WaveletIndex"][[i]];
temp6=Append[temp6,temp5-> dwtpredict[[1;;temp4]]];
temp7[[i]]=Length[temp3]+temp5;
,{i,1,10}];

dims = dwd["DataDimensions"];

Clear[temp1];

temp1=DiscreteWaveletData[temp6,dwt["Wavelet"],dwt["Transform"],{90}];
RTPrcpred2= InverseWaveletTransform[temp1];
];
If [Length[data2]>0,
Clear[temp1];
RTPercPrice = RTPercPrice-Min[RTPercPrice]+MinPercPriceRT;
RTPrcpred2=RTPrcpred2-RTPrcpred2[[1]]+RTPercPrice[[-1]];


];


Clear[temp1,intRTPrcpred2];
{temp1,intRTPrcpred2} = getIntegrate2[RTPrcpred2,1,1,Length[RTPrcpred2]];
,
RTPrcpred2=ConstantArray[0,1];
intRTPrcpred2=ConstantArray[0,1];];




Clear[data2];Clear[RTVolpred2];
If[debugflag==1,Print["Start of RTVolpred"]];
If[Length[RT]>0,
data2 = ConstantArray[0.0,Length[RT]];
Do[ data2[[j]] =RTPercVol[[j]] ,{j,1,Length[RT]}];
Clear[RTVolpred2,minmpe,minrmse];
If[optionflag==1,
Clear[RTVolA,RTVolw1,RTVolw2,RTVolw3,RTVolw4];
{minrmse,minmpe,RTVolpred2,RTVolA,RTVolw1,RTVolw2,RTVolw3,RTVolw4}=NeuralNet1[data2,nodeslayer,inneriterations,rho,toler,numpasses,90,{},{},{},{},1.0,optionflag,deTrendflag,debugflag];
];
If[optionflag==0,
Clear[RTVolA2,RTVolw12,RTVolw22,RTVolw32,RTVolw42];
{minrmse,minmpe,RTVolpred2,RTVolA2,RTVolw12,RTVolw22,RTVolw32,RTVolw42}=NeuralNet1[data2,nodeslayer,inneriterations,rho,toler,numpasses,90,RTVolw1,RTVolw2,RTVolw3,RTVolw4,RTVolA,optionflag,deTrendflag,debugflag];

];

If[debugflag==1&&optionflag<2,Print["minmpe = " , minmpe,"   minrmse=",minrmse]];
If[optionflag==2,
Clear[temp1];
{plot2,temp1}=  MusicFinal[data2,90 ,data2[[-1]],55,0,debugflag];
RTVolpred2=Flatten[temp1[[1,All]]];
];
If[optionflag==3,
Clear[dwt,dwd,dwtpredict,dwtdata];
dwd=DiscreteWaveletTransform[RandomReal[1,90],BiorthogonalSplineWavelet[],5];

dwt = DiscreteWaveletTransform[data2,BiorthogonalSplineWavelet[], 5,Padding->0.0];
Clear[temp1,temp2,temp3,temp4,temp5,temp6,temp7];

temp2=8;
temp6={};
While[temp2<90,temp2=temp2+8];
temp7=ConstantArray[0,10];
 Do[

Clear[temp3];
temp3 =Normal[dwd][[i,2]];
temp4 =Length[temp3];
temp5=Normal[dwt][[i,2]];

Clear[temp1,dwtpredict,dwtpredict2];
dwtpredict = ConstantArray[0,{3,temp4}];
{plot2,dwtpredict2} =  MusicFinal[temp5,temp4 ,temp5[[-1]],55,0,debugflag];
dwtpredict=Flatten[dwtpredict2[[1,All]]];
temp5=dwd["WaveletIndex"][[i]];
temp6=Append[temp6,temp5-> dwtpredict[[1;;temp4]]];
temp7[[i]]=Length[temp3]+temp5;
,{i,1,10}];

dims = dwd["DataDimensions"];

Clear[temp1];

temp1=DiscreteWaveletData[temp6,dwt["Wavelet"],dwt["Transform"],{90}];
RTVolpred2= InverseWaveletTransform[temp1];
];
If [Length[data2]>0,
Clear[temp1];
RTPercVol=RTPercVol -Min[RTPercVol]+MinPercVolRT;
RTVolpred2 = RTVolpred2 - RTVolpred2[[1]]+RTPercVol[[-1]];

];


Clear[temp1,intRTVolpred2];
{temp1,intRTVolpred2}=getIntegrate2[RTVolpred2,1,1,Length[RTVolpred2]];
,
RTVolpred2=ConstantArray[0,1];
intRTVolpred2=ConstantArray[0,1];];



Clear[RTpred];
RTpred =N[ (RTPrcpred2/(10^(-100)+Max[Abs[RTPrcpred2]])+RTVolpred2/(10^(-100)+Max[Abs[RTVolpred2]]))*50.0];

If[optionflag==1,
If[FileExistsQ["outoptions2.txt"],DeleteFile["outoptions2.txt"]];

Save["outoptions2.txt",{futureA,futurew1,futurew2,futurew3,futurew4,ACCA,ACCw1,ACCw2,ACCw3,ACCw4,DPOA,DPOw1,DPOw2,DPOw3,DPOw4,MACDA,MACDw1,MACDw2,MACDw3,MACDw4,RTPrcA,RTPrcw1,RTPrcw2,RTPrcw3,RTPrcw4,RTVolA,RTVolw1,RTVolw2,RTVolw3,RTVolw4,DACCA,DACCw1,DACCw2,DACCw3,DACCw4}];

];
];













Clear[temp4];
temp4 = Join[{YrData2[[-1]]},meanpath];
Clear[meanpath];
meanpath = temp4;
(*calculate the limits and most probable values of the call and put options,output them for user viewing to text fields*)
val0=0;val1 =0;val2=0;val3=0;val4=0;val5=0;
Clear[temp4,temp3];


Do[val0=valueforwardup[[j]]+val0;val5=valueforwarddown[[j]]+val5;val1 = val1 + confcall10[[j]]/dis[[j]];val2 = val2 + confcall90[[j]]/dis[[j]];
    val3 = val3 + confput10[[j]]/dis[[j]];val4 = val4+confput90[[j]]/dis[[j]],{j,2,futuresteps}];
val0 = N[val0/(futuresteps-1)];val5 = N[val5/(futuresteps-1)];
val1 = N[val1/(futuresteps-1)];val2 = N[val2/(futuresteps-1)];
val3 = N[val3/(futuresteps-1)];val4=N[val4/(futuresteps-1)];
(*calculate confidence levels for Risk analysis*)
val6=0;val7=0;val8=0;val9=0;
Do[val6 = val6+confcall60[[j+1]]/dis[[j+1]];val7=val7+confput60[[j+1]]/dis[[j+1]];val8=val8+confcall50[[j+1]]/dis[[j+1]];val9=val9+confput50[[j+1]]/dis[[j+1]],{j,1,futuresteps-1}];
val6=N[val6/(futuresteps-1)];
val7=N[val7/(futuresteps-1)];
val8 = N[val8/(futuresteps-1)];
val9=N[val9/(futuresteps-1)];
If [debugflag==1,Print[Dimensions[temperatures]]];

Clear[temp3];
Clear[temp1,temp2];
{temp1,temp2,temp3}=getPercentErrorLinear[meanpath[[1;;futuresteps]],debugflag];
negFlag=0;If [N[Sum[temp1[[1]]*i+temp1[[2]],{i,1,futuresteps}]/futuresteps]<s0,negFlag=1];
{conf01,conf10,conf25,conf50,conf75,conf90,conf99,indxlist,ratioALLC,sumval1,ratio33,ratio50,ratio80,ratio99} = calculateConfLevels[temperatures,pdB,SpotPrice,dis,negFlag,0];

If[debugflag==1,Print["FinishedcalcConfLevels"]];

(* Risk analysis,compute the area under the curve of conf99 to yesterdays price or volume value to the area between yesterdays price or volume value and conf01 *)

If[debugflag==1,Print["StartofPlots"]];
(*plot future value of call option,plot confidence limits on that option as well*)
Clear[temp,temp4,temp5];
If [StartDate==0,
temp = ConstantArray[{},Length[YrData2]];
temp4 = ConstantArray[{},Length[YrData2]];
temp5= ConstantArray[{},Length[YrData2]]];
If [StartDate>0,
temp = ConstantArray[{},Length[YrData]];
temp4 = ConstantArray[{},Length[YrData]];
temp5= ConstantArray[{},Length[YrData]]];


Clear[EMA40,EMA200,temp4];

If [SeasonalFlag==0,
EMA40 =EMA200= ConstantArray[0.0,Length[YrData2]],ratioMA=-1;
EMA40=EMA200=ConstantArray[0.0,1]];
If[SeasonalFlag==1 || Length[YrData2]<200,
ratioMA=-1.0];

If [SeasonalFlag==0,
If [Length[YrData2]≥ 40,
EMA40[[40]]=N[Total[YrData2[[1;;40]]]/40]];
If[debugflag==1,Print["*^2"]];
If [Length[YrData2]> 200,
EMA200[[200]]=N[Total[YrData2[[1;;200]]]/200];
Do[EMA200[[i]]=N[2/201*Total[YrData2[[i-199;;i]]]/200+199/201*EMA200[[i-1]]],{i,201,Length[YrData2]}];
]];
Clear[temp,temp2];

If [SeasonalFlag==1,temp =EMA200[[-FortyBDAYS;;-1]],
temp = EMA200[[-Length[YrData2];;-1]]];
If [SeasonalFlag==0,
If [Length[YrData2]>40,
Do[EMA40[[i]]=N[2/41*Total[YrData2[[i-39;;i]]]/40+39/41*EMA40[[i-1]]],{i,41,Length[YrData2]}]];
If[Length[YrData2]≥200,ratioMA = N[EMA40[[Length[YrData2]]]/EMA200[[Length[YrData2]]]]]];
If [SeasonalFlag==1,temp2 = EMA40[[-FortyBDAYS;;-1]],
temp2=EMA40[[-Length[YrData2];;-1]]];

Clear[EMA40,EMA200];
EMA40=temp2;
EMA200=temp;


If[debugflag==1,Print["*3.1"]];

Clear[temp2,temp3];
If [Length[datelisttemp2]>0,
If [SeasonalFlag==0,
temp3 = Join[YrData2,meanpath[[2;;futuresteps]]];

Clear[EMA40a,EMA200a];
EMA40a = ConstantArray[0.0,Length[temp3]];
EMA200a=ConstantArray[0.0,Length[temp3]];

If [Length[temp3]> 40,
EMA40a[[40]]=N[Total[temp3[[1;;40]]]/40];
Do[EMA40a[[i]]=N[2/41*Total[temp3[[i-39;;i]]]/40+39/41*EMA40a[[i-1]]],{i,41,Length[temp3]}]];
If[debugflag==1,Print["*^3.2"]];

If [Length[temp3]> 200,
EMA200a[[200]]=N[Total[temp3[[1;;200]]]/200];
Do[EMA200a[[i]]=N[2/201*Total[temp3[[i-199;;i]]]/200+199/201*EMA200a[[i-1]]],{i,201,Length[temp3]}];
If[debugflag==1,Print["*5"]];
Clear[temp4,temp5,temp6];
temp5=matlabFind1[EMA200a,Greater,0.0];
temp6 = matlabFind1[EMA200a,Equal,0.0];
Do[EMA200a[[temp6[[i]]]]=10.^200.,{i,1,Length[temp6]}];
If[debugflag==1,Print["*6"]];
Clear[temp7,temp8];
temp7 = temp3[[Length[YrData2];;Length[temp3]]];
If [Length[YrData2]>year,
flaga=1;flagb=Length[YrData2]-1;
If[debugflag==1,Print["*6a"]];
If[negFlag==0,temp8=N[EMA40a[[Length[YrData2];;Length[temp3]]]/EMA200a[[Length[YrData2];;Length[temp3]]]],
temp8=N[EMA200a[[Length[YrData2];;Length[temp3]]]/EMA40a[[Length[YrData2];;Length[temp3]]]]],
flaga=0;flagb=199;
If[negFlag==0,temp8= N[EMA40a[[200;;Length[temp3]]]/EMA200a[[200;;Length[temp3]]]],temp8= N[EMA200a[[200;;Length[temp3]]]/EMA40a[[200;;Length[temp3]]]]]];
If[debugflag==1,Print["*6b"]];
If[negFlag==1,temp4=matlabFind1[temp8,LessEqual,.7143];,
temp4 = matlabFind1[temp8,GreaterEqual,1.39];];
If[debugflag==1,Print["*6c"]];
If[negFlag==0,
If[flaga==0,If[Length[temp4]>0,If[temp4[[1]]<Length[YrData2]-flagb,If[ temp8[[Length[YrData2]-flagb]]<1.39, flagb=Length[YrData2]-1;
temp8=N[EMA200a[[Length[YrData2];;Length[temp3]]]/EMA40a[[Length[YrData2];;Length[temp3]]]];temp4=matlabFind1[temp8,GreaterEqual,1.39]]]]];
,If[flaga==0,If[Length[temp4]>0,If[temp4[[1]]<Length[YrData2]-flagb,If[ temp8[[Length[YrData2]-flagb]]>N[1/1.39], flagb=Length[YrData2]-1;
temp8=N[EMA200a[[Length[YrData2];;Length[temp3]]]/EMA40a[[Length[YrData2];;Length[temp3]]]];temp4=matlabFind1[temp8,LessEqual,N[1/1.39]]]]]];];

If[debugflag==1,Print["*6d"]];
If [Length[temp4]==0,position=Length[temp3];If[negFlag==0,price = EMA200a[[-1]]*1.4,price=EMA200a[[-1]]*.7143],
position=temp4[[1]]+flagb;price =temp3[[position]]];
If[debugflag==1,Print["*6e"]];
If[debugflag==1,Print["Price = ",price,", ratio = ",If[negFlag==0,temp8[[position-flagb]],1/temp8[[position-flagb]]]]],
EMA200a[[Length[temp3]]]=N[Total[temp3[[1;;Length[temp3]]]]/Length[temp3]];position=Length[temp3];If [negFlag==0,price =1.4*EMA200a[[-1]],price=.7143*EMA200a[[-1]]]]; 
If[debugflag==1,Print["*6f"]];

Clear[temp,temp4,temp5,temp1];

If [StartDate==0,

temp =temp1= ConstantArray[{},Length[datelisttemp2]];
temp4 = ConstantArray[{},Length[datelisttemp2]];
temp5 = ConstantArray[{},Length[datelisttemp2]];


Clear[coeffs1,temp6,temp7];
{coeffs1,temp6,temp7}=getPercentErrorLinear[YrData2[[datelisttemp2]],debugflag];
If[debugflag==1,Print["**********",temp3,datelisttemp2]];

Clear[leastpurseerr];
leastpurseerr = ConstantArray[{},futuresteps];
Do[leastpurseerr[[i-Length[YrData2]]]={DateData3[[i-Length[YrData2]]],N[i*coeffs1[[1]]+coeffs1[[2]]]};,{i,Length[YrData2]+1,Length[YrData2]+futuresteps}];

Do [temp1[[j]]={Transpose[YearData[[datelisttemp2]]][[1,j]],N[coeffs1[[1]]*datelisttemp2[[j]]+coeffs1[[2]]]};temp[[j]] = {Transpose[YearData[[datelisttemp2]]][[1,j]],cubPCR1[[datelisttemp2[[j]]]]};
temp4[[j]]={Transpose[YearData[[datelisttemp2]]][[1,j]],EMA40[[datelisttemp2[[j]]]]};
temp5[[j]]={Transpose[YearData[[datelisttemp2]]][[1,j]],EMA200[[datelisttemp2[[j]]]]},{j,1,Length[datelisttemp2]}]];

If [StartDate>0,
temp =temp1= ConstantArray[{},Length[datelisttemp1]];
temp4 = ConstantArray[{},Length[datelisttemp1]];
temp5 = ConstantArray[{},Length[datelisttemp1]];
Clear[coeffs1,temp6,temp7];
{coeffs1,temp6,temp7}=getPercentErrorLinear[YrData[[datelisttemp1]],debugflag];

Clear[leastpurseerr];
leastpurseerr = ConstantArray[{},futuresteps];
Do[leastpurseerr[[i-Length[YrData]]]={DateData3[[i-Length[YrData]]],N[i*coeffs[[1]]+coeffs[[2]]]};,{i,Length[YrData]+1,Length[YrData]+futuresteps}];



Do [temp1[[j]]={Transpose[YearData2[[datelisttemp1]]][[1,j]],N[coeffs[[1]]*datelisttemp1[[j]]+coeffs[[2]]]};temp[[j]] = {Transpose[YearData2[[datelisttemp1]]][[1,j]],cubPCR1[[datelisttemp1[[j]]]]};
temp4[[j]]={Transpose[YearData2[[datelisttemp1]]][[1,j]],EMA40[[datelisttemp1[[j]]]]};
temp5[[j]]={Transpose[YearData2[[datelisttemp1]]][[1,j]],EMA200[[datelisttemp1[[j]]]]},{j,1,Length[datelisttemp1]}]],
price=0;

If [StartDate==0,

Clear[temp1,temp];
temp1=temp = ConstantArray[{},Length[datelisttemp2]];

Clear[coeffs,temp6,temp7];
{coeffs,temp6,temp7}=getPercentErrorLinear[YrData2[[datelisttemp2]],debugflag];
If[debugflag==1,Print[temp3,datelisttemp2]];

Clear[leastpurseerr];
leastpurseerr = ConstantArray[{},futuresteps];
Do[leastpurseerr[[i-Length[YrData2]]]={DateData3[[i-Length[YrData2]]],N[i*coeffs1[[1]]+coeffs1[[2]]]};,{i,Length[YrData2]+1,Length[YrData2]+futuresteps}];



Do [temp[[j]] = {Transpose[YearData[[datelisttemp2]]][[1,j]],cubPCR1[[datelisttemp2[[j]]]]};temp1[[j]]={Transpose[YearData[[datelisttemp2]]][[1,j]],N[coeffs1[[1]]*datelisttemp2[[j]]+coeffs1[[2]]]},{j,1,Length[datelisttemp2]}]];
If [StartDate>0,
Clear[temp1,temp];

temp1 =temp= ConstantArray[{},Length[datelisttemp1]];

Clear[coeffs1,temp6,temp7];
{coeffs1,temp6,temp7}=getPercentErrorLinear[YrData[[datelisttemp1]],debugflag];
Clear[leastpurseerr];
leastpurseerr = ConstantArray[{},futuresteps];
Do[leastpurseerr[[i-Length[YrData]]]={DateData3[[i-Length[YrData]]],N[i*coeffs1[[1]]+coeffs1[[2]]]};,{i,Length[YrData]+1,Length[YrData]+futuresteps}];

Do [temp[[j]] = {Transpose[YearData2[[datelisttemp1]]][[1,j]],cubPCR1[[datelisttemp1[[j]]]]};temp1[[j]]={Transpose[YearData2[[datelisttemp1]]][[1,j]],N[coeffs1[[1]]*datelisttemp1[[j]]+coeffs1[[2]]]},{j,1,Length[datelisttemp1]}]]];
,
Clear[temp,temp1,temp2,temp3,temp5,temp6,temp7];
temp=temp1=temp2=temp3=temp5=temp6=temp7=ConstantArray[0,1];
EMA40a =EMA40=EMA200= ConstantArray[0.0,1];
EMA200a=ConstantArray[0.0,1];
price=0;
];
Clear[temp12];
temp12 = Join[YrData2[[-34;;-1]],Flatten[futurepath[[1,All]]]];
If [debugflag== 1,Print["FourierRSI"];];
FourierRSI = getRSI[temp12,17];
FourierRSI=FourierRSI[[35;;Length[FourierRSI]]];
If[debugflag==1,Print["End of FourierRSI"];]; 
If[Length[datelisttemp2]>0,
If [SeasonalFlag==1,
If [StartDate==0,

plotPrices=Show[DateListPlot[YearData[[datelisttemp2]],Joined->True,PlotRange-> Automatic,GridLines->Automatic,AxesLabel->{"Past Days","underlying"},PlotLabel->"Past years data for "<>stockTicker<>"\nMagenta-200 day EMA,Green-40 day EMA,Red-Cubic fit least Perc. Error\nOrange- Linear fit least Perc. Error",RotateLabel->True],DateListPlot[temp,Joined-> True,GridLines->Automatic,PlotStyle->Directive[Red] ],DateListPlot[temp1,Joined-> True,GridLines->Automatic,PlotStyle->Directive[Orange]]],
plotPrices=Show[DateListPlot[YearData2[[datelisttemp1]],Joined->True,GridLines->Automatic,AxesLabel->{"Past Days","underlying"},PlotLabel->"Past years data for "<>stockTicker<>"\nMagenta-200 day EMA,Green-40 day EMA,Red-Cubic fit least Perc. Error\nOrange- Linear fit least Perc. Error",RotateLabel->True],DateListPlot[temp,Joined-> True,GridLines->Automatic,PlotStyle->Directive[Red] ],DateListPlot[temp1,Joined-> True,GridLines->Automatic,PlotStyle->Directive[Orange]]]];,
If [StartDate==0,
plotPrices=Show[DateListPlot[YearData[[datelisttemp2]],Joined->True,PlotRange-> Automatic,GridLines->Automatic,AxesLabel->{"Past Days","underlying"},PlotLabel->"Past years data for "<>stockTicker<>"\nMagenta-200 day EMA,Green-40 day EMA\nRed- Linear fit least Perc. Error",RotateLabel->True,PlotStyle-> Blue],
DateListPlot[temp1,Joined-> True,GridLines->Automatic,PlotStyle->Directive[Red]],DateListPlot[temp4,Joined-> True,GridLines->Automatic,PlotStyle-> Directive[Green]],DateListPlot[temp5,Joined-> True,GridLines->Automatic,PlotStyle-> Directive[Magenta]]],
plotPrices=Show[DateListPlot[YearData2[[datelisttemp1]],Joined->True,PlotRange-> Automatic,GridLines->Automatic,AxesLabel->{"Past Days","underlying"},PlotLabel->"Past years data for "<>stockTicker<>"\nMagenta-200 day EMA,Green-40 day EMA,Red-Cubic fit least Perc. Error\nOrange- Linear fit least Perc. Error",RotateLabel->True],DateListPlot[temp,Joined-> True,GridLines->Automatic,PlotStyle->Directive[Red] ],DateListPlot[temp1,Joined-> True,GridLines->Automatic,PlotStyle->Directive[Orange]] ,DateListPlot[temp4,Joined-> True,GridLines->Automatic,PlotStyle-> Directive[Green]],DateListPlot[temp5,Joined-> True,GridLines->Automatic,PlotStyle-> Directive[Magenta]]]]];


plotDiffprob= ListLinePlot[{uppersdv,lowersdv},Joined->True,AxesLabel-> {"Future Days","Mean Difference"},PlotLabel-> "Mean deviation of difference from most probable meanpath",GridLines->Automatic,PlotStyle->{Blue,Red}];
plotRSI = ListLinePlot[RSIdata[[-Floor[365/5];;-1]],Joined->True,AxesLabel-> {"Past Days","RSI"},PlotLabel-> "RSI for past years data with EMA 17 days",GridLines->Automatic,PlotStyle->Red];
plotFourierRSI= ListLinePlot[FourierRSI,Joined->True,AxesLabel-> {"Future Days","RSI"},PlotLabel-> "Fourier RSI for future days data with EMA 17 days",GridLines->Automatic,PlotStyle->Red];
plotDPO=ListLinePlot[DPOResult[[-Floor[365/5];;-1]],Joined->True,Filling-> True,AxesLabel-> {"Past Days","DPO"},PlotLabel-> "DPO for past years data",GridLines->Automatic,PlotStyle->Magenta];
plotMACD=ListLinePlot[BuySignal,Joined->True,AxesLabel-> {"Past Days","MACD"},PlotLabel-> "MACD buy signal for past years data",GridLines->Automatic,PlotStyle->Magenta];
plotBandWidth=ListLinePlot[BandWidth,Joined->True,AxesLabel-> {"Past Days","BandWidth"},PlotLabel-> "Bollinger BandWidth+100 days in future",GridLines->Automatic,PlotStyle->Magenta];
plotPercb = ListLinePlot[{Percb[[-Floor[365/5];;-1]],ConstantArray[80.0,Floor[365/5]],ConstantArray[20.0,Floor[365/5]]},Joined->True,AxesLabel-> {"Past Days","%b"},PlotLabel-> "Bollinger Percent b",GridLines->Automatic,PlotStyle->{Magenta,Red,Red}];
plotBollinger = ListLinePlot[{YrData2,EMAN2,Upper,Lower},Joined->True,AxesLabel-> {"Past Days","Bands"},PlotLabel-> "Bollinger Bands",GridLines->Automatic,PlotStyle->{Black,Magenta,Red,Red}];
plotPercK =  ListLinePlot[{PercK,percD,percDslow},Joined->True,AxesLabel-> {"Past Days","%K"},PlotLabel->"Stochastics-%K-Black,%D-Red,%Dslow-Dark Cyan",GridLines->Automatic,PlotStyle->{Black,Red,Darker Cyan}];
plotMoment=ListLinePlot[Momentum,Joined->True,AxesLabel-> {"Past Days","Momentum"},PlotLabel-> "Momentum Oscillator",GridLines->Automatic,PlotStyle->Magenta,RotateLabel-> True];
If[Length[VolEMA2]>0,
plotVolEMA = ListLinePlot[{VolEMA2[[-Floor[Length[VolEMA2]/6];;-1]],VolEMA3[[-Floor[Length[VolEMA2]/6];;-1]],VolEMA9[[-Floor[Length[VolEMA2]/6];;-1]]},Joined-> True,AxesLabel-> {"Past Days","VolEMA"},PlotLabel->"EMA2,EMA3,EMA5 of Volume-Red,Blue,Magenta",GridLines-> Automatic ,PlotStyle-> {Red,Blue,Magenta}];
,
plotVolEMA = ListLinePlot[{0,0},Joined-> True,AxesLabel-> {"Past Days","VolEMA"},PlotLabel->"EMA2,EMA3,EMA5 of Volume-Red,Blue,Magenta",GridLines-> Automatic ,PlotStyle-> {Red,Blue,Magenta}];
];
plotRT=ListLinePlot[RT[[-Floor[Length[RT]/6];;-1]],Joined->True,AxesLabel->{"Past Days","RT"},PlotLabel-> "Relative Timing\n>0 is good, <0 is worse",GridLines-> Automatic,PlotStyle-> Blue,RotateLabel-> True];

plotRTPrcPrc=ListLinePlot[RTPercPrice[[-Floor[Length[RT]/6];;-1]],Joined->True,AxesLabel->{"Past Days","RT"},PlotLabel-> "Relative Timing Percent Price(Red) <0 %<0; >0 %>0",GridLines-> Automatic,PlotStyle->Blue,RotateLabel-> True];
plotRTPrcVol=ListLinePlot[RTPercVol[[-Floor[Length[RT]/6];;-1]],Joined->True,AxesLabel->{"Past Days","RT"},PlotLabel-> "Relative Timing Percent Volume(Red) <0 %<0; >0 %>0",GridLines-> Automatic,PlotStyle->Blue,RotateLabel-> True];
plotIntRTPrc=ListLinePlot[IntPercPriceRT[[-Floor[Length[RT]/6];;-1]],Joined->True,AxesLabel->{"Past Days","IntRT"},PlotLabel-> "Integrated Relative Timing Percent Price(Magenta)\n <0 is worse, >0 is good",GridLines-> Automatic,PlotStyle->Magenta,RotateLabel-> True];
plotIntRTVol=ListLinePlot[IntPercVolRT[[-Floor[Length[RT]/6];;-1]],Joined->True,AxesLabel->{"Past Days","IntRT"},PlotLabel-> "Integrated RelativeTime Percent Volume(Magenta)\n <0 is worse, >0 is good",GridLines-> Automatic,PlotStyle-> Magenta,RotateLabel-> True];
plotIntRT=ListLinePlot[IntRT[[-Floor[Length[RT]/6];;-1]],Joined->True,AxesLabel->{"Past Days","IntRT"},PlotLabel-> "Integrated RelativeTime (Magenta)\n<0 is worse, >0 is good",GridLines-> Automatic,PlotStyle-> Magenta,RotateLabel-> True];
plotAccumulation=ListLinePlot[Accumulation[[-Length[RT];;-1]],Joined->True,AxesLabel->{"Past Days","IntAccum"},PlotLabel-> "Integrated Market Action-Accumulation (Magenta))\n<0 means its being dumped, >0 is accumulated,100=100%",GridLines-> Automatic,PlotStyle-> Magenta,RotateLabel-> True];
plotDailyAcc=ListLinePlot[DailyAcc[[-Floor[Length[RT]/6];;-1]],Joined->True,AxesLabel->{"Past Days","Action"},PlotLabel-> "Market Pice-Volume product action (Magenta)\nnegative slope means its being dumped,positive slope is accumulated",GridLines-> Automatic,PlotStyle-> Magenta,RotateLabel-> True];

If[optionflag >-1,
plotintDPOpred=ListLinePlot[intDPOpred,Joined->True,Filling-> True,AxesLabel-> {"Past Days","Forecast of intDPO"},PlotLabel-> " Integrated Forecast of DPO ",GridLines->Automatic,PlotStyle->Red];
plotDailyACCpred = ListLinePlot[DailyACCpred,Joined->True,AxesLabel-> {"Future Days","Action"},PlotLabel-> "Prediction of Market Action\n<0 is worse, >0 is good",GridLines->Automatic,PlotStyle-> Red];
plotintDlyACCpred= ListLinePlot[intDailyACCpred,Joined->True,AxesLabel-> {"Future Days","IAction"},PlotLabel-> "Prediction of Integrated Market Action\n<0 is worse, >0 is good",GridLines->Automatic,PlotStyle-> Red];
plotACCpred=ListLinePlot[{ACCpred,conf504,conf104,conf904,meanpath4},Joined->True,AxesLabel-> {"Future Days","Accum"},PlotLabel-> "Prediction of Market Accumulation\n Magenta-90% conf limits",GridLines->Automatic,PlotStyle-> {Red,Blue,Magenta,Magenta,Blue}];
plotintACCpred=ListLinePlot[intACCpred,Joined->True,AxesLabel-> {"Future Days","IAccum"},PlotLabel-> "Prediction of Integrated Market Accumulation",GridLines->Automatic,PlotStyle-> Red];
plotRTpred=ListLinePlot[RTpred,Joined->True,AxesLabel->{"Future Days","RTpred"},PlotLabel-> "Predicted Percent RelativeTime(Red)\n<0 is worse, >0 is good",GridLines-> Automatic,PlotStyle-> Red,RotateLabel-> True];
plotRTPrcpred=ListLinePlot[RTPrcpred2,Joined->True,AxesLabel->{"Future Days","RTPrcpred"},PlotLabel-> "Predicted Percent RelativeTime Price(Red)\n<0 is worse, >0 is good",GridLines-> Automatic,PlotStyle-> Red,RotateLabel-> True];
plotintRTPrcpred2=ListLinePlot[intRTPrcpred2,Joined->True,AxesLabel->{"Future Days","intRTPrcpred"},PlotLabel-> "Predicted Integrated Percent RelativeTime Price(Red)\n<0 is worse, >0 is good",GridLines-> Automatic,PlotStyle-> Red,RotateLabel-> True];
plotRTVolpred=ListLinePlot[RTVolpred2,Joined->True,AxesLabel->{"Future Days","RTpred"},PlotLabel-> "Predicted Percent RelativeTime Volume(Red)\n<0 is worse, >0 is good",GridLines-> Automatic,PlotStyle-> Red,RotateLabel-> True];
plotintRTVolpred=ListLinePlot[intRTVolpred2,Joined->True,AxesLabel->{"Future Days","intRTpred"},PlotLabel-> "Predicted Integrated Percent RelativeTime Volume(Red)\n<0 is worse, >0 is good",GridLines-> Automatic,PlotStyle-> Red,RotateLabel-> True];
plotDPOpred=ListLinePlot[DPOPred2,Joined->True,AxesLabel->{"Future Days","DPOpred"},PlotLabel-> "Predicted DPO, 20 days in past to 30 days in future(Red)",GridLines-> Automatic,PlotStyle-> Red,RotateLabel-> True];
plotMACDpred=ListLinePlot[MACDpred2,Joined->True,AxesLabel->{"Future Days","MACDpred"},PlotLabel-> "Predicted MACD buy signal(Red)",GridLines-> Automatic,PlotStyle->Red,RotateLabel-> True];
];
,
plotProfit=ListLinePlot[{0,0},Joined-> True,AxesLabel-> {"Future Days","Profit"},PlotLabel-> "Profit per day from all 4 legs",GridLines-> Automatic,PlotStyle-> Blue];
plotPrices =DateListPlot[{{DateString[],{0,0}},{enddate,{0,0}}},Joined->True,GridLines->Automatic,AxesLabel->{"Past Days","underlying"},PlotLabel->"Past years data for "<>stockTicker<>"\nMagenta-200 day EMA,Green-40 day EMA,Red-Cubic fit least Perc. Error\nOrange- Linear fit least Perc. Error",RotateLabel->True];
plotRSI = ListLinePlot[RSIdata[[-Floor[365/5];;-1]],Joined->True,AxesLabel-> {"Past Days","RSI"},PlotLabel-> "RSI for past years data with EMA 17 days",GridLines->Automatic,PlotStyle->Red];
plotFourierRSI= ListLinePlot[FourierRSI,Joined->True,AxesLabel-> {"Future Days","RSI"},PlotLabel-> "Fourier RSI for future days data with EMA 17 days",GridLines->Automatic,PlotStyle->Red];
plotDPO=ListLinePlot[DPOResult[[-Floor[365/5];;-1]],Joined->True,Filling-> True,AxesLabel-> {"Past Days","DPO"},PlotLabel-> "DPO for past years data",GridLines->Automatic,PlotStyle->Magenta];
plotMACD=ListLinePlot[BuySignal,Joined->True,AxesLabel-> {"Past Days","MACD"},PlotLabel-> "MACD buy signal for past years data",GridLines->Automatic,PlotStyle->Magenta];
plotBandWidth=ListLinePlot[BandWidth,Joined->True,AxesLabel-> {"Past Days","BandWidth"},PlotLabel-> "Bollinger BandWidth+100 days in future",GridLines->Automatic,PlotStyle->Magenta];
plotPercb = ListLinePlot[{Percb[[-Floor[365/5];;-1]],ConstantArray[80.0,Floor[365/5]],ConstantArray[20.0,Floor[365/5]]},Joined->True,AxesLabel-> {"Past Days","%b"},PlotLabel-> "Bollinger Percent b",GridLines->Automatic,PlotStyle->{Magenta,Red,Red}];
plotBollinger = ListLinePlot[{{0,0},EMAN2,Upper,Lower},Joined->True,AxesLabel-> {"Past Days","Bands"},PlotLabel-> "Bollinger Bands",GridLines->Automatic,PlotStyle->{Black,Magenta,Red,Red}];
plotPercK =  ListLinePlot[{PercK,percD,percDslow},Joined->True,AxesLabel-> {"Past Days","%K"},PlotLabel->"Stochastics-%K-Black,%D-Red,%Dslow-Dark Cyan",GridLines->Automatic,PlotStyle->{Black,Red,Darker Cyan}];
plotMoment=ListLinePlot[Momentum,Joined->True,AxesLabel-> {"Past Days","Momentum"},PlotLabel-> "Momentum Oscillator",GridLines->Automatic,PlotStyle->Magenta,RotateLabel-> True];
plotVolEMA = ListLinePlot[{VolEMA2[[-Floor[Length[VolEMA2]/6];;-1]],VolEMA3[[-Floor[Length[VolEMA2]/6];;-1]],VolEMA9[[-Floor[Length[VolEMA2]/6];;-1]]},Joined-> True,AxesLabel-> {"Past Days","VolEMA"},PlotLabel->"EMA2,EMA3,EMA5 of Volume-Red,Blue,Magenta",GridLines-> Automatic ,PlotStyle-> {Red,Blue,Magenta}];
plotRT=ListLinePlot[{0,0},Joined->True,AxesLabel->{"Past Days","RT"},PlotLabel-> "Relative Timing\n>0 is good, <0 is worse",GridLines-> Automatic,PlotStyle-> Blue,RotateLabel-> True];
plotRTPrcPrc=ListLinePlot[{0,0},Joined->True,AxesLabel->{"Past Days","RT"},PlotLabel-> "Relative Timing Percent Price(Red) <0 %<0; >0 %>0",GridLines-> Automatic,PlotStyle->Blue,RotateLabel-> True];
plotRTPrcVol=ListLinePlot[{0,0},Joined->True,AxesLabel->{"Past Days","RT"},PlotLabel-> "Relative Timing Percent Volume(Red) <0 %<0; >0 %>0",GridLines-> Automatic,PlotStyle->Blue,RotateLabel-> True];
plotIntRTPrc=ListLinePlot[{0,0},Joined->True,AxesLabel->{"Past Days","IntRT"},PlotLabel-> "Integrated Relative Timing Percent Price(Magenta)\n <0 is worse, >0 is good",GridLines-> Automatic,PlotStyle->Magenta,RotateLabel-> True];
plotIntRTVol=ListLinePlot[{0,0},Joined->True,AxesLabel->{"Past Days","IntRT"},PlotLabel-> "Integrated RelativeTime Percent Volume(Magenta)\n <0 is worse, >0 is good",GridLines-> Automatic,PlotStyle-> Magenta,RotateLabel-> True];
plotIntRT=ListLinePlot[{0,0},Joined->True,AxesLabel->{"Past Days","IntRT"},PlotLabel-> "Integrated RelativeTime (Magenta)\n<0 is worse, >0 is good",GridLines-> Automatic,PlotStyle-> Magenta,RotateLabel-> True];
plotAccumulation=ListLinePlot[{0,0},Joined->True,AxesLabel->{"Past Days","IntAccumulation"},PlotLabel-> "Integrated Market Action-Accumulation (Magenta))\n<0 means its being dumped, >0 is accumulated,100=100%",GridLines-> Automatic,PlotStyle-> Magenta,RotateLabel-> True];
plotDailyAcc=ListLinePlot[{0,0},Joined->True,AxesLabel->{"Past Days","MarketAction"},PlotLabel-> "Market Pice-Volume product action (Magenta)\nnegative slope means its being dumped,positive slope is accumulated",GridLines-> Automatic,PlotStyle-> Magenta,RotateLabel-> True];];

If[debugflag==1,Print["*7b"]];
Clear[temp4,temp5,temp6,temp7,temp8,temp9,temp10,temp11];
temp6 = ConstantArray[{},{Length[datelisttemp2]}];
temp7 =ConstantArray[{},{Length[datelisttemp2]}];
temp8 =ConstantArray[{},{Length[datelisttemp2]}];
temp9 =ConstantArray[{},{Length[datelisttemp2]}];
temp10 = ConstantArray[{},{Length[datelisttemp2]}];
temp11 =  ConstantArray[{},{Length[datelisttemp2]}];
 temp4 =ConstantArray[{},{Length[datelisttemp2]}];
temp5= ConstantArray[{},{Length[datelisttemp2]}];


Do [ temp4[[j]] = {DateData2[[j]],sma3[[j]]};temp5[[j]] ={DateData2[[j]],sma10[[j]]};temp6[[j]]= {DateData2[[j]],sma18[[j]]};temp7[[j]]= {DateData2[[j]],sma1[[j]]};temp8[[j]]= {DateData2[[j]],sma18v[[j]]};temp9[[j]]= {DateData2[[j]],sma10v[[j]]};temp10[[j]]={DateData2[[j]],sma3v[[j]]};,{j,1,Length[datelisttemp2]}];
If[debugflag==1,Print[temp4];];
If[debugflag==1,Print["Length datelisttemp2=",Length[datelisttemp2]]];

If [debugflag==1,Print["*7baa"];];
plotEMAs =
DateListPlot[{temp6[[-Floor[Length[temp6]/6];;-1]],temp4[[-Floor[Length[temp4]/6];;-1]],temp5[[-Floor[Length[temp5]/6];;-1]]},PlotRange-> Automatic,Joined-> True,GridLines-> Automatic,PlotStyle-> {Blue,Magenta,Darker[ Green]},PlotLabel-> "Price Moving Averages Indicators 3(Magenta) 9(Green) 18(Blue) EMA day"];
plotEMAs2 = 
DateListPlot[{temp9[[-Floor[Length[temp9]/6];;-1]],temp10[[-Floor[Length[temp10]/6];;-1]],temp8[[-Floor[Length[temp8]/6];;-1]]},PlotRange-> Automatic,Joined-> True,GridLines-> Automatic,PlotStyle-> {Darker[ Green],Magenta,Blue},PlotLabel-> "Volume Moving Averages Indicators 3(Magenta) 9(Green) 18(Blue) EMA day"];

If [debugflag==1,Print["*7bab"];];





Clear[temp6,temp3,temp5];
temp6=temp3=temp5 = temp12= ConstantArray[{},futuresteps];
Do[If[futurepath[[1,i]]≥ s0 ,temp12[[i]]=futurepath[[1,i]]-s0;,temp12[[i]]=0.0;];,{i,1,futuresteps}];
Do[temp6[[j+1]]={j,valueforwardup[[j+1]]};temp3[[j+1]]={j,confcall10[[j+1]]};temp5[[j+1]]={j,confcall90[[j+1]]},{j,0,futuresteps-1}];
If [debugflag==1,Print["*7baba"];];
plotFutureCall=ListLinePlot[{temp6,temp3,temp5,temp12},PlotRange-> {Min[confcall10],Max[confcall90,temp12]},PlotStyle->{Blue, Red,Red,Magenta},AxesLabel->{"days ahead","dollars"},GridLines->Automatic,PlotLabel->"Present Value: Call Option;\n90% conf lim Red,Fourier Magenta",RotateLabel->True];
If [debugflag==1,Print["*7bac"];];
(* plot future value of put option, plot confidence limits as well *)
Clear[temp6,temp3,temp5,temp12];
temp12=ConstantArray[0.0,futuresteps];
If [debugflag==1,Print["*7bacb"];];
Do[If[futurepath[[1,i]]≤ s0 ,temp12[[i]]=s0-futurepath[[1,i]];,temp12[[i]]=0.0;];,{i,1,futuresteps}];
temp6=temp3=temp5 = ConstantArray[{},futuresteps];
If [debugflag==1,Print["*7bad"];];
Do[temp6[[j+1]]={j,valueforwarddown[[j+1]]};temp3[[j+1]]={j,confput10[[j+1]]};temp5[[j+1]]={j,confput90[[j+1]]},{j,0,futuresteps-1}];
plotFuturePut=ListLinePlot[{temp6,temp3,temp5,temp12},PlotRange-> {Min[confput10],Max[confput90,temp12]},PlotStyle->{Blue, Red,Red,Magenta},GridLines->Automatic,AxesLabel->{"days from today's date","dollars"},PlotLabel->"Present Value: Put Option;\n90% conf lim Red,Fourier Magenta",RotateLabel->True];
If [debugflag==1,Print["*7bae"];];

(* if volume actdata,plot log of confidence limits into future, otherwise plot confidence limits not in log form *)
If[debugflag== 1,Print["Startcubic"]];
Clear[temp11];
{temp11,volatility,vol2} = getPercentErrorCubic2[YrData2,temperatures,meanpath[[1;;futuresteps]]]; 
If[debugflag==1,Print["Endcubic"]];
Clear[temp5,temp,temp2,temp3,temp4,temp6,temp7,temp8];
temp = ConstantArray[{},Length[volatility]];
Do[ temp[[j]] = {j,volatility[[j]]},{j,1,Length[volatility]}];
temp=ConstantArray[{},futuresteps];
temp2 = ConstantArray[{},futuresteps];
temp3 = ConstantArray[{},futuresteps];
temp4=ConstantArray[{},futuresteps];
temp5=ConstantArray[{},futuresteps];
temp6 =ConstantArray[{},futuresteps];
temp7=ConstantArray[{},futuresteps];
temp8=ConstantArray[{},futuresteps];
Do[temp[[j]]={j,meanpath[[j]]};temp2[[j]] = {j,conf50[[j]]};temp3[[j]]={j,conf01[[j]]};temp4[[j]]={j,conf99[[j]]};temp5[[j]]={j,conf25[[j]]};temp6[[j]]={j,conf75[[j]]};temp7[[j]]={j,conf10[[j]]};temp8[[j]]={j,conf90[[j]]},{j,1,futuresteps}];

plotVolatility = ListLinePlot[volatility,AxesLabel->{"days ahead","Volatility"},GridLines->Automatic,PlotLabel->"Volatility Plot"];
plotConfLimits=ListLinePlot[{temp,temp2,temp3,temp4,temp5,temp6,temp7,temp8},PlotStyle->{Magenta,Blue,Green,Green,Cyan,Cyan,Red,Red},AxesLabel->{"future days","underlying $"},PlotLabel->"Confidence Lines",GridLines->Automatic,PlotLegends->{"mean path","50%", "1%","99%","25%","75%","10%","90%"},RotateLabel->True,ImageSize->{300,270}];
(* plot the most probable path, if price actdata,plot the 80% confidence limits as well *)
Clear[temp,temp2,temp3,temp4,temp5,temp6,temp7,temp8];

If [futuresteps>10,L=10,L=futuresteps];
VolumePlot = DateListPlot[YearVolume,Joined-> False,PlotStyle-> Red,PlotLabel-> "Volume on a given date",GridLines-> Automatic];
Clear[temp2,temp3,temp6];
If[debugflag==1,Print["*1"]];
callputratio =callputratioALL= ConstantArray[0.0,futuresteps];
Do[If[valueforwarddown[[j]]==   0.0,valueforwarddown[[j]]=10^(-40)];temp2=valueforwardup[[j]]/valueforwarddown[[j]];callputratio[[j]]=If[negFlag==1,-N[1./(1.+temp2)*100.],N[temp2/(1.+temp2)*100.]],{j,1,futuresteps}];
Clear[temp2,temp3];
temp3 =callputratio[[futuresteps;;futuresteps-L+1;;-1]];
If [negFlag==1,sgn1=-1.0,sgn1=1.0];

Clear[temp2,temp4,temp7];
Do[Do[If[temp3[[i]]*sgn1>temp3[[j]]*sgn1,temp2 = temp3[[i]];temp3[[i]]= temp3[[j]];temp3[[j]]=temp2],{i,j+1,L}],{j,1,L}];


If [negFlag==0,MostProbPerc = N[Max[temp3[[1;;L]]]],MostProbPerc = N[Min[temp3[[1;;L]]]]];


callputratioALL = sumval1;

If [debugflag==1,Print["*2a"];];
Clear[temp3,temp2,temp6,temp4,temp5,temp7];
temp3 = ConstantArray[{},198];
temp2 =temp6=ConstantArray[{},futuresteps];
temp5 = ConstantArray[0.0,futuresteps];
Do[temp3[[j]]={indxlist[[j]],ratioALLC[[j]]},{j,1,198}];

Do[temp2[[j+1]] = {j,N[callputratio[[j+1]]]};temp5[[j+1]]=callputratioALL[[j+1]];temp6[[j+1]]={j,temp5[[j+1]]},{j,0,futuresteps-1}];
If [negFlag==0,ratio = Max[callputratioALL[[futuresteps;;futuresteps-L+1;;-1]]],ratio = Min[callputratioALL[[futuresteps;;futuresteps-L+1;;-1]]]];
Clear[temp7,temp5];


PercentWincallputPlot = ListLinePlot[{temp2,temp6},PlotStyle->{ Red,Blue},PlotLabel-> "% Win Chance per day\n Red-Most Probable. Blue-ALL conf levels.",GridLines-> Automatic,PlotRange->If[negFlag==1,{-105,0},{0,105}],Joined-> True];
PercentWinPlot = ListLinePlot[temp3,PlotStyle-> Red,PlotLabel-> "% Win Chance versus probability of confidence level",GridLines-> Automatic,PlotRange->If[negFlag==1,{-105,0},{0,105}],Joined-> True];
If [debugflag==1,Print[Dimensions[callup]]];
         N1=50;

If [debugflag==1,Print["*2b"];];
Clear[img];
img=ConstantArray[{},Floor[(2*198+1-5+1)/4]+1];
k=1;Do[Do[If [calldown[[j,i]]==0.0,calldown[[j,i]]=10^(-20)],{j,1,2*198+1}],{i,1,futuresteps}];Do[i=j;If[i>199,i=2*198+1-i];img[[k]]=ListLinePlot[N[callup[[j,1;;futuresteps]]/calldown[[j,1;;futuresteps]]],PlotStyle -> RGBColor[1-N[(N1+i)/(198+1+N1)],1,1-N[(N1+i)/(198+1+N1)]],GridLines-> Automatic,Joined-> True];k=k+1,{j,5,2*198+1,4}];
kmax=k-1;
If[debugflag==1,Print["*3"]];
Clear[temp4];
temp4 = ConstantArray[0,L];

temp4[[1;;L]]=Ordering[N[valueforwardup[[futuresteps-L+1;;futuresteps]]/valueforwarddown[[futuresteps-L+1;;futuresteps]]]];

call1 =(sgn1+1)/2* N[valueforwardup[[futuresteps-L+temp4[[L]]]]]+ N[valueforwardup[[futuresteps-L+temp4[[1]]]]]*(sgn1-1)/(-2);put1=(sgn1+1)/2*N[valueforwarddown[[futuresteps-L+temp4[[L]]]]]+(sgn1-1)/(-2)*N[valueforwarddown[[futuresteps-L+temp4[[1]]]]];

CallPutRatioPlot=Show[ ListLinePlot[N[callup[[1,1;;futuresteps]]/(calldown[[1,1;;futuresteps]]+10^(-20))],PlotRange-> {Min[callup[[1;;2*198+1,1;;futuresteps]]/calldown[[1;;2*198+1,1;;futuresteps]],valueforwardup/valueforwarddown],Max[callup[[1;;2*198+1,1;;futuresteps]]/calldown[[1;;2*198+1,1;;futuresteps]],valueforwardup/valueforwarddown]},PlotLabel->"Call/Put Ratios across days for different conf levels\n Red-Most Probable ratio per day",
PlotStyle -> RGBColor[1-N[N1/(198+1+N1)],1,1-N[N1/(198+1+N1)]],GridLines-> Automatic,Joined-> True],Table[img[[k]],{k,kmax}],ListLinePlot[valueforwardup/valueforwarddown,PlotStyle-> Red,Joined-> True]];
Clear[img];



Clear[temp1,temp5,temp6];
temp5=temp1 = ConstantArray[{},futuresteps];
temp6=ConstantArray[{},futuresteps];
If[debugflag==1,Print["*7"]];

Do[ temp5[[j]] = {j,price};temp1[[j]]=price;temp6[[j]]={DateData3[[j]],price};,{j,1,futuresteps}];

Clear[temp7];
Clear[temp8];
temp8=ConstantArray[{},futuresteps];
If[Length[Flatten[futurepath[[1,All]]]]>0,
If[debugflag==1,Print["*7a",futurepath,DateData3];]
Do[temp8[[j]]={DateData3[[j]],futurepath[[1,j]]};,{j,1,futuresteps}];
,
Do[temp8[[j]]={DateData3[[j]],0},{j,1,futuresteps}]];

Clear[temp9];
If[debugflag==1,Print["*8"]];
temp9 = ConstantArray[{},{futuresteps}];
Do[temp9[[j]]={DateData3[[j]],meanpath[[j]]};,{j,1,futuresteps}];

temp7=ConstantArray[{},futuresteps];
If[Length[Flatten[futurepath[[1,All]]]]>0,
Do[temp7[[j]]={j,futurepath[[1,j]]},{j,1,futuresteps}];
];
Clear[temp20,temp21];
temp20=temp21=ConstantArray[{},futuresteps];
Do[temp20[[j]]={DateData3[[j]],futurepath[[2,j]]};temp21[[j]]={DateData3[[j]],futurepath[[3,j]]};,{j,1,futuresteps}];
If[debugflag==1,Print["*9"]];
If[optionflag==0||optionflag==1,
plotFutureARMA = DateListPlot[{leastpurseerr,temp9,temp8,temp6}, PlotRange-> Automatic,PlotStyle-> {Black,Blue,Red,Magenta},Joined-> True,AxesLabel->{"days ahead","Future MeanPath"},PlotLabel->"least perc Err-Black,Most probable path(Blue),Neural Net Prediction(Red)\nEMA40/EMA200 ratio=1.4 is magenta",GridLines->Automatic,RotateLabel->True];
plotFutureARMA2= DateListPlot[{temp20,temp21}, PlotRange-> Automatic,PlotStyle-> {Orange,Gray},Joined-> True,AxesLabel->{"days ahead","Future Quantum"},PlotLabel->"Quantum Mechanics Uncertainty principle\nOrange is upper freq, Gray is lower freq",GridLines->Automatic,RotateLabel->True],
Clear[temp1];
If [optionflag==2,
temp1="least perc ERR(black),Most probable path(Blue),MUSIC Analysis Forecast(Red)\nEMA40/EMA200 ratio=1.4 is magenta",
temp1="least perc ERR(black),Most probable path(Blue),Wavelet Analysis Forecast(Red)\nEMA40/EMA200 ratio=1.4 is magenta"];plotFutureARMA = DateListPlot[{leastpurseerr,temp9,temp8,temp6},PlotRange-> Automatic,PlotStyle-> {Black,Blue,Red,Magenta},Joined-> True,AxesLabel->{"days ahead","Future MeanPath"},PlotLabel->temp1,GridLines->Automatic,RotateLabel->True];
plotFutureARMA2= DateListPlot[{temp20,temp21}, PlotRange-> Automatic,PlotStyle-> {Orange,Gray},Joined-> True,AxesLabel->{"days ahead","Future Quantum"},PlotLabel->"Quantum Mechanics Uncertainty principle\nOrange is upper freq, Gray is lower freq",GridLines->Automatic,RotateLabel->True];

];

Clear[leastpurseerr,temp6,temp8,temp9];
leastpurseerr=ConstantArray[{},futuresteps];
Do[leastpurseerr[[i-Length[YrData2]]]={i-Length[YrData2],N[i*coeffs1[[1]]+coeffs1[[2]]]};,{i,Length[YrData2]+1,Length[YrData2]+futuresteps}];
If[optionflag≥ 2|| optionflag== -1,
If [optionflag==2,
temp1="MUSIC Analysis Forecast(Red)\nleast % ERR-black, 98% conf levels Orange",
temp1="Wavelet Analysis Forecast(Red)\nleast % ERR-black, 98% conf levels Orange"];
temp6=temp8=temp9=ConstantArray[{},futuresteps];
Do[temp6[[j]]={j,conf50[[j]]}; temp8[[j]]={j,conf01[[j]]};temp9[[j]]={j,conf99[[j]]};,{j,1,futuresteps}];
plotNetForecast1=ListLinePlot[{leastpurseerr,temp7,temp5,temp6,temp8,temp9},PlotStyle-> {Black,Red,Magenta,Blue,Orange,Orange},PlotRange-> Automatic,AxesLabel->{"days ahead","Future Path"},PlotLabel->temp1,GridLines->Automatic,RotateLabel->True,Joined-> True];
If [optionflag==2,
temp1="MUSIC Analysis Forecast(Red)\nleast % ERR-black",
temp1="Wavelet Analysis Forecast(Red)\nleast % ERR-black"];plotNetForecast2= ListLinePlot[{leastpurseerr,temp7,temp5},PlotStyle-> {Black,Red,Magenta},PlotRange-> Automatic,AxesLabel->{"days ahead","Future Path"},PlotLabel->temp1,GridLines->Automatic,RotateLabel->True,Joined-> True];
,

plotNetForecast1 = ListLinePlot[{leastpurseerr,temp7,temp5,temp6,temp8,temp9},PlotStyle-> {Black,Red,Magenta,Blue,Orange,Orange},PlotRange-> Automatic,AxesLabel->{"days ahead","Future NetPath"},PlotLabel->"Neural Net Prediction of future price(Red)\nleast % ERR-black",GridLines->Automatic,RotateLabel->True,Joined-> True];
plotNetForecast2=ListLinePlot[{leastpurseerr,temp7,temp5},PlotStyle-> {Black,Red,Magenta},PlotRange-> Automatic,AxesLabel->{"days ahead","Future NetPath"},PlotLabel->"Neural Net Prediction of future price(Red)\nleast % ERR-black",GridLines->Automatic,RotateLabel->True,Joined-> True]];
If[debugflag==1,Print["*10"]];

If[debugflag==1,Print["*11"]];
Clear[temp2,temp3,callfourier,callputRATFour,PercWinFour];
temp2=temp3=ConstantArray[0.0,futuresteps];
If[Length[Flatten[futurepath[[1,All]]]]>0,
Do[v = futurepath[[1,j]]-SpotPrice; If [v≥ 0,temp2[[j-1]]=v/dis[[j-1]],temp3[[j-1]]=-v/dis[[j-1]]],{j,2,futuresteps}];
callfourier = N[Total[temp2]/(futuresteps-1)];putfourier=N[Total[temp3]/(futuresteps-1)];
callputRATFour = N[callfourier/(putfourier+.001)];
PercWinFour = N[callfourier/(callfourier+putfourier+.001)*100.0]
,
callfourier=0;
callputRATFour=0;
PercWinFour =0;
];

Clear[temp2,temp3,temp6];
temp2=temp3=temp6=  ConstantArray[{},futuresteps];

Clear[leastpurseerr];
leastpurseerr=ConstantArray[{},futuresteps];
Do[leastpurseerr[[i-Length[YrData2]]]={i-Length[YrData2],N[i*coeffs1[[1]]+coeffs1[[2]]]};,{i,Length[YrData2]+1,Length[YrData2]+futuresteps}];
Do[temp2[[j]]={j,N[meanpath[[j]]]};temp3[[j]]={j,N[conf10[[j]]]};temp6[[j]]={j,N[conf90[[j]]]},{j,1,futuresteps}];
plotMeanPath=ListLinePlot[{leastpurseerr,temp2,temp3,temp6,temp5},PlotStyle->{Black,Blue, Red,Red,Magenta},PlotRange-> {conf10[[-1]],conf90[[-1]]},GridLines->Automatic,PlotLabel->"Most Probable Path-blue,lst % err-black;\n 90% conf limits Red",AxesLabel->{"future days","prob Fut Val"},RotateLabel->True];
If[debugflag==1,Print["*12"]];
Clear[temp6,temp11];
If[position> Length[YrData2] && Length[YrData2]>0,
temp6= position-Length[YrData2];
temp6 =Floor[N[temp6/5.0]]*2+temp6;
,
If[debugflag==1,Print["*13"]];
temp6=1;
];
If[SeasonalFlag==1,temp11="-1",
temp11 = DatePlus[DateString[{"MonthName", "  ","Day","/","Year"}],temp6];
If[Length[StringCases[temp11,"Sat"]]>0,temp11=DatePlus[temp11,2]];
If[Length[StringCases[temp11,"Sun"]]>0,temp11=DatePlus[temp11,1]]];
Clear[temp,temp2];
If[debugflag==1,Print["*4.1"]];
If[Length[YearData]<200,
temp2 = StringJoin["ratio of EMA40 to EMA",IntegerString[Length[YrData]]];EMA200[[Length[YrData2]]] =  N[Total[YrData2[[1;;Length[YrData2]]]]/Length[YrData2]],
temp2 = "ratio of EMA40 to EMA200"];
If [debugflag==1,Print["*4.2"]];
callb = ConstantArray[0,4];
putb = ConstantArray[0,4];
callc = ConstantArray[0,4];
putc = ConstantArray[0,4];
calle=ConstantArray[0,4];
pute=ConstantArray[0,4];
Clear[temp2,temp3,temp6];

Do[Clear[temp6,temp7];

callBS=0;putBS=0;
temp7=N[strikes[[i]]];
If[busdays[[i]]>0,temp6=Join[YrData2,Flatten[futurepath[[1,1;;busdays[[i]]]]]];
If[Abs[OptionCounts[[i]]]>0&&busdays[[i]]>0,{callb[[i]],putb[[i]],sigma,DeltaCall,DeltaPut,Gamma2,Vega,ThetaCall,ThetaPut,RhoCall,RhoPut}=getBSGreeks[YrData,busdays[[i]],interestRate,temp7,debugflag];,{callb[[i]],putb[[i]],sigma,DeltaCall,DeltaPut,Gamma2,Vega,ThetaCall,ThetaPut,RhoCall,RhoPut}=getBSGreeks[YrData,futuresteps,interestRate,temp7,debugflag];];
If[Abs[OptionCounts[[i]]]>0,{callBS,putBS,sigma,DeltaCall,DeltaPut,Gamma2,Vega,ThetaCall,ThetaPut,RhoCall,RhoPut}=getBSGreeks[temp6,1,interestRate,temp7,debugflag]]];callc[[i]]=callBS;putc[[i]]=putBS;,{i,1,4}];
calle=ConstantArray[0,4];
pute = ConstantArray[0,4];
Clear[temp6];
Do[Clear[temp6,temp7];

callBS=0;putBS=0;
temp7=N[strikes[[i]]];If[busdays[[i]]>0,temp6=Join[YrData2,meanpath[[1;;busdays[[i]]]]];If[Abs[OptionCounts[[i]]]>0,{callBS,putBS,sigma,DeltaCall,DeltaPut,Gamma2,Vega,ThetaCall,ThetaPut,RhoCall,RhoPut}=getBSGreeks[temp6,1,interestRate,temp7,debugflag]]];calle[[i]]=callBS;pute[[i]]=putBS;,{i,1,4}];


If [debugflag==1,Print["*4.2a"]];
{callBS,putBS,sigma,DeltaCall,DeltaPut,Gamma2,Vega,ThetaCall,ThetaPut,RhoCall,RhoPut}=getBSGreeks[YrData2,futuresteps,interestRate,SpotPrice,debugflag];
If[debugflag==1,Print["*4.3"]];
Clear[temp1,temp3];
If[sgn1==1,temp1=N[call1/(put1+.001)/(1+call1/(put1+.001))*100.0],temp1=-N[put1/(call1+.001)/(1+put1/(call1+.001))*100.0]];
If[Mean[Flatten[futurepath[[1,All]]]]>SpotPrice,temp3=N[PercWinFour];,temp3=-N[putfourier/(callfourier+.001)/(1+putfourier/(callfourier+.001))*100.0];];
If[debugflag==1,Print["*4.4"]];
Clear[temp7];
If[optionflag==-1||optionflag==3,temp7="Wavelet Extrapolation"];
If[optionflag==0||optionflag==1,temp7="Neural Net Extrapolation"];
If[optionflag==2,temp7="Fourier Extrapolation"];
Clear[temp5,temp6,temp8,temp9,temp10,temp4,temp12];
temp8=StringJoin["Call " , temp7];
temp9=StringJoin["Put ",temp7];
temp10=StringJoin["ratio Call\n",temp7," to call BS"];
temp4=StringJoin["ratio Put ",temp7," to put BS"];
temp5 = StringJoin["ratio Call/Put\n", temp7] ;
temp6 = StringJoin["Win Percentage\n" ,temp7];
If [debugflag==1,Print["*4.5"]];

odds = N[call1/(10^(-100)+put1)]; (* Most probable odds *)
p = N[odds/(odds+1)];
If [debugflag==1,Print["4.6"]];
If[p≥0&&p≤1,
kelly =N[0.92*(p*(odds-1)-(1-p))/(odds-1+10^(-100))];,kelly=0.0];
odds=N[put1/(call1+10^(-100))];
p=N[odds/(1+odds)];
If [debugflag==1,Print["4.7"]];
If[p≥0&&p≤1,
kelly2 =N[0.92*(p*(odds-1)-(1-p))/(odds-1+10^(-100))];,kelly2=0.0;];

odds = N[callfourier/(10^(-100)+putfourier)];
p=N[odds/(odds+1)];
If[debugflag==1,Print["4.8"]];
If[p≥0&&p≤1,kellyfourier =N[0.92*(p*(odds-1)-(1-p))/(odds+10^(-100))];,kellyfourier=0.0;];
odds=N[putfourier/(10^(-100)+callfourier)];
p=N[odds/(odds+1)];
If[debugflag==1,Print["4.9"]];
If[p≥0&&p≤1,
kellyfourier2 =0.92*((1-p)*(1/(odds+10^(-100))+1)-p)*(odds-1);,
kellyfourier2=0.0;];
If[debugflag==1,Print["5.0"]];
Do[If[OptionCounts[[i]]<0,If [(OptionTypes[[i]]=="Call"||OptionTypes[[i]]=="call"||OptionTypes[[i]]=="CALL"),Do[profit[[j]]=profit[[j]]+callb[[i]]*100*Abs[OptionCounts[[i]]];,{j,1,busdays[[i]]}];];
If[(OptionTypes[[i]]=="Put"||OptionTypes[[i]]=="put"||OptionTypes[[i]]=="PUT"),Do[profit[[j]]=profit[[j]]+putb[[i]]*100*Abs[OptionCounts[[i]]];,{j,1,busdays[[i]]}]];];,{i,1,4}];
(* Close the Trade *)
If[debugflag==1,Print["5.1"]];
Do[If[OptionCounts[[i]]<0,If[(OptionTypes[[i]]=="Call"||OptionTypes[[i]]=="call"||OptionTypes[[i]]=="CALL"),profit[[busdays[[i]]]]=profit[[busdays[[i]]]] - Abs[OptionCounts[[i]]]*callc[[i]]*100];
If[(OptionTypes[[i]]=="Put"||OptionTypes[[i]]=="put"||OptionTypes[[i]]=="PUT"),profit[[busdays[[i]]]]=profit[[busdays[[i]]]]-putc[[i]]*100*Abs[OptionCounts[[i]]];];];,{i,1,4}];
If[debugflag==1,Print["5.2"]];
Do[If[OptionCounts[[i]]<0,If [(OptionTypes[[i]]=="Call"||OptionTypes[[i]]=="call"||OptionTypes[[i]]=="CALL"),Do[profit2[[j]]=profit2[[j]]+callb[[i]]*100*Abs[OptionCounts[[i]]];,{j,1,busdays[[i]]}];];
If[(OptionTypes[[i]]=="Put"||OptionTypes[[i]]=="put"||OptionTypes[[i]]=="PUT"),Do[profit2[[j]]=profit2[[j]]+putb[[i]]*100*Abs[OptionCounts[[i]]];,{j,1,busdays[[i]]}]];];,{i,1,4}];
(* Close the Trade *)

If[debugflag==1,Print["5.3"]];Do[If[OptionCounts[[i]]<0,If[(OptionTypes[[i]]=="Call"||OptionTypes[[i]]=="call"||OptionTypes[[i]]=="CALL"),profit2[[busdays[[i]]]]=profit2[[busdays[[i]]]] - Abs[OptionCounts[[i]]]*calle[[i]]*100];
If[(OptionTypes[[i]]=="Put"||OptionTypes[[i]]=="put"||OptionTypes[[i]]=="PUT"),profit2[[busdays[[i]]]]=profit2[[busdays[[i]]]]-pute[[i]]*100*Abs[OptionCounts[[i]]];];];,{i,1,4}];

If[debugflag==1,Print["5.4"]];




plotProfit2=ListLinePlot[profit2,Joined-> True,AxesLabel-> {"Future Days","Profit"},PlotLabel-> "Most Probable Profit per day from all 4 legs",GridLines-> Automatic,PlotStyle-> Blue];
plotProfit=ListLinePlot[profit,Joined-> True,AxesLabel-> {"Future Days","Profit"},PlotLabel-> "Fourier Profit per day from all 4 legs",GridLines-> Automatic,PlotStyle-> Blue];

If[googleflag==1,temp12="\nData from Google",temp12="\nData from Yahoo"];
timestamp2 = DateString[];
Print[timestamp1," , timestamp2=",timestamp2];

Labeled[Framed[Column[{If [forecastindicatorflag==1&&catastropheflag==1,

If[currencyflag==0,If[optionflag>-1,GraphicsGrid[{{plotPrices,plotpdf},{plotProfit,plotProfit2},{plotEMAs,plotFutureARMA},{,plotFutureARMA2},{plotEMAs2,plotMeanPath},{plotDiffprob,plotNetForecast1},{plotFutureCall,plotNetForecast2},{plotAccumulation,plotACCpred},{plotDailyAcc,plotDailyACCpred},{indicatorpredictplain,PlotIntMean3},{plotintDlyACCpred,plotintACCpred},{plotMACD,plotMACDpred},{plotRSI,plotBollinger},{plotPercb,plotBandWidth},{plotDPO,plotDPOpred},{plotintDPOpred},{plotMoment,plotVolEMA},{plotRT,plotRTPrcPrc},{plotIntRT,plotIntRTPrc},{plotRTpred,plotRTPrcpred},{plotRTPrcVol,plotIntRTVol},{plotintRTPrcpred2,plotintRTVolpred},{plotRTVolpred,plotPercK},{plotFuturePut,indicatorpredict2plain},{plotVolatility, indicatorspredict},{plotConfLimits,indicatorspredict2},{VolumePlot,PercentWincallputPlot},{CallPutRatioPlot,PercentWinPlot},{imagepoint9,imagepoint8},{imagepoint7,imagepoint6},{imagepoint5,imagepoint4},{image1point1,image1point2},{image1point3,image1point4},{image1point5,image1point6}},ImageSize-> {1200,7500}],GraphicsGrid[{{plotPrices,plotpdf},{plotProfit,plotProfit2},{plotEMAs,plotFutureARMA},{,plotFutureARMA2},{plotEMAs2,plotMeanPath},{plotDiffprob}{plotFutureCall,indicatorpredictplain},{plotRSI,PlotIntMean3},{plotDailyAcc,plotAccumulation},{plotMACD,plotBollinger},{plotPercb,plotBandWidth},{plotDPO,plotPercK},{plotMoment,plotVolEMA},{plotRT,plotRTPrcPrc},{plotIntRT,plotIntRTPrc},{plotRTPrcVol,plotIntRTVol},{plotFuturePut,indicatorpredict2plain},{plotVolatility, indicatorspredict},{plotConfLimits,indicatorspredict2},{VolumePlot,PercentWincallputPlot},{CallPutRatioPlot,PercentWinPlot},{imagepoint9,imagepoint8},{imagepoint7,imagepoint6},{imagepoint5,imagepoint4},{image1point1,image1point2},{image1point3,image1point4},{image1point5,image1point6}},ImageSize-> {1200,7500}]],GraphicsGrid[{{plotPrices,plotpdf},{plotProfit,plotProfit2},{plotEMAs,plotFutureARMA},{,plotFutureARMA2},{plotEMAs2,plotMeanPath},{plotDiffprob,plotNetForecast1},{plotFutureCall,plotNetForecast2},{plotAccumulation,plotACCpred},{indicatorpredictplain,PlotIntMean3},{plotDailyAcc,plotDailyACCpred},{plotMACD,plotMACDpred},{plotRSI,plotBollinger},{plotPercb,plotBandWidth},{plotDPO,plotDPOpred},{plotintDPOpred},{plotMoment,plotVolEMA},{plotintDlyACCpred,plotintACCpred},{plotRT,plotRTPrcPrc},{plotIntRT,plotIntRTPrc},{plotRTpred,plotRTPrcpred},{plotRTPrcVol,plotIntRTVol},{plotintRTPrcpred2,plotintRTVolpred},{plotRTVolpred,plotPercK},{plotVolatility, indicatorspredict},{plotConfLimits,PercentWincallputPlot},{CallPutRatioPlot,PercentWinPlot},{imagepoint9,imagepoint8},{imagepoint7,imagepoint6},{imagepoint5,imagepoint4},{image1point1,image1point2},{image1point3,image1point4},{image1point5,image1point6}},ImageSize-> {1200,7000}]],If [forecastindicatorflag==1&& catastropheflag==0,If[currencyflag==0,If[optionflag>-1,GraphicsGrid[{{plot1,plot3},{plotPrices,plotpdf},{plotProfit,plotProfit2},{plotEMAs,plotFutureARMA},{,plotFutureARMA2},{plotEMAs2,plotMeanPath},{plotDiffprob,plotNetForecast1},{plotFourierRSI,plotNetForecast2},{plotAccumulation,plotACCpred},{plotRSI,plotBollinger},{plotFutureCall,plotFuturePut},{plotDailyAcc,plotDailyACCpred},{indicatorpredictplain,PlotIntMean3},{plotintDlyACCpred,plotintACCpred},{plotMACD,plotMACDpred},{plotPercb,plotBandWidth},{plotDPO,plotDPOpred},{plotintDPOpred},{plotMoment,plotVolEMA},{plotRT,plotRTPrcPrc},{plotIntRT,plotIntRTPrc},{plotRTpred,plotRTPrcpred},{plotRTPrcVol,plotIntRTVol},{plotintRTPrcpred2,plotintRTVolpred},{plotRTVolpred,plotPercK},{indicatorpredict2plain},{plotVolatility, indicatorspredict},{plotConfLimits,indicatorspredict2},{VolumePlot,PercentWincallputPlot},{CallPutRatioPlot,PercentWinPlot}},ImageSize-> {1200,7500}],GraphicsGrid[{{plotPrices,plotpdf},{plotProfit,plotProfit2},{plotEMAs,plotFutureARMA},{,plotFutureARMA2},{plotEMAs2,plotMeanPath},{plotDiffprob,plotNetForecast1},{plotAccumulation,plotNetForecast2},{plotDailyAcc,}{plotFutureCall,indicatorpredictplain},{plotRSI,PlotIntMean3},{plotMACD,plotBollinger},{plotPercb,plotBandWidth},{plotDPO,plotPercK},{plotMoment,plotVolEMA},{plotRT,plotRTPrcPrc},{plotIntRT,plotIntRTPrc},{plotRTPrcVol,plotIntRTVol},{plotFuturePut,indicatorpredict2plain},{plotVolatility, indicatorspredict},{plotConfLimits,indicatorspredict2},{VolumePlot,PercentWincallputPlot},{CallPutRatioPlot,PercentWinPlot}},ImageSize-> {1200,6800}]],If[optionflag>-1,GraphicsGrid[{{plotPrices,plotpdf},{plotProfit,plotProfit2},{plotEMAs,plotFutureARMA},{,plotFutureARMA2},{plotEMAs2,plotMeanPath},{plotDiffprob,plotNetForecast1},{plotFutureCall,plotNetForecast2},{plotAccumulation,plotACCpred},{indicatorpredictplain,PlotIntMean3},{plotDailyAcc,plotDailyACCpred},{plotintDlyACCpred,plotintACCpred},{plotMACD,plotMACDpred},{plotRSI,plotBollinger},{plotPercb,plotBandWidth},{plotDPO,plotDPOpred},{plotintDPOpred},{plotMoment,plotVolEMA},{plotRT,plotRTPrcPrc},{plotIntRT,plotIntRTPrc},{plotRTpred,plotRTPrcpred},{plotRTPrcVol,plotIntRTVol},{plotintRTPrcpred2,plotintRTVolpred},{plotRTVolpred,plotPercK},{plotFuturePut,indicatorpredictplain},{plotVolatility, indicatorspredict},{plotConfLimits,PercentWincallputPlot},{CallPutRatioPlot,PercentWinPlot}},ImageSize-> {1200,7500}],GraphicsGrid[{{plotPrices,plotpdf},{plotProfit,plotProfit2},{plotEMAs,plotFutureARMA},{plotMeanPath,plotFutureCall},{plotDiffprob,plotNetForecast1},{,plotNetForecast2},{plotRSI,PlotIntMean3},{plotDailyAcc,plotAccumulation},{plotMACD,plotBollinger},{plotPercb,plotBandWidth},{plotDPO,plotPercK},{plotMoment,plotVolEMA},{plotRT,plotRTPrcPrc},{plotIntRT,plotIntRTPrc},{plotRTPrcVol,plotIntRTVol},{plotFuturePut,indicatorpredictplain},{plotVolatility, indicatorspredict},{plotConfLimits,PercentWincallputPlot},{CallPutRatioPlot,PercentWinPlot}},ImageSize-> {1200,5500}]]],
If[currencyflag==0,
GraphicsGrid[{{plotPrices,plotpdf},{plotProfit,plotProfit2},{plotEMAs,plotFutureARMA},{,plotFutureARMA2},{plotEMAs2,plotMeanPath},{plotFutureCall,plotFuturePut},{plotVolatility,plotConfLimits},{VolumePlot,PercentWinPlot}},ImageSize-> {1200,2500}],GraphicsGrid[{{plotPrices,plotpdf},{plotEMAs,plotFutureARMA},{,plotFutureARMA2},{plotFutureCall,plotMeanPath},{plotFuturePut,plotVolatility},{plotConfLimits,PercentWinPlot}},ImageSize-> {1200,2500}]]]],
Grid[{{Labeled[Framed[ToString[stockTicker]],"Stock Ticker Symbol", Top],Labeled[Framed[ToString[dataType]],"Data Type", Top],Labeled[Framed[ToString[enddate]],"Today's date", Top],Labeled[Framed[ToString[ExpDate]],"Expiration Date", Top]},{Labeled[Framed[SpotPrice,FrameStyle-> Green],"Spot Price", Top],Labeled[Framed[N[interestRate*100.0]],"Risk Free Rate", Top],Labeled[Framed[N[inflation*100.0]],"Inflation rate", Top],Labeled[Framed[N[dividend*100.0]],"Dividend Yield", Top]},{Labeled[Framed[ppast],"ppast", Top],Labeled[Framed[paths2],"Number of paths", Top],Labeled[Framed[percChange],"Percentage Increase", Top],Labeled[Framed[netGain],"Theoretical Gain Index", Top]},{Labeled[Framed[s0,FrameStyle-> Green],"Yesterday's price", Top],Labeled[Framed[N[call1/(put1+.001)]],"Most Prob. Call/Put ratio", Top],Labeled[Framed[N[temp1],FrameStyle-> Blue],"Most prob % win call/put",Top],Labeled[Framed[N[call2/(put2+.001)]],"ALL conf lev Call/Put ratio", Top]},{Labeled[Framed[N[MostProbPerc],FrameStyle-> Blue],"Most Prob. % Chance Win",Top],Labeled[Framed[N[ratio],FrameStyle-> Blue],"% chance win ALL conf lev", Top],
Labeled[Framed[N[probofMeanPath]],"Ratio of area mean error\n from area mean path",Top],Labeled[Framed[N[2*Erf[sigma]*100]],"Volatility sigma %",Top],},
{Labeled[Framed[ratioMA],temp2, Top],Labeled[Framed[temp11],"Sell Date at 1.40",Top],Labeled[Framed[price],"Sell PricePoint",Top],Labeled[Framed[N[YearsBack*365-1+StartDate]],"Number of real days\nof past data",Top]},{Labeled[Framed[ratio99,FrameStyle-> Magenta],"99% conf interval\n% win probability", Top],Labeled[Framed[ratio80,FrameStyle-> Magenta],"90% conf interval\n% win probability", Top],Labeled[Framed[ratio50,FrameStyle-> Magenta],"50% conf interval\n% win probability", Top],Labeled[Framed[ratio33,FrameStyle-> Magenta],"33% conf interval\n% win probability", Top]},{Labeled[Framed[N[pr]],"Prob of Ups", Top],Labeled[Framed[N[rat1-1]],"Mean Up", Top],Labeled[Framed[N[1-rat2]],"Mean Down", Top],Labeled[Framed[sumv],"mean value of Distbn", Top]},{Labeled[Framed[sdev1],"Stand. Dev. of Ups",Top],Labeled[Framed[sdev2],"Stand. Dev. of Downs",Top]},
{Labeled[Framed[val0,FrameStyle-> Red],"Most Probable Call value", Top],Labeled[Framed[confcall,FrameStyle-> Red],"Call Value, All conf lev",Top],Labeled[Framed[val5,FrameStyle-> Red],"Most Probable Put value", Top],Labeled[Framed[confput,FrameStyle-> Red],"Put Value, All conf lev",Top]},
{Labeled[Framed[N[val0/(callBS+.001)],FrameStyle-> Orange],"ratio of MP/BS call",Top],Labeled[Framed[N[confcall/(callBS+.001)],FrameStyle-> Orange],"ratio All conf lev/BS call",Top],Labeled[Framed[N[val5/(putBS+.001)],FrameStyle-> Orange],"ratio of MP to BS put",Top],Labeled[Framed[N[confput/(putBS+.001)],FrameStyle-> Orange],"ratio of All conf lev/BS put",Top]},
{Labeled[Framed[kelly],"Risk,Call Kelly,\nMost Probable Odds",Top],Labeled[Framed[kelly2],"Risk, Put Kelly",Top]},
{Labeled[Framed[N[callfourier],FrameStyle-> Red],temp8,Top],Labeled[Framed[N[putfourier]],temp9 ,Top],Labeled[Framed[N[kellyfourier],FrameStyle-> Red],"kelly Fourier Call",Top],Labeled[Framed[N[kellyfourier2]],"Kelly Fourier Put" ,Top]},{Labeled[Framed[N[callfourier/(callBS+.001)],FrameStyle-> Orange],temp10,Top],Labeled[Framed[N[putfourier/(putBS+.001)]],temp4,Top],Labeled[Framed[N[callputRATFour]],temp5,Top],Labeled[Framed[N[temp3],FrameStyle-> Magenta],temp6,Top]},{Labeled[Framed[OverallKellyMP,FrameStyle-> Red],"Most Probable OverallKelly for all 4 LEGS",Top],Labeled[Framed[OverallKellyFourier,FrameStyle-> Red],"Fourier OverallKelly for all 4 LEGS",Top]},{Labeled[Framed[OptionCounts[[1]]],"Number of options\n-ve means sell",Top],Labeled[Framed[OptionTypes[[1]]],"Type of option\nCall or Put",Top],Labeled[Framed[N[strikes[[1]]]],"Strike Price",Top],Labeled[Framed[Expiries[[1]]],"Expiry date,\n1st leg",Top]},
{Labeled[Framed[OptionCounts[[2]]],"Number of options\n-ve means sell",Top],Labeled[Framed[OptionTypes[[2]]],"Type of option\nCall or Put",Top],Labeled[Framed[N[strikes[[2]]]],"Strike Price",Top],Labeled[Framed[Expiries[[2]]],"Expiry date\n2nd leg",Top]},
{Labeled[Framed[OptionCounts[[3]]],"Number of options\n-ve means sell",Top],Labeled[Framed[OptionTypes[[3]]],"Type of option\nCall or Put",Top],Labeled[Framed[N[strikes[[3]]]],"Strike Price",Top],Labeled[Framed[Expiries[[3]]],"Expiry date\n3rd leg",Top]},
{Labeled[Framed[OptionCounts[[4]]],"Number of options\n-ve means sell",Top],Labeled[Framed[OptionTypes[[4]]],"Type of option\nCall or Put",Top],Labeled[Framed[N[strikes[[4]]]],"Strike Price",Top],Labeled[Framed[Expiries[[4]]],"Expiry date\n4th leg",Top]},
{Labeled[Framed[val1],"80% lower limit of Call", Top],Labeled[Framed[val8],"50% median limit of Call",Top],Labeled[Framed[val6],"60% upper limit of Call",Top],Labeled[Framed[val2],"80% upper limit of Call", Top]},{Labeled[Framed[val3],"80% lower limit of Put", Top],Labeled[Framed[val9],"50% median limit of Put",Top],Labeled[Framed[val7],"60% upper limit of Put",Top],Labeled[Framed[val4],"80% upper limit of Put", Top]},
{Labeled[Framed[callBS,FrameStyle-> Red],"Black-Scholes\ncall value",Top],Labeled[Framed[putBS],"BS put value",Top],Labeled[Framed[DeltaCall],"Call Delta",Top],Labeled[Framed[Gamma2],"Gamma call & put",Top]},{Labeled[Framed[Vega],"Vega call & put",Top],Labeled[Framed[ThetaCall],"Theta call",Top],Labeled[Framed[RhoCall],"Rho call",Top],Labeled[Framed[DeltaPut],"Delta put",Top]},{Labeled[Framed[ThetaPut],"Theta put",Top],Labeled[Framed[RhoPut],"Rho put",Top]}
}]}]]

,If [SeasonalFlag==0,Style["YEARLY ANALYSIS: Option Prices, Future Values, Mean Path for "<>ToString[stockTicker]<>" from "<>ToString[timestamp1]<>" to "<>ToString[ExpDate]<>ToString[temp12],Brown,14],
Style["SEASONAL ANALYSIS: Option Prices, Future Values, Mean Path for "<>ToString[stockTicker]<>" from "<>ToString[enddate]<>" to "<>ToString[ExpDate]<>ToString[temp12],Brown,14]], Top,Alignment->Center]];

Examples

(* All Rights Reserved - CopyRight 2012, Richard John Belshaw, AGU,AAAS,ASA,IEEE,ACS,ACM*)

Import["americandata241114.csv"]

CountryData["Properties"]

CountryData["Mexico","CurrencyCode"]

WolframAlpha["Crude Oil price"]

WolframAlpha["AAPL",{{"FundamentalsAndFinancials",1},"ComputableData"}]

FinancialData["HOLI"]

SetDirectory["C://Users//Chondrally//Documents"]

"/Users/Chondrally"

N[4*ArcTan[1]*(3*(7+23)-Sqrt[(7+3*23)*(23+7*3)])]

N[4*23*EllipticE[(23^2-7^2)/23^2]]

92/2

a= 5;b=4;

WolframAlpha["a=5,b=4, integrate 4*sqrt(1+(b/a^2*x)^2/(1-x^2/a^2)) dx from 0 to a"]
WolframAlphaQueryResults
$Failed
WolframAlphaQueryResults
WolframAlphaQueryResults
WolframAlphaQueryResults
WolframAlphaQueryResults
WolframAlphaQueryResults
WolframAlphaQueryResults
WolframAlphaQueryResults
WolframAlphaQueryResults

WolframAlpha["integrate 4*4*5sqrt(cos(2x))/cos(x)^3 dx from 0 to pi/4"]

WolframAlpha["integrate 4*5*4*sqrt(1-tan(x)^2)*sec(x)^2 dx from 0 to pi/4"]

WolframAlpha["a=5,b=4,h=N[(a-b)^2/(a+b)^2],N[pi*(a+b)*(1+3*h/(10+Sqrt[4-3*h]))]"]

WolframAlpha["Integrate 1/pi*((5-5^(1/5)*cos(theta))^2+5^(6/5)*sin(theta)^2)^(1/2) d(theta)for theta from 0 to pi"]

FinancialData["^Vix",All]

N[1/4000]*100

directry="C://Users//Chondrally//Documents"; (* Select a directory on your drive to store the neural net weights between runs once trained, only necessary if optionflag=1 or 0*)
stockTicker ="COHR" (*The stock Ticker label for a company AAPL=Apple, MSFT= Microsoft, go to Yahoo(YHOO) finance with Google(GOOG) search to find the ticker symbol*)
dataType = "Close" (* enter Close,High,Low,Open *)
YearsBack=1;(* the number of years of past data to include in the analysis*)
StartDate = 0; (* StartDate = 0 is one year ago to the day,  otherwise enter an integer number of business days in the past to start from.  Set YearsBack=1 and then pick StartDate=  252= 1 year ago,22 or 23= 1 month ago, 66 or 69 days for 3 months ago*)

inflation =.02; (* the inflation rate per year *)
interestRate =.02; (* the risk free interest rate *)
dividend =0.0; (* the dividend rate per year like 3% would be .03 *)
(* 4 Legs,  for an iron condor or a butterfly or a backspread or a horizontal spread or a diagonal spread or a debit or credit spread   *)
strikes=ConstantArray[0,4];
Expiries=ConstantArray["",4];
OptionCounts=ConstantArray[0,4];
OptionTypes=ConstantArray["",4];

(* if OptionCount tts,  the number of options to be purchased for that leg,  is equal to zero,  then no calculation will be done for that leg.  Different Expiries are permissible for horizontal spreads *)
strikes[[1]] =0;    (*0 is at the money*)
Expiries[[1]] = "Nov 17/2017";
OptionCounts[[1]] = 1;  (* can be negative for selling puts or calls*)
OptionTypes[[1]]="CALL" ;   (* option type  either "Call" or "Put" or "call" or "put"*)
(* 2nd leg of a spread or horizontal spread *)
strikes[[2]]=0;
Expiries[[2]]="";
OptionCounts[[2]]=0;
OptionTypes[[2]]="Put";
(* 3rd leg of a spread *)
strikes[[3]]=0;
Expiries[[3]]="";
OptionCounts[[3]]=0;
OptionTypes[[3]]="Call";
(*4th leg of an iron condor *)
strikes[[4]]=0;
Expiries[[4]]="";
OptionCounts[[4]]=0;
OptionTypes[[4]] = "Put";

Legs={strikes,Expiries,OptionCounts,OptionTypes };

optionflag =2; (* If optionflag=3, then a fourier extrapolation of the discrete wavelet transform is carried out,If optionflag=2=two,  then a (MUSIC)Multiple signal classification fourier analysis and forecast is carried out(the default, considered to be the most accurate and fastest, around 3 minutes and 10 seconds) instead of the neural nets (the whole thing with fourier runs in about 2 minutes and 20 seconds for a one year lookback and 3 month look ahead on a 3GHz 4 core computer-Intel 7(INTC)); 
if optionflag= 1 = train net weights and save them in directory file (this runs in about 20 minutes with a one year lookback and a 3 month look ahead),  0= read weights from directory file and calculate net results  much quicker but you must run optionflag=1 first for a given Ticker, if optionflag=-1 = do not use neural nets or fourier extrapolation at all: Only Bayesian Markov Monte Carlo and Wavelet Analysis are carried out ,   quite a bit quicker,  but no neural net or fourier results showed and no predicted indicators *)
debugflag =0; (* if you want to see the progress of the evaluation,  set debugflag =1    *)
(* After you have entered your data above,  just press SHIFT-ENTER together to evaluate this cell and run the program to get results , Occasionally
a 1/0 infinity will be encountered in EvaluateNet or NeuralNet1 subroutine..... this will not affect the final results; To insert a page break between output panes,  move the mouse to the line you want the page break,  let the cursor become a horizontal line, and then right click and select 'insert page break'*)
(*Very important output indicators are the probability density function (pdf) and price delta 3,9,18 and volume delta 3,9,18 day Exponential moving averages (EMAs). Also Market accumulation and  percentage WIN chance per day and All confidence level win percentage per day as well as the percentage chance win per confidence level. Also the probability of ups (which should be >.5 for upward trending stocks and <.5 for downward trending stocks,  the mean up, the mean down and the mean of the probability density function which should be greater than 1 for upward trending stocks and less than 1 for downward trending stocks. Relative Timing Percent Price is also important. The bollinger bandwidth is important to get cheap options when the bandwidth is relatively small*)
catastropheflag =0; (* when this is set to one=1,  a complex multi-hour (1.2 hours for 5 year look back and 3 month look ahead) computation is involved that calculates the probability per day of a level crossing from the monte carlo simulation.  ie. the levels 1.1,1.2,1.3,.1.4,1.5,1.6 and .9,.8,.7,.6 , .5,.4 are levels of ratio of price from day 2 to day 1 are calculated and accumulated in separate distributions so that we can find out if there is any likelihood of a "Close" price being up or down by that much on any given day from the previous day and what the probabilty of the event is by random chance and the patterns in the market distributions and the fat tailed distribution is used.  Typically catastropheflag is only employed for indexes or ETFs like "SP500" or Oil or Gold indexes or currencies.catastropheflag=0 for normal stock analysis*)
paths =4000;  (* 1000 is 0.1% error and 4000 is 0.025% error and 10000 is .01% error.  number of paths into future to calculate for indicatorpaths and for main prediction *)
googleflag=1; (* if googleflag =1 the data is from google.  if googleflag=0, the data is from Yahoo *)
nodeslayer = {37,23,13,5}; (* number of nodes per layer of neural network...  37 is number of days in first layer.  5 is number of cyclical trends in final layer *)
optionPrices[directry,stockTicker,"",dataType,YearsBack,StartDate,Legs,inflation,interestRate,dividend,1.0,paths,paths,1,catastropheflag,1,0,0,20,nodeslayer,optionflag,googleflag,debugflag]
(* Don't forget to read the stock news at YAHOO(YHOO) financial or Google Finance (GOOGL) or Bloomberg or Thomson Reuters to get the latest positive or negative take on a stock and assess if a whale or a venture capitalist is investing in a stock because of a new product which can change the outlook at earnings time*)