Home

Introduction

Literature

Installation

Documentation

Tutorial

Statistical Finance

We provide functions for portfolio selection and option pricing and hedging. The tools are based on nonparametric regression methods, including kernel and nearest neighborhood regression. In addition, functions are provided for downloading and processing financial data.

We provide an R package "finatool". R is a language and environment for statistical computing and graphics. It may be downloaded from R archive network .

The package "finatool" is designed by Jussi Klemelä. I am grateful for bug reports.


Contents

  1. Introduction
  2. Literature
  3. Installation
  4. Documentation
  5. Tutorial

Introduction:


Literature:


Installation instructions:

  • Download the file ft.R (updated 2009/02) and then issue the command

    > source("/path/ft.R")

    in the R console. (Note that one has to specify the full name of the file and use the for example in unix the command,

    > source("/home/aaa/Desktop/ft.R")

    where "aaa" is the user account, in OS X

    > source("/Users/aaa/Desktop/ft.R")

    and in Windows XP

    > source("C:\\Documents and Settings\\user\\Desktop\\ft.R")

  • Alternatively, download package finatool_0.0.1.tar.gz (not currently updated).

    • Windows binaries are not yet available at http://www.r-project.org/ (-> CRAN -> Choose mirror -> Packages)

    • Installation instructions are provided by issuing command R CMD INSTALL --help or command R INSTALL --help. Installation may be done (in unix) with the command:

      R CMD INSTALL finatool_0.0.1.tar.gz

      This will install (in unix) the package to directory "/R_HOME/R/library/", where "R_HOME" is the location of R tree. That is, directory "/R_HOME/library/finatool" will be created and files will be installed to that directory. For example, R_HOME may be /usr/lib/R.

    • In R, issue the command

      library(finatool)

      which makes the functions available.


Documentation:

Here is a listing of the functions, which the package provides.

Functions for downloading and reading data:

  • read.yahoo: reads data from Yahoo web-site
  • read.stlouis: reads data from a St.Louis-file
  • SP500: tickers for the companies in the SP500 stock index
  • DAX: tickers for the companies in the DAX30 stock index

Functions for preprocessing:

  • data.manip: extracts the closing prices and the date; removes the days where there is at least one missing observation; arranges the observations so that the latest observation is the last element of the data matrix; (returns a list with elements "data" and "time")
  • returns: calculates retruns, logarithmic returns, or differences from a price matrix
  • copula.trans: makes a copula transformation for a data matrix
  • tekni1d: calculates technical indicators from a 1D price vector

Functions for exploratory data analysis:

  • scan1d: makes a series of one dimensional visualizations froma a data matrix
  • subset.movies: makes a movie of observations included in the estimates of the level sets

Portfolio selection:

  • make.portdat: makes data which is used to select a portfolio of stocks
  • option.data: makes data which is used to select a portfolio of options
  • pf.nn: calculates an estimate for the optimal portfolio using nearest neighbor regression
  • pf.nn.redu: calculates an estimate for the optimal portfolio using nearest neigborhood regression, restricting the weights to full investment in individual assets, and allowing shorting
  • pf.kernel: calculates an estimate for the optimal portfolio using kernel regression
  • pf.kernel.redu: calculates an estimate for the optimal portfolio using kernel regression, restricting the weights to full investment in individual assets, and allowing shorting
  • pf.greedy.redu: calculates an estimate for the optimal portfolio using a greedy regressogram, restricting the weights to full investment in individual assets, and allowing shorting

Diagnostics of portfolio selection:

  • pf.seq: calculates the sequence of portfolios and the wealth process given a vector time series of price relatives, using either kernel regression or nearest neighbor regression
  • pf.seq.seq: calculates the sequences of portfolios and the wealth processes given a vector time series of price relatives and a sequence of smoothing parameters, for various lengths of previous observations, using either kernel regression or nearest neighbor regression
  • pf.scan: plots the output of function "pf.seq.seq"
  • plot.condi: plots an estimate of the conditional distribution of the log-return, for various portfolio weights, using the kernel method
  • plot.condi.seq: plots a sequence of estimates of conditional distributions of the log-returns, given a vector time series of price relatives
  • pf.historical: visualizes the kernel- or nn-neigborhoods for historical data
  • pf.scale: visualizes how sensitive the portfolio weights are for the smoothing parameter
  • b.scale: shows the portfolio weights for different smoothing parameters at a single time point
  • wealth: calculates the wealth process of a constantly rebalanced portfolio
  • plot.compa: plots a comparison of two wealth processes
  • predic.seq: makes a sequence of predictions of asset returns

Functions for option hedging and pricing:

  • hedging: calculates an optimal delta for an European call option, using numerical optimization
  • hedging.data: calculates data which is used for caluculating the hedging parameter
  • mc.hedge: calculates the price and the delta which are optimal in the minimum variance sense for a single period hedging of an European call or put option, using Monte Carlo integration
  • bs: calculates the Black-Scholes price for an European call or put option
  • bs.delta: calculates the delta of Black-Scholes hedging for an European call or put option
  • bs.implied: calculates the Black-Scholes implied volatility given the current price of an European call or put option

Regression function estimation:

  • pcf.kernesti: calculates a kernel regression estimator (Nadaraya-Watson estimator)
  • single.index: calculates an estimate of the index in the single index model
  • linear: calculates the estimates of the coefficients of linear regression
  • greedy: calculates a pointwise estimate of a regression function using greedy regressograms
  • bagg: calculates a pointwise estimate of a regression function using bootstrap aggregated greedy regressograms or linear regression
  • additive: calculates a pointwise estimate of a regression function using backfitting in the additive model
  • make.regdat: transforms a vector time series of price relatives to a regression data, making an optional copula transformation

Miscallenous:

  • emp.distribu: calculates the value of an empirical distribution function
  • emp.quantile: calculates the value of an empirical function
  • sim.ts: simulates a trajectory of stock prices
  • ml: calculates a maximum likelihood estimator for the parameters of a density

In R use the command help(func) to get online manual for "func".


Tutorial

# First load the library 

library(finatool)

Downloading data from Yahoo's website

# define the vector of tickers

ticker<-c("^GDAXI","^FTSE","^FCHI") 

# read from the Yahoo web site

destfile<-"~/pois"         # define a name for a trash file
ry<-read.yahoo(ticker, destfile=destfile)

See here Yahoo tickers.

Summary

ticker<-c("^GDAXI","^FTSE","^FCHI") 
destfile<-"~/pois"       
# destfile<-"C:\\Documents and Settings\\user\\Desktop\\pois"
ry<-read.yahoo(ticker, source="web", destfile=destfile)

Reading data from a St. Louis-file

# define the ticker

ticker<-c("DGS1","DGS10","DGS30")   

# give the directory, where the file is located

direc<-"/Karhu/Tulo/Data/Fina/IR_txt_2/data/"

# read data

skip<-c(15,15,18)   # give the amount of lines skipped at the beginning of files
rs<-read.stlouis(ticker, direc, skip=skip)

See here St.Louis tickers.

Summary: Rates

ticker<-c("DGS1","DGS10","DGS30")   
direc<-"~/Karhu/Tulo/Data/Fina/IR_txt_2/data/"
skip<-c(15,15,18) 
rs<-read.stlouis(ticker, direc, skip=skip)

Summary: Currencies

ticker<-c("DEXSZUS","DEXMXUS","DEXINUS")         
direc<-"~/Tulo/Data/Fina/FX_txt_2/data/"
skip<-c(15,15,18)
rs<-read.stlouis(ticker, direc, skip=skip)

Data manipulation

Read the data, either from Yahoo
ticker<-c("^GDAXI","^FTSE") 
destfile<-"~/pois"       
rr<-read.yahoo(ticker, source="web", destfile=destfile)
or from St. Louis
ticker<-c("DGS10","DGS30")   
direc<-"~/ada/Tulo/Data/Fina/IR_txt_2/data/"
skip<-c(15,18)  # give the amount of lines skipped at the beginning of files
rr<-read.stlouis(ticker, direc, skip=skip)
or from both simultaneously

and then we move on to preprocess the data

# first the data is transformed to a price matrix and time vector, 
# missing values are deleted

dm<-data.manip(rr,ticker) 

# we can make a data frame 

df<-data.frame(dm$data,row.names=dm$time)
names(df)<-ticker

plot(df[,1],type="l")

# we make the data matrix either to a matrix of 
# prices, returns, logarithmic returns, or increments, labeled as
# "price", "return", "loga", "incre"

method<-c("return","return") #c("incre","incre") #c("return","incre") 
R<-returns(df,method=method)
plot(R)

# the marginals can be normalized to have approximately
# the standard Gaussian or the uniform distribution,
# choose either "gauss" or "uniform"

marginal<-c("gauss","gauss")
RR<-copula.trans(R,marginal=marginal)
plot(RR)

# we can analyze the data with rggobi

library(rggobi)
g<-ggobi(df)

Summary: Stocks

# stock indeces

ticker<-c("^GDAXI","^FTSE") 
destfile<-"~/pois"       
rr<-read.yahoo(ticker, source="web", destfile=destfile)
dm<-data.manip(rr,ticker) 
df<-data.frame(dm$data,row.names=dm$time)
names(df)<-ticker
method<-c("return","return")
R<-returns(df,method=method)
marginal<-c("gauss","gauss")
RR<-copula.trans(R,marginal=marginal)

# stocks

ticker<-c("NOK","AAPL") 
destfile<-"~/pois"       
rr<-read.yahoo(ticker, source="web", destfile=destfile)
dm<-data.manip(rr,ticker,what="AdjClose") 
plot(dm$data[,1],type="l")
plot(dm$data[,2],type="l")

dm<-data.manip(rr,ticker,what="Volume") 
plot(dm$data[,1],type="l")
plot(dm$data[,2],type="l")

Summary: Rates

ticker<-c("DGS1","DGS10","DGS30")   
direc<-"~/ada/Tulo/Data/Fina/IR_txt_2/data/"
skip<-c(15,15,18) 
rs<-read.stlouis(ticker, direc, skip=skip)
dm<-data.manip(rs,ticker) 
df<-data.frame(dm$data,row.names=dm$time)
names(df)<-ticker
method<-c("incre","incre","incre")
R<-returns(df,method=method)
marginal<-c("gauss","gauss","gauss")
RR<-copula.trans(R,marginal=marginal)

Summary: Currencies

ticker<-c("DEXSZUS","DEXMXUS","DEXINUS")         
direc<-"~/ada/Tulo/Data/Fina/FX_txt_2/data/"
skip<-c(15,15,18)
rs<-read.stlouis(ticker, direc, skip=skip)
dm<-data.manip(rs,ticker)
df<-data.frame(dm$data,row.names=dm$time)
names(df)<-ticker
method<-c("return","return","return")
R<-returns(df,method=method)
marginal<-c("gauss","gauss","gauss")
RR<-copula.trans(R,marginal=marginal)

Visualizing 1D marginals

ticker<-c("^GDAXI","^FTSE","^FCHI") 
destfile<-"~/pois"      
ry<-read.yahoo(ticker, source="web", destfile=destfile)
dm<-data.manip(ry,ticker) 

df<-data.frame(dm$data,row.names=dm$time)
names(df)<-ticker

method<-c("return","return","return")
R<-returns(df,method=method)
df<-data.frame(R)
names(df)<-ticker

type<-"ts"                # time series plot
scan1d(df,type=type)

type<-"index"             # index plot
scan1d(df,type=type)

Univariate distributions

ticker<-c("^GDAXI") 
destfile<-"~/pois"      
ry<-read.yahoo(ticker, source="web", destfile=destfile)
dm<-data.manip(ry,ticker) 
#method<-"price"
#df<-data.final(dm,ticker,method=method)
#S<-df[,1]
S<-dm$data
plot(S)

S<-matrix(S,length(S),1)

method<-"incre"
R<-returns(S,method)
plot(R,type="l")

method<-"loga"
R<-returns(S,method)
plot(R,type="l")

method<-"relative"
R<-returns(S,method)
plot(R,type="l")

method<-"return"
R<-returns(S,method)
plot(R,type="l")

mean(R)
sd(R)

binlkm<-20
histo1d(R,binlkm)

h<-0.01
N<-50
pcf<-pcf.kerndens(R,h=h,N=N)
dp<-draw.pcf(pcf)
plot(dp$x,dp$y,type="l")

dist.func(R)

Movie of subsetting

ticker<-c("^GDAXI","^FCHI") 
destfile<-"/home/jsk/Desktop/pois"      
ry<-read.yahoo(ticker, source="web", destfile=destfile)
dm<-data.manip(ry,ticker) 
method<-"return"
marginal<-"gauss"
dendat<-data.final(dm,ticker,method=method,marginal=marginal)

filepath<-"/home/jsk/public_html/statfina-html/depe-matrix/movies/DaxCac/"
maxk<-20
radmat<-nn.radit(dendat,maxk)

k<-15
ngrid<-150
grid.low<-0
grid.up<-0.3

subset.movie(dendat, ticker, filepath, radmat, 
k=k, ngrid=ngrid, grid.low=grid.low, grid.up=grid.up)

convert -delay 30 /home/jsk/public_html/statfina-html/depe-matrix/movies/DaxCac/fig*.jpg /home/jsk/public_html/statfina-html/depe-matrix/movies/DaxCac.gif 

Linear regression

# we obtain returns of the DAX stock index

ticker<-c("^GDAXI") 
destfile<-"~/pois"       
ry<-read.yahoo(ticker, source="web", destfile=destfile)
#save(file="/home/jsk/Arti/statfina/Dax.var",list=c("ry"))
#load(file="/Users/jsk/Karhu/Arti/statfina/DaxMdax.var")
dm<-data.manip(ry,ticker) 
method<-"return"
S<-returns(dm$data,method=method)
n<-length(S)
plot(S,type="l")

# we calculate volatilities for the 5 day periods 

perlen<-5
pernum<-floor(n/perlen)
volas<-matrix(0,pernum,1)
for (i in 1:pernum){
    beg<-(i-1)*perlen+1
    end<-(i-1)*perlen+perlen
    period<-S[beg:end]
    volas[i]<-sqrt(sum(period^2)/perlen)*sqrt(252)
}
plot(volas,type="l")

1D predictor

# we try to pedict the volatility of a 5 day period with the
# help of the volatility of the previous 5 day period

dendat<-matrix(0,pernum-1,2)
for (i in 1:(pernum-1)){
    dendat[i,1]<-volas[i]
    dendat[i,2]<-volas[i+1]
}
plot(dendat)

x<-matrix(dendat[,1],length(dendat[,1]),1)
y<-dendat[,2]
par<-linear(x,y)

t<-seq(0,1,0.05)
u<-par$beta0+par$beta1*t
matplot(x,y)
matplot(t,u,add=TRUE,type="l")

t<-seq(0,1,0.05)
u<-as.real(cor(x,y))*t
matplot(x,y)
matplot(t,u,add=TRUE,type="l")

# we make a logarithmic transform for the x-variable

x<-matrix(log(dendat[,1]),length(dendat[,1]),1)
y<-matrix(dendat[,2],length(dendat[,2]),1)
plot(x,y)

par<-linear(x,y)

t<-seq(-3.5,0.1,0.05)
u<-par$beta0+par$beta1*t
matplot(x,y)
matplot(t,u,add=TRUE,type="l")


2D predictor

# we use now the volatilities of two periods to predict 
# the volatility of the next period

dendat<-matrix(0,pernum-2,3)
for (i in 1:(pernum-2)){
    dendat[i,1]<-volas[i]
    dendat[i,2]<-volas[i+1]
    dendat[i,3]<-volas[i+2]
}
plot(dendat[,1],dendat[,2])

library(scatterplot3d)
scatterplot3d(dendat)

x<-dendat[,1:2]
y<-dendat[,3]
par<-linear(x,y)

Kernel regression

# we obtain returns of the DAX stock index

ticker<-c("^GDAXI") 
destfile<-"~/pois"       
ry<-read.yahoo(ticker, source="web", destfile=destfile)
#save(file="/home/jsk/Arti/statfina/Dax.var",list=c("ry"))
#load(file="/Users/jsk/Karhu/Arti/statfina/DaxMdax.var")
dm<-data.manip(ry,ticker) 
method<-"return"
S<-returns(dm$data,method=method)
n<-length(S)
plot(S,type="l")

# we calculate volatilities for the 5 day periods 

perlen<-5
pernum<-floor(n/perlen)
volas<-matrix(0,pernum,1)
for (i in 1:pernum){
    beg<-(i-1)*perlen+1
    end<-(i-1)*perlen+perlen
    period<-S[beg:end]
    volas[i]<-sqrt(sum(period^2)/perlen)*sqrt(252)
}
plot(volas,type="l")

1D kernel estimation

# we try to pedict the volatility of a 5 day period with the
# help of the volatility of the previous 5 day period

dendat<-matrix(0,pernum-1,2)
for (i in 1:(pernum-1)){
    dendat[i,1]<-volas[i]
    dendat[i,2]<-volas[i+1]
}
plot(dendat)

# we estimate the regression function

x<-dendat[,1]
y<-dendat[,2]
h<-0.05
N<-60
pcf<-pcf.kernesti(x,y,h,N)
dp<-draw.pcf(pcf)          # requires package "denpro"
matplot(dp$x,dp$y,type="l",xlim=c(0,1.1),ylim=c(0,1.1))
matplot(x,y,add=TRUE)

# we make a logarithmic transform for the x-variable

x<-log(dendat[,1])
y<-dendat[,2]
plot(x,y)

h<-0.2
N<-80
pcf<-pcf.kernesti(x,y,h,N)
dp<-draw.pcf(pcf)
matplot(dp$x,dp$y,type="l",xlim=c(-3.5,0.2),ylim=c(0,1.2))
matplot(x,y,add=TRUE)

# we make a logarithmic transform for both variables

x<-log(dendat[,1])
y<-log(dendat[,2])
plot(x,y)

h<-0.4
N<-80
pcf<-pcf.kernesti(x,y,h,N)
dp<-draw.pcf(pcf)
matplot(dp$x,dp$y,type="l",xlim=c(-3.5,0.2),ylim=c(-3.5,0.2))
matplot(x,y,add=TRUE)

# we make a copula transform and then estimate the regression function

marginal<-c("gauss","original")
regdat<-copula.trans(dendat,marginal=marginal)
plot(regdat)

x<-regdat[,1]
y<-regdat[,2]
h<-0.2
N<-80
pcf<-pcf.kernesti(x,y,h,N)
dp<-draw.pcf(pcf)
matplot(dp$x,dp$y,type="l",xlim=c(-3,3),ylim=c(0,1.2))
matplot(x,y,add=TRUE)

# we look at the conditional densities using kernel estimates

hd<-0.04
N<-100
pcf<-pcf.kerndens(matrix(y,length(y),1),hd,N,kernel="gauss")
dp<-draw.pcf(pcf)
plot(dp$x,dp$y,type="l",xlab="y",ylab="")

arg<--2
kw<-kernesti.weights(arg,x,h)

pcf2<-pcf.kerndens(matrix(y,length(y),1),hd,N,kernel="gauss",weights=kw)
dp2<-draw.pcf(pcf2)
plot(dp2$x,dp2$y,type="l")

minx<-0
maxx<-1.2
miny<-0
maxy<-10
plot(x="",y="",xlim=c(minx,maxx),ylim=c(miny,maxy),xlab="",ylab="")
matplot(dp$x,dp$y,type="l",add=TRUE)
matplot(dp2$x,dp2$y,type="l",add=TRUE,col="blue")

# we look at the conditional densities using histograms

binlkm<-20
histo1d(y,binlkm,graphplot=TRUE,normalization=FALSE)

arg<-0.1
kw<-kernesti.weights(arg,x,h)

x11()
histo1d(y,binlkm,graphplot=TRUE,normalization=FALSE,weights=length(y)*kw)

x11()
brushcol<-"blue"
histo1d(y,binlkm,subweights=kw,
height=360,
normalization=FALSE,
brushcol=brushcol,graphplot=TRUE)

2D kernel estimation

# we use now the volatilities of two periods to predict 
# the volatility of the next period

dendat<-matrix(0,pernum-2,3)
for (i in 1:(pernum-2)){
    dendat[i,1]<-volas[i]
    dendat[i,2]<-volas[i+1]
    dendat[i,3]<-volas[i+2]
}
plot(dendat[,1],dendat[,2])

library(scatterplot3d)
scatterplot3d(dendat)

# we make the logarithmic transform for the explanatory variables
# and estimate the regression function

x<-matrix(0,dim(dendat)[1],2)
x[,1]<-log(dendat[,1])
x[,2]<-log(dendat[,2])
plot(x)
y<-dendat[,3]
scatterplot3d(x[,1],x[,2],y)

h<-0.7
N<-c(40,40)
pcf<-pcf.kernesti(x,y,h,N)

dp<-draw.pcf(pcf,pnum=N)    # need package "denpro"

contour(dp$x,dp$y,dp$z,drawlabels=FALSE)

persp(dp$x,dp$y,dp$z,phi=30,theta=30)

# we make the copula transform for the explanatory variables
# and estimate the regression function

x<-copula.trans(dendat[,1:2])
plot(x)
y<-dendat[,3]

h<-1.4
N<-c(40,40)
pcf<-pcf.kernesti(x,y,h,N)

dp<-draw.pcf(pcf,pnum=N)

persp(dp$x,dp$y,dp$z,phi=30,theta=30)

contour(dp$x,dp$y,dp$z,drawlabels=FALSE)

# we make a data sphering for the explanatory variables
# and then estimate the regression function

xx<-dendat[,1:2]
cova<-cov(xx)
eig<-eigen(cova,symmetric=TRUE)
sigsqm<-eig$vectors%*%diag(eig$values^{-1/2}) 
x<-t(t(sigsqm)%*%t(xx-mean(xx)))  
plot(x)
y<-dendat[,3]

h<-1.9
N<-c(40,40)
pcf<-pcf.kernesti(x,y,h,N)

dp<-draw.pcf(pcf,pnum=N)

persp(dp$x,dp$y,dp$z,phi=30,theta=30)

contour(dp$x,dp$y,dp$z,drawlabels=FALSE)

# we make first the copula transform for the explanatory variables
# and then the data sphering, and then we estimate the regression function

x<-copula.trans(dendat[,1:2])
plot(x)
type<-"sphering"
x<-preprocess(x,type=type)
plot(x)
y<-dendat[,3]

h<-1.4
N<-c(40,40)
pcf<-pcf.kernesti(x,y,h,N)

dp<-draw.pcf(pcf,pnum=N)

persp(dp$x,dp$y,dp$z,phi=30,theta=30)

contour(dp$x,dp$y,dp$z,drawlabels=FALSE)

Linear regression by bootstrap aggregation

# we obtain returns of the DAX stock index

ticker<-c("^GDAXI") 
destfile<-"~/pois"       
ry<-read.yahoo(ticker, source="web", destfile=destfile)
#save(file="/home/jsk/Arti/statfina/Dax.var",list=c("ry"))
#load(file="/Users/jsk/Karhu/Arti/statfina/DaxMdax.var")
dm<-data.manip(ry,ticker) 
method<-"return"
S<-returns(dm$data,method=method)
n<-length(S)
plot(S,type="l")

# we calculate volatilities for the 5 day periods 

perlen<-5
pernum<-floor(n/perlen)
volas<-matrix(0,pernum,1)
for (i in 1:pernum){
    beg<-(i-1)*perlen+1
    end<-(i-1)*perlen+perlen
    period<-S[beg:end]
    volas[i]<-sqrt(sum(period^2)/perlen)*sqrt(252)
}
plot(volas,type="l")

1D case

# we try to pedict the volatility of a 5 day period with the
# help of the volatility of the previous 5 day period

dendat<-matrix(0,pernum-1,2)
for (i in 1:(pernum-1)){
    dendat[i,1]<-volas[i]
    dendat[i,2]<-volas[i+1]
}
plot(dendat)

# we estimate the regression function

x<-matrix(dendat[,1],length(dendat[,1]),1)
y<-matrix(dendat[,2],length(dendat[,2]),1)

B<-2
seed<-1
estimator<-"linear"
t<-seq(0,1,0.05)
u<-matrix(0,length(t),1)
for (i in 1:length(t)) u[i]<-bagg(x,y,t[i],B=B,seed=seed,estimator=estimator)
matplot(x,y)
matplot(t,u,type="l",add=TRUE,col="red") #xlim=c(0,1.1),ylim=c(0,1.1))

# we make a logarithmic transform for the x-variable

x<-matrix(log(dendat[,1]),length(dendat[,1]),1)
y<-matrix(dendat[,2],length(dendat[,2]),1)
plot(x,y)

B<-10
propor<-0.5
seed<-10
estimator<-"linear"
t<-seq(-3.5,0.1,0.05)
u<-matrix(0,length(t),1)
for (i in 1:length(t)) 
  u[i]<-bagg(x,y,t[i],B=B,seed=seed,propor=propor,estimator=estimator)
matplot(x,y)
matplot(t,u,type="l",add=TRUE,col="red") #xlim=c(-3.5,0.1),ylim=c(0,1.1))


Greedy regressogram

Note: Function "greedy" uses c-code but function "greedyR" uses only R.

# we obtain returns of the DAX stock index

ticker<-c("^GDAXI") 
destfile<-"~/pois"       
ry<-read.yahoo(ticker, source="web", destfile=destfile)
dm<-data.manip(ry,ticker) 
method<-"return"
S<-returns(dm$data,method=method)
n<-length(S)
plot(S,type="l")

# we calculate volatilities for the 5 day periods 

perlen<-5
pernum<-floor(n/perlen)
volas<-matrix(0,pernum,1)
for (i in 1:pernum){
    beg<-(i-1)*perlen+1
    end<-(i-1)*perlen+perlen
    period<-S[beg:end]
    volas[i]<-sqrt(sum(period^2)/perlen)*sqrt(252)
}
plot(volas,type="l")

1D case

# we try to pedict the volatility of a 5 day period with the
# help of the volatility of the previous 5 day period

dendat<-matrix(0,pernum-1,2)
for (i in 1:(pernum-1)){
    dendat[i,1]<-volas[i]
    dendat[i,2]<-volas[i+1]
}
plot(dendat)

# we estimate the regression function

x<-matrix(dendat[,1],length(dendat[,1]),1)
y<-matrix(dendat[,2],length(dendat[,2]),1)
plot(x,y)

M<-20
m<-10
splitfreq<-1
t<-seq(0,1,0.05)
u<-matrix(0,length(t),1)
for (i in 1:length(t)) u[i]<-greedy(x,y,t[i],M,m,splitfreq)$val
matplot(x,y) #,add=TRUE)
matplot(t,u,type="l",add=TRUE,col="red")#xlim=c(0,1.1),ylim=c(0,1.1))

M<-10
m<-4
arg<-0.6
gr<-greedy(x,y,arg,M,m)
matplot(x,y)
matplot(gr$x,gr$y,add=TRUE,col="red")

# we make a logarithmic transform for the x-variable

x<-matrix(log(dendat[,1]),length(dendat[,1]),1)
y<-matrix(dendat[,2],length(dendat[,2]),1)
plot(x,y)

M<-5
m<-10
splitfreq<-1
t<-seq(-3.5,0.1,0.05)
u<-matrix(0,length(t),1)
for (i in 1:length(t)) u[i]<-greedy(x,y,t[i],M,m,splitfreq=splitfreq)$val
matplot(x,y) #,add=TRUE)
matplot(t,u,type="l",add=TRUE,col="red")#xlim=c(-3.5,0.1),ylim=c(0,1.1))

# bootstrap aggregation

x<-matrix(log(dendat[,1]),length(dendat[,1]),1)
y<-matrix(dendat[,2],length(dendat[,2]),1)
plot(x,y)

M<-5
m<-5
splitfreq<-1
B<-20
propor<-0.5
seed<-10
estimator<-"greedy"
t<-seq(min(x),max(x),0.1)  #seq(-3.5,0.1,0.1)
u<-matrix(0,length(t),1)
for (i in 1:length(t)) 
   u[i]<-bagg(x,y,t[i],B=B,seed=seed,propor=propor,estimator=estimator,
              M=M,m=m,splitfreq=splitfreq)
matplot(x,y)
matplot(t,u,type="l",add=TRUE,col="red") #xlim=c(-3.5,0.1),ylim=c(0,1.1))


2D case

# we use now the volatilities of two periods to predict 
# the volatility of the next period

dendat<-matrix(0,pernum-2,3)
for (i in 1:(pernum-2)){
    dendat[i,1]<-volas[i]
    dendat[i,2]<-volas[i+1]
    dendat[i,3]<-volas[i+2]
}
plot(dendat[,1],dendat[,2])

library(scatterplot3d)
scatterplot3d(dendat)

# we make the logarithmic transform for the explanatory variables
# and estimate the regression function

x<-matrix(0,dim(dendat)[1],2)
x[,1]<-log(dendat[,1])
x[,2]<-log(dendat[,2])
plot(x)
y<-dendat[,3]
scatterplot3d(x[,1],x[,2],y)

M<-3
m<-10
t<-seq(-3.5,0.1,0.1)
u<-t
z<-matrix(0,length(t),length(u))
for (i in 1:length(t)) 
   for (j in 1:length(u))
      z[i,j]<-greedy(x,y,c(t[i],u[j]),M,m)$val

persp(t,u,z,phi=30,theta=30)

contour(t,u,z) #,drawlabels=FALSE)

Single index regression

# we use package "Rdonlp2" for the optimization

library(Rdonlp2)

# we obtain returns of the DAX stock index

ticker<-c("^GDAXI") 
destfile<-"~/pois"       
# destfile<-"C:\\Documents and Settings\\user\\Desktop\\pois"
ry<-read.yahoo(ticker, source="web", destfile=destfile)
#save(file="/home/jsk/Arti/statfina/Dax.var",list=c("ry"))
#load(file="/Users/jsk/Karhu/Arti/statfina/DaxMdax.var")
dm<-data.manip(ry,ticker) 
method<-"return"
df<-data.final(dm,ticker,method=method) 
n<-dim(df)[1]
S<-matrix(df[1:n,1],n,1)
plot(S,type="l")

# we calculate volatilities for the 5 day periods 

perlen<-5
pernum<-floor(n/perlen)
volas<-matrix(0,pernum,1)
for (i in 1:pernum){
    beg<-(i-1)*perlen+1
    end<-(i-1)*perlen+perlen
    period<-S[beg:end]
    volas[i]<-sqrt(sum(period^2)/perlen)*sqrt(252)
}
plot(volas,type="l")

# we use now the volatilities of d periods to predict 
# the volatility of the next period

d<-2
dendat<-matrix(0,pernum-d,d+1)
for (i in 1:(pernum-d))
    for (j in 1:(d+1))
      dendat[i,j]<-volas[i+j-1]

# we make the copula transform for the explanatory variables
# and estimate the regression function

x<-copula.trans(dendat[,1:d])
plot(x)
y<-dendat[,d+1]

# we calculate the best index

h<-0.6
thetahat<-single.index(x,y,h=h,kernel="gauss")

# the final estimate is a kernel estimate

z<-x%*%thetahat
h<-0.4
N<-60
pcf<-pcf.kernesti(z,y,h,N)
dp<-draw.pcf(pcf)          # requires package "denpro"
matplot(dp$x,dp$y,type="l",xlim=c(-3,3),ylim=c(0,1.1))
matplot(z,y,add=TRUE)

# simulation study

n<-200
d<-2
#sig<-matrix(c(1,0.1,0.1,1),d,d)
#eig<-eigen(sig)
#A<-eig$vectors%*%diag(sqrt(eig$values))
#sig
#A%*%t(A)

set.seed(1)
x<-matrix(rnorm(d*n),n,d)
plot(x)

theta<-c(0.2,0.8)
z<-x%*%theta
epsilon<-0.2
y<-sin(z)+epsilon*rnorm(n)
plot(z,y)

h<-0.2
thetahat<-single.index(x,y,h=h,kernel="gauss")
thetahat

Additive model

# we obtain returns of the DAX stock index

ticker<-c("^GDAXI") 
destfile<-"~/pois"       
ry<-read.yahoo(ticker, source="web", destfile=destfile)
dm<-data.manip(ry,ticker) 
method<-"return"
S<-returns(dm$data,method=method)
n<-length(S)
plot(S,type="l")

# we calculate volatilities for the 5 day periods 

perlen<-5
pernum<-floor(n/perlen)
volas<-matrix(0,pernum,1)
for (i in 1:pernum){
    beg<-(i-1)*perlen+1
    end<-(i-1)*perlen+perlen
    period<-S[beg:end]
    volas[i]<-sqrt(sum(period^2)/perlen)*sqrt(252)
}
plot(volas,type="l")

# we use now the volatilities of two periods to predict 
# the volatility of the next period

dendat<-matrix(0,pernum-2,3)
for (i in 1:(pernum-2)){
    dendat[i,1]<-volas[i]
    dendat[i,2]<-volas[i+1]
    dendat[i,3]<-volas[i+2]
}
plot(dendat[,1],dendat[,2])

library(scatterplot3d)
scatterplot3d(dendat)

# we make the logarithmic transform for the explanatory variables
# and estimate the regression function

x<-matrix(0,dim(dendat)[1],2)
x[,1]<-log(dendat[,1])
x[,2]<-log(dendat[,2])
plot(x)
y<-dendat[,3]

scatterplot3d(x[,1],x[,2],y)

h<-0.3
kernel<-"gauss"
M<-2
arg<-c(-1,-1)
additive(x,y,arg,h=h,kernel=kernel,M=M)

t<-seq(-3.5,0.1,0.1)
add<-matrix(0,length(t),2)
for (i in 1:length(t)) add[i,]<-additive(x,y,c(t[i],t[i]),h=h,kernel=kernel,M=M)

z<-matrix(0,length(t),length(t))
for (i in 1:length(t)) 
   for (j in 1:length(t))
      z[i,j]<-sum(add[i,1]+add[j,2])

persp(t,t,z,phi=30,theta=30)

contour(t,t,z) #,drawlabels=FALSE)

plot(t,add[,1],type="l")

plot(t,add[,2],type="l")

Prediction of covariance

ticker<-c("^GDAXI","^MDAXI")  
destfile<-"~/pois"    
ry<-read.yahoo(ticker, source="web", destfile=destfile)
dm<-data.manip(ry,ticker) 
method<-rep("relative",length(ticker))
U<-returns(dm$data,method=method)

perlen<-5
n<-dim(U)[1]
pernum<-floor(n/perlen)
corrs<-matrix(0,pernum,1)
for (i in 1:pernum){
    beg<-(i-1)*perlen+1
    end<-(i-1)*perlen+perlen
    period1<-U[beg:end,1]
    period2<-U[beg:end,2]
    corrs[i]<-cor(period1,period2)
}
plot(corrs,type="l")

dendat<-matrix(0,pernum-1,2)
for (i in 1:(pernum-1)){
    dendat[i,1]<-corrs[i]
    dendat[i,2]<-corrs[i+1]
}
plot(dendat)


marginal<-c("gauss","gauss")
regdat<-copula.trans(dendat,marginal=marginal)
plot(regdat)

Portfolio selection

# we use package "Rdonlp2" for the optimization

library(Rdonlp2)

Download the data

ticker<-c("^GDAXI","^MDAXI")  
destfile<-"~/pois"    
# destfile<-"C:\\Documents and Settings\\user\\Desktop\\pois"
ry<-read.yahoo(ticker, source="web", destfile=destfile)

#save(file="/home/jsk/Arti/statfina/var/DaxMdax.var",list=c("ry"))
#save(file="/Users/jsk/Karhu/Arti/statfina/var-ada/DaxMdax.var",list=c("ry"))
#load(file="/Users/jsk/Karhu/Arti/statfina/var-ada/DaxMdax.var")

dm<-data.manip(ry,ticker) 

plot(dm$data[,1],type="l")

plot(dm$data[,2],type="l")

# we calculate the price relatives

method<-rep("relative",length(ticker))
U<-returns(dm$data,method=method)
plot(U)

# we illustrate the effect of copula transform

marg<-rep("gauss",length(ticker))
V<-copula.trans(U,marg=marg)
plot(V)

# we shall use the previous price relatives to predict future price relatives 

k<-10
marginal<-"gauss"
mp<-make.portdat(U,k,marginal=marginal,rate=0.02/360)

Nearest neighbor method

# we apply the nearest neigborhood method with m nearest neighbors

m<-15
wts<-pf.nn(mp$Z,mp$arg,mp$X,m=m)

# we apply the reduced nearest neigborhood method with m nearest neighbors

m<-15
wts<-pf.nn.redu(mp$Z,mp$arg,mp$X,m=m)

# we study the historical performance of the nearest neighborhood method

estimator<-"nn"
m<-15
gamma<-1
pfseq<-pf.seq(mp$Z,mp$X,estimator=estimator,m=m,gamma=gamma)
#,quantile=TRUE,alpha=0.1)
#,markow=TRUE)

end<-length(pfseq$wealth)
back<-end #250   # round(end/2)
start<-end-back+1
plot(pfseq$wealth[start:end]/pfseq$wealth[start],type="l")

plot(pfseq$port[start:end,1])

plot(pfseq$return[start:end])

# we compare the nn-portfolio choice to the equally weighted portfolio

market<-wealth(U)
back<-length(pfseq$wealth)  #250
plot.compa(pfseq$wealth,market,back)

# we study the historical performance of the reduced nearest neighborhood method

estimator<-"nn.redu"
m<-15
gamma<-1
pfseq<-pf.seq(mp$Z,mp$X,estimator=estimator,m=m,gamma=gamma)

market<-wealth(U)
back<-length(pfseq$wealth)  #250
plot.compa(pfseq$wealth,market,back)

# visualization

neigh<-nearest.neigh(mp$arg,mp$X,m=m)
paracoor(mp$X[neigh,])         # requires package "denpro"

y<-mp$Z[,1:2]%*%c(0,1)  #wts
daat<-matrix(c(mp$X[neigh,],y[neigh]),length(y[neigh]),dim(mp$X)[2]+1,byrow=FALSE)
paracoor(daat)

# the optimization surface
 
N<-rep(40,dim(mp$Z)[2]-1)
pcf<-pf.surface(N,mp$Z,mp$arg,mp$X,m=m) #,gamma=gamma,markow=FALSE)

## 1D case

dp<-draw.pcf(pcf,pnum=N)    # need package "denpro"
plot(dp$x,dp$y,type="l")

## 2D case

dp<-draw.pcf(pcf,pnum=N)   
contour(dp$x,dp$y,dp$z,drawlabels=FALSE)
persp(dp$x,dp$y,dp$z,phi=40,theta=-50,ticktype="detailed",
xlab="b1",ylab="b2",zlab="")

## general case

lst<-leafsfirst(pcf)
plotvolu(lst)

Kernel method

k<-5
marginal<-"gauss"
n<-dim(U)[1]
# Unew<-U[(n-750):n,]
# mp<-make.portdat(Unew,k,marginal=marginal,rate=0.02/360) #,sphering=TRUE)
# plot(mp$X[,1],mp$X[,6])
mp<-make.portdat(U,k,marginal=marginal,rate=0.02/360) #,sphering=TRUE)

# we apply the kernel method with smoothing parameter h

h<-1
wts<-pf.kernel(mp$Z,mp$arg,mp$X,h=h)

# we apply the reduced kernel method with smoothing parameter h

h<-1
wts<-pf.kernel.redu(mp$Z,mp$arg,mp$X,h=h)

# we study the historical performance of the kernel method

estimator<-"kernel"
h<-1
kernel<-"gauss"
pfseq<-pf.seq(mp$Z,mp$X,estimator=estimator,h=h,kernel=kernel)

end<-length(pfseq$wealth)
back<-end #250   # round(end/2)
start<-end-back+1
plot(pfseq$wealth[start:end]/pfseq$wealth[start],type="l")

# we compare the kernel-portfolio to the equally weighted portfolio

market<-wealth(U)
back<-length(pfseq$wealth)  #250
plot.compa(pfseq$wealth,market,back)

# we study the historical performance of the reduced kernel method

estimator<-"kernel.redu"
h<-1
kernel<-"gauss"
pfseq<-pf.seq(mp$Z,mp$X,estimator=estimator,h=h,kernel=kernel)

market<-wealth(U)
back<-length(pfseq$wealth)  #250
plot.compa(pfseq$wealth,market,back)

# we study the historical performance of shorting

estimator<-"kernel.redu"
h<-2
kernel<-"gauss"
longonly<-FALSE
pfseq<-pf.seq(mp$Z,mp$X,estimator=estimator,h=h,kernel=kernel,longonly=longonly)

market<-wealth(U)
back<-250  #length(pfseq$wealth)  #250
plot.compa(pfseq$wealth,market,back)

# visualization

w<-kernesti.weights(mp$arg,mp$X,h=h)
or<-order(w)
plot(w[or])
XX<-mp$X[or,]
paletti<-grey(1-w/max(w))[or]    
paracoor(XX,paletti=paletti)

y<-mp$Z[,1:2]%*%c(0,1)
daat<-matrix(c(mp$X[neigh,],y[neigh]),length(y[neigh]),dim(mp$X)[2]+1,byrow=FALSE)
paracoor(daat)

Method of regressograms

k<-15
marginal<-"gauss"
n<-dim(U)[1]
Unew<-U[(n-750):n,]
mp<-make.portdat(Unew,k,marginal=marginal,rate=0.02/360,sphering=TRUE)
plot(mp$X[,1],mp$X[,6])

M<-10
m<-30
splitfreq<-0.5
longonly<-FALSE
wts<-pf.greedy.redu(mp$Z,mp$arg,mp$X,M=M,m=m,splitfreq=splitfreq,
longonly=longonly)

# we study the historical performance of the regressogram method

estimator<-"greedy.redu"
M<-10
m<-30
splitfreq<-0.5
longonly<-FALSE
pfseq<-pf.seq(mp$Z,mp$X,estimator=estimator,M=M,m=m,longonly=longonly,
              splitfreq=splitfreq)

# save(file="/home/jsk/Arti/greedy/var/pfseq.DaxMdax.k4.M5.m10.long.var",list=c("pfseq"))
# save(file="/home/jsk/Arti/greedy/var/pfseq.DaxMdax.k10.M7.m10.long.var",list=c("pfseq"))
# save(file="/home/jsk/Arti/greedy/var/pfseq.DaxMdax.k10.M4.m30.long.sphering.var",list=c("pfseq"))
# save(file="/home/jsk/Arti/greedy/var/pfseq.DaxMdax.k5.M5.m30.short.sphering.var",list=c("pfseq"))


end<-length(pfseq$wealth)
start<-1  #end-round(n/2)
plot(pfseq$wealth[start:end]/pfseq$wealth[start],type="l")

# we compare the kernel-portfolio to the equally weighted portfolio

market<-wealth(U)
back<-length(pfseq$wealth)  #250
plot.compa(pfseq$wealth,market,back)

Single index method

# we apply the single index method with smoothing parameter h

h<-1
wts<-pf.si.redu(mp$Z,mp$arg,mp$X,h=h)

Diagnostics

# Scale of portfolio weights

estimator<-"nn"
sseq<-seq(1,40,1)
b.scale(mp,sseq=sseq,estimator=estimator)

estimator<-"kernel"
sseq<-seq(0.5,2,0.1)
b.scale(mp,sseq=sseq,estimator=estimator)


# Scanning of historical performance

ticker<-c("^GDAXI","^N225") #"^MDAXI")  
destfile<-"~/pois"    
ry<-read.yahoo(ticker, source="web", destfile=destfile)

dm<-data.manip(ry,ticker) 

method<-rep("relative",length(ticker))
df<-data.final(dm,ticker,method=method)

d<-length(ticker)
n<-dim(df)[1]
U<-matrix(0,n,d)
for (i in 1:d) U[,i]<-df[1:n,i]

k<-5
marginal<-"gauss"
mp<-make.portdat(U,k,marginal=marginal,rate=0.02/360)

estimator<-"kernel" #"nn"
h<-1
m<-15
gamma<-1
pfseq<-pf.seq(mp$Z,mp$X,estimator=estimator,m=m,gamma=gamma,h=h)

x11()
x11()
x11()
x11()

past<-1
verti<-k*d/2+0.5
locx<-FALSE
locz<-FALSE
bscale=TRUE
sseq<-seq(0.5,2,0.1)
pf.historical(ticker,dm,mp,pfseq,past=past,estimator=estimator,m=m,h=h,verti=verti,locx=locx,locz=locz,bscale=bscale,sseq=sseq)

# Scanning of portfolios

estimator<-"kernel" #"nn"
kseq<-c(5)
hseq<-c(1,1.5)
pfseqseq<-pf.seq.seq(U,estimator=estimator,kseq=kseq,hseq=hseq)

x11()
x11()

source("~/finatool/R/pf.scale.R")
past<-1
locx<-FALSE
locz<-FALSE
bscale=TRUE
sseq<-seq(0.5,3,0.1)
pf.scale(ticker,dm,mp,pfseqseq,past=past,estimator=estimator,m=m,h=h,verti=verti,locx=locx,locz=locz,bscale=bscale,sseq=sseq)


# conditional densities

ticker<-c("^GDAXI","^MDAXI")  
destfile<-"~/pois"    
ry<-read.yahoo(ticker, source="web", destfile=destfile)
dm<-data.manip(ry,ticker) 

method<-rep("relative",length(ticker))
U<-returns(dm$data,method=method)

marginal<-"gauss"
k<-4
mp<-make.portdat(U,k,marginal=marginal,rate=0.02/360)

h<-0.1
binlkm<-5
plot.condi(Z=mp$Z,arg=mp$arg,X=mp$X,h=h,binlkm=binlkm)

plot.condi.seq(U,k=k,h=h)

# visualization of classes

estimator<-"nn"
m<-15
gamma<-1
pfseq<-pf.seq(mp$Z,mp$X,estimator=estimator,m=m,gamma=gamma)

cl<-classify(mp$X,pfseq$port)

n<-dim(mp$X)[1]
se<-seq(1,n)
se1<-se[(cl[,1]==1)]
se2<-se[(cl[,2]==1)]
se3<-se[(cl[,3]==1)]

cl1<-mp$X[se1,]
cl2<-mp$X[se2,]
cl3<-mp$X[se3,]

dim(cl1)[1]
dim(cl2)[1]
dim(cl3)[1]
dim(mp$X)[1]

maxk<-15
dendat<-cl2
radmat<-nn.radit(dendat,maxk)

k<-15
p<-0.7
upp<-nn.likeset(dendat,radmat,k,p=p) #,lambda=NULL)

see<-seq(1:dim(dendat)[1])
denosa<-dendat[see[upp==TRUE],]
paracoor(denosa)

Portfolio of options

# obtain the data

ticker<-c("^GDAXI") 
destfile<-"~/pois"       
ry<-read.yahoo(ticker, source="web", destfile=destfile)
#save(file="/home/jsk/Arti/statfina/Dax.var",list=c("ry"))
#load(file="/Users/jsk/Karhu/Arti/statfina/DaxMdax.var")
dm<-data.manip(ry,ticker) 
method<-"price"
df<-data.final(dm,ticker,method=method) 
n<-dim(df)[1]
beg<-4000
S<-matrix(df[beg:n,1],n-beg+1,1)
plot(S,type="l")

# set the parameters

S0<-S[length(S)]      # current stock price
t<-0.04               # time to expiration in fractions of year
r<-0.05               # yearly risk free rate

# find the current option prices

odax<-read.csv("~/odax")

for (i in 1:length(odax$Symbol)){
 if (odax$P.C[i]=="C") type<-"call" else type<-"put"
 if (is.na(odax$Bid[i])) bid<-odax$Last[i] else bid<-odax$Bid[i]
 if (is.na(odax$Ask[i])) ask<-odax$Last[i] else ask<-odax$Ask[i]
 odax$IVbid[i]<-bs.implied(bid,S0,odax$Strike[i],r,t,type)
 odax$IVask[i]<-bs.implied(ask,S0,odax$Strike[i],r,t,type) 
}
odaxi<-odax
odaxi$Symbol<-NULL
odaxi$Type<-NULL
odaxi$Exchange<-NULL
odaxi$Currency<-NULL
odaxi

# choose the base instruments

options<-read.table("~/Arti/statfina/options2.t",header=TRUE,na.string="-",
colClasses=c("character","character","integer","real","integer","real"))
options

# construct the vectors of response variables

daysinyear<-250
z<-option.data(S,t,r,options,daysinyear=daysinyear)

plot(z[,1])

mean(z[,1])

histo1d(z[,2],20)

# construct the explanatory variables (we use the previous price data)

method<-"relative"
U<-returns(S,method=method)
k<-4
mp<-make.portdat(U,k)
x<-mp$X

lenz<-dim(z)[1]
lenx<-dim(x)[1]
T<-round(daysinyear*t)

X<-x[1:(lenx-T),]     # explanatory variables are in history
lennewz<-lenx-T
begz<-lenz-lennewz+1
Z<-z[begz:lenz,]      # z is longer than X, so that we remove at the beg

arg<-x[lenx,]

# we apply the nearest neigborhood method with m nearest neighbors

m<-10
wts<-pf.nn(Z,arg,X,m=m)

# we apply the kernel method with smoothing parameter h

h<-1
wts<-pf.kernel(Z,arg,X,h=h)

Maximum likelihood estimation

# we use package "Rdonlp2" for the optimization

library(Rdonlp2)

# simulate data from a Student distribution

set.seed(1)
n<-1000
mu<-0
sigma<-1
df<-6
x<-mu+sigma*rt(n=n,df=df)

# set the constraints

mu.low<--1
mu.upp<-1
sigma.low<-0
sigma.upp<-4
nu.low<-3
nu.upp<-10

# estimate the parameters

para<-ml(x,
mu.low=mu.low,mu.upp=mu.upp,
sigma.low=sigma.low,sigma.upp=sigma.upp,
nu.low=nu.low,nu.upp=nu.upp)
para

# simulate a stock price process a logarithmic Student distribution

S0<-100
model.type<-"log-return"  #"incre"
dist<-"student"

annu.mu<-0.1
annu.vola<-0.2
df<-4

len<-1000
seed<-2
S<-sim.ts(len,S0=S0,annu.vola=annu.vola,annu.mu=annu.mu,
          model.type=model.type,seed=seed,
          dist=dist,df=df)
plot(S,type="l")

# set the constraints

mu.low<--0.1
mu.upp<-0.1
sigma.low<-0
sigma.upp<-1
nu.low<-2
nu.upp<-10

# estimate the parameters

x<-returns(S,method="loga")
para<-ml(x,
         mu.low=mu.low,mu.upp=mu.upp,
         sigma.low=sigma.low,sigma.upp=sigma.upp,
         nu.low=nu.low,nu.upp=nu.upp)

mu.estim<-para[1]
annu.mu.estim<-para[1]*250
annu.vola.estim<-para[2]*sqrt(250)
nu.estim<-para[3]

mean(x)*250
annu.mu.estim
annu.vola.estim
nu.estim