fAssets/ 0000755 0001760 0000144 00000000000 12254146510 011712 5 ustar ripley users fAssets/inst/ 0000755 0001760 0000144 00000000000 12251673345 012677 5 ustar ripley users fAssets/inst/COPYRIGHT.html 0000644 0001760 0000144 00000020411 11370220754 015124 0 ustar ripley users
Rmetrics::COPYRIGHT
Rmetrics
Copyrights
2005-12-18 Built 221.10065
________________________________________________________________________________
Copyrights (C) for
R:
see R's copyright and license file
Version R 2.0.0 claims:
- The stub packages from 1.9.x have been removed.
- All the datasets formerly in packages 'base' and 'stats' have
been moved to a new package 'datasets'.
- Package 'graphics' has been split into 'grDevices' (the graphics
devices shared between base and grid graphics) and 'graphics'
(base graphics).
- Packages must have been re-installed for this version, and
library() will enforce this.
- Package names must now be given exactly in library() and
require(), regardless of whether the underlying file system is
case-sensitive or not.
________________________________________________________________________________
for
Rmetrics:
(C) 1999-2005, Diethelm Wuertz, GPL
Diethelm Wuertz
www.rmetrics.org
info@rmetrics.org
________________________________________________________________________________
for non default loaded basic packages part of R's basic distribution
MASS:
Main Package of Venables and Ripley's MASS.
We assume that MASS is available.
Package 'lqs' has been returned to 'MASS'.
S original by Venables & Ripley.
R port by Brian Ripley .
Earlier work by Kurt Hornik and Albrecht Gebhardt.
methods:
Formally defined methods and classes for R objects, plus other
programming tools, as described in the reference "Programming
with Data" (1998), John M. Chambers, Springer NY.
R Development Core Team.
mgcv:
Routines for GAMs and other generalized ridge regression
with multiple smoothing parameter selection by GCV or UBRE.
Also GAMMs by REML or PQL. Includes a gam() function.
Simon Wood
nnet:
Feed-forward Neural Networks and Multinomial Log-Linear Models
Original by Venables & Ripley.
R port by Brian Ripley .
Earlier work by Kurt Hornik and Albrecht Gebhardt.
________________________________________________________________________________
for the code partly included as builtin functions from other R ports:
fBasics:CDHSC.F
GRASS program for distributional testing.
By James Darrell McCauley
Original Fortran Source by Paul Johnson EZ006244@ALCOR.UCDAVIS.EDU>
fBasics:nortest
Five omnibus tests for the composite hypothesis of normality
R-port by Juergen Gross
fBasics:SYMSTB.F
Fast numerical approximation to the Symmetric Stable distribution
and density functions.
By Hu McCulloch
fBasics:tseries
Functions for time series analysis and computational finance.
Compiled by Adrian Trapletti
fCalendar:date
The tiny C program from Terry Therneau is used
R port by Th. Lumley ,
K. Halvorsen , and
Kurt Hornik
fCalendar:holidays
The holiday information was collected from the internet and
governmental sources obtained from a few dozens of websites
fCalendar:libical
Libical is an Open Source implementation of the IETF's
iCalendar Calendaring and Scheduling protocols. (RFC 2445, 2446,
and 2447). It parses iCal components and provides a C API for
manipulating the component properties, parameters, and subcomponents.
fCalendar:vtimezone
Olsen's VTIMEZONE database consists of data files are released under
the GNU General Public License, in keeping with the license options of
libical.
fSeries:bdstest.c
C Program to compute the BDS Test.
Blake LeBaron
fSeries:fracdiff
R functions, help pages and the Fortran Code for the 'fracdiff'
function are included.
S original by Chris Fraley
R-port by Fritz Leisch
since 2003-12: Martin Maechler
fSeries:lmtest
R functions and help pages for the linear modelling tests are included .
Compiled by Torsten Hothorn ,
Achim Zeileis , and
David Mitchell
fSeries:mda
R functions, help pages and the Fortran Code for the 'mars' function
are implemeted.
S original by Trevor Hastie & Robert Tibshirani,
R port by Friedrich Leisch, Kurt Hornik and Brian D. Ripley
fSeries:modreg
Brian Ripley and the R Core Team
fSeries:polspline
R functions, help pages and the C/Fortran Code for the 'polymars'
function are implemented
Charles Kooperberg
fSeries:systemfit
Simultaneous Equation Estimation Package.
R port by Jeff D. Hamann and
Arne Henningsen
fSeries:tseries
Functions for time series analysis and computational finance.
Compiled by Adrian Trapletti
fSeries:UnitrootDistribution:
The program uses the Fortran routine and the tables
from J.G. McKinnon.
fSeries:urca
Unit root and cointegration tests for time series data.
R port by Bernhard Pfaff .
fExtremes:evd
Functions for extreme value distributions.
R port by Alec Stephenson
Function 'fbvpot' by Chris Ferro.
fExtremes:evir
Extreme Values in R
Original S functions (EVIS) by Alexander McNeil
R port by Alec Stephenson
fExtremes:ismev
An Introduction to Statistical Modeling of Extreme Values
Original S functions by Stuart Coles
R port/documentation by Alec Stephenson
fOptions
Option Pricing formulas are implemented along the book and
the Excel spreadsheets of E.G. Haug, "The Complete Guide to Option
Pricing"; documentation is partly taken from www.derivicom.com which
implements a C Library based on Haug. For non-academic and commercial
use we recommend the professional software from "www.derivicom.com".
fOptions:SOBOL.F
ACM Algorithm 659 by P. Bratley and B.L. Fox
Extension on Algorithm 659 by S. Joe and F.Y. Kuo
fOptions:CGAMA.F
Complex gamma and related functions.
Fortran routines by Jianming Jin.
fOptions:CONHYP.F
Confluenet Hypergeometric and related functions.
ACM Algorithm 707 by mark Nardin, W.F. Perger, A. Bhalla
fPortfolio:mvtnorm
Multivariate Normal and T Distribution.
Alan Genz ,
Frank Bretz
R port by Torsten Hothorn
fPortfolio:quadprog
Functions to solve Quadratic Programming Problems.
S original by Berwin A. Turlach
R port by Andreas Weingessel
fPortfolio:sn
The skew-normal and skew-t distributions.
R port by Adelchi Azzalini
fPortfolio:tseries
Functions for time series analysis and computational finance.
Compiled by Adrian Trapletti
fAssets/inst/unitTests/ 0000755 0001760 0000144 00000000000 12251673345 014701 5 ustar ripley users fAssets/inst/unitTests/Makefile 0000644 0001760 0000144 00000000420 11370220754 016326 0 ustar ripley users PKG=fAssets
TOP=../..
SUITE=doRUnit.R
R=R
all: inst test
inst: # Install package -- but where ?? -- will that be in R_LIBS ?
cd ${TOP}/..;\
${R} CMD INSTALL ${PKG}
test: # Run unit tests
export RCMDCHECK=FALSE;\
cd ${TOP}/tests;\
${R} --vanilla --slave < ${SUITE}
fAssets/inst/unitTests/runit.AssetsMeanCov.R 0000644 0001760 0000144 00000003352 11370220754 020673 0 ustar ripley users
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU Library General
# Public License along with this library; if not, write to the
# Free Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307 USA
# Copyrights (C)
# for this R-port:
# 1999 - 2007, Diethelm Wuertz, GPL
# Diethelm Wuertz
# info@rmetrics.org
# www.rmetrics.org
# for the code accessed (or partly included) from other R-ports:
# see R's copyright and license files
# for the code accessed (or partly included) from contributed R-ports
# and other sources
# see Rmetrics's copyright file
################################################################################
# FUNCTION: ASSETS STATISTICS:
# assetsMeanCov Estimates mean and variance for a set of assets
################################################################################
test.assetsMeanCov =
function()
{
# Time Series Object:
Data <- as.timeSeries(LPP2005REC)[, 1:6]
# Settings:
class(Data)
# use "cov":
args(assetsMeanCov)
assetsMeanCov(Data)
# use "shrink"
assetsMeanCov(Data, "shrink")
# Return Value:
return()
}
################################################################################
fAssets/inst/unitTests/runit.AssetsFit.R 0000644 0001760 0000144 00000010322 11370220754 020060 0 ustar ripley users
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU Library General
# Public License along with this library; if not, write to the
# Free Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307 USA
# Copyrights (C)
# for this R-port:
# 1999 - 2007, Diethelm Wuertz, GPL
# Diethelm Wuertz
# info@rmetrics.org
# www.rmetrics.org
# for the code accessed (or partly included) from other R-ports:
# see R's copyright and license files
# for the code accessed (or partly included) from contributed R-ports
# and other sources
# see Rmetrics's copyright file
################################################################################
# FUNCTION: SIMULATION AND PARAMETER ESTIMATION:
# 'fASSETS' Class representation for "fASSETS" Objects
# assetsSim Simulates a set of artificial assets
# assetsFit Estimates the parameters of set of assets
# method = "norm" assuming a multivariate Normal distribution
# method = "snorm" assuming a multivariate skew-Normal distribution
# method = "st" assuming a multivariate skew-Student-t
# FUNCTION: PRINT, PLOT AND SUMMARY METHOD:
# show.fASSETS S4: Print method for an object of class fASSETS
# plot.fASSETS S3: Plot method for an object of class fASSETS
# summary.fASSETS S3: Summary method for an object of class fASSETS
# FUNCTION: REQUIRED UTILITY FUNCTION:
# .msn.quantities Function from R package sn [part of fMultivar]
################################################################################
test.assetsSim =
function()
{
# assetsSim(n, dim=2, model =
# list(mu=rep(0, dim), Omega=diag(dim), alpha=rep(0, dim), df=Inf),
# assetNames = NULL)
# Normel Assets:
assetsSim(n = 10, dim = 3)
assetsSim(n = 10, dim = 3,
list(mu=rep(0, 3), Omega=diag(3), alpha=rep(0.0, 3), df=Inf))
# Skew Normal Assets:
assetsSim(n = 10, dim = 3, model =
list(mu=rep(0, 3), Omega=diag(3), alpha=rep(0.1, 3), df=Inf))
# Student-t Assets:
assetsSim(n = 10, dim = 3, model =
list(mu=rep(0, 3), Omega=diag(3), alpha=rep(0.0, 3), df=4))
# Skew Student-t Assets:
assetsSim(n = 10, dim = 3, model =
list(mu=rep(0, 3), Omega=diag(3), alpha=rep(0.1, 3), df=4))
# Add Asset Names:
assetsSim(n = 10, dim = 3, assetNames = c("A", "B", "C"))
# Return Value:
return()
}
# ------------------------------------------------------------------------------
test.assetsFit =
function()
{
# function (x, method = c("st", "snorm", "norm"), title = NULL,
# description = NULL, fixed.df = NA, ...)
# Normal Assets:
x = assetsSim(n = 1000, dim = 3)
fit = assetsFit(x, "norm")
fit
# Skew Normal Assets:
x = assetsSim(n = 1000, dim = 3, model =
list(mu=rep(0, 3), Omega=diag(3), alpha=c(-0.5, 0 , 0.5), df=Inf))
fit = assetsFit(x, "snorm")
fit
# Student-t Assets:
x = assetsSim(n = 1000, dim = 3, model =
list(mu=rep(0, 3), Omega=diag(3), alpha=rep(0, 3), df=4))
fit = assetsFit(x, "st")
fit
# Student-t Assets - Fixed df:
x = assetsSim(n = 1000, dim = 3, model =
list(mu=rep(0, 3), Omega=diag(3), alpha=rep(0, 3), df=4))
fit = assetsFit(x, "st", fixed.df = 4)
fit
par(ask = FALSE)
class(fit)
print(fit)
plot(fit, which = "all") # CHECK X-Label
summary(fit, doplot = FALSE) # CHECK - add doplot
# Return Value:
return()
}
################################################################################
fAssets/inst/unitTests/runit.AssetsSelect.R 0000644 0001760 0000144 00000014754 11370220754 020572 0 ustar ripley users
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU Library General
# Public License along with this library; if not, write to the
# Free Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307 USA
# Copyrights (C)
# for this R-port:
# 1999 - 2007, Diethelm Wuertz, GPL
# Diethelm Wuertz
# info@rmetrics.org
# www.rmetrics.org
# for the code accessed (or partly included) from other R-ports:
# see R's copyright and license files
# for the code accessed (or partly included) from contributed R-ports
# and other sources
# see Rmetrics's copyright file
################################################################################
# FUNCTION: ASSETS SELECTION:
# assetsSelect Selects individual assets from a set of assets
# use = "hclust" hierarchical clustering of returns
# use = "kmeans" k-means clustering of returns
################################################################################
test.assetsSelectHClust =
function()
{
if (FALSE) {
# Hierarchical Clustering:
# Select the 4 most dissimilar assets from Berndt's data set
# The data set "berndtInvest" is from Berndt's textbook
# "The Practice of Econometrics". It is a data.frame consisting
# of 18 columns with the following entries:
# [1] %d/%B/%y "CITCRP" "CONED" "CONTIL" "DATGEN" "DEC"
# [7] "DELTA" "GENMIL" "GERBER" "IBM" "MARKET" "MOBIL"
# [13] "PANAM" "PSNH" "TANDY" "TEXACO" "WEYER" "RKFREE"
# The first column holds the date, the 11th the market rate,
# and the last (the 18th) the risk free rate.
# Load the Data and Create an Object of Class 'timeSeries':
data(berndtInvest)
berndtInvest = as.timeSeries(berndtInvest)
class(berndtInvest)
head(berndtInvest)
# Exclude the Date, Market Returns and Interest Rate Columns
# from the data frame, then multiply by 100 for percentual returns ...
allAssets = 100 * berndtInvest[, -c(1, 10, 17)]
class(allAssets)
head(allAssets)
# Graph Frame:
par(mfrow = c(2, 1), cex = 0.7)
# Select the "n" Most Dissimilar Assets from
# Hierarchical Clustering:
n = 4
args(assetsSelect)
clustered = assetsSelect(allAssets, doplot = TRUE)
# Create my Assets Set from the "n" selected Symbols:
myAssets = allAssets[, c(clustered$order[1:n])]
colnames(myAssets)
# Print the Column Return:
mu.vec = colMeans(myAssets)
mu.vec
# or ...
mu.vec = colMeans(series(myAssets))
mu.vec
# Print the Covariance Matrix:
cov.mat = cov(series(myAssets))
cov.mat
# Plot Cumulated Returns of the Assets:
ts.plot(colCumsums(myAssets), col = 1:4)
grid()
legend(0, 250, legend = colnames(myAssets), pch = "----", col = 1:4)
title(main = "Cumulated Returns", ylab = "Cumulated Returns")
abline(h = 0, lty = 3)
}
NA
# Return Value:
return()
}
# ------------------------------------------------------------------------------
test.assetsSelectKMeans =
function()
{
# K-Means Clustering:
if (FALSE) {
# Load Data
berndtInvest = as.timeSeries(data(berndtInvest))
allAssets = 100 * berndtInvest[, -c(1, 10, 17)]
allAssets = as.matrix(allAssets)
head(allAssets)
# assetsSelect(x, use = c("hclust", "kmeans"), doplot = TRUE, ...)
clustered = assetsSelect(t(allAssets), use = "kmeans",
centers = 4, doplot = TRUE)
}
NA
# Return Value:
return()
}
# ------------------------------------------------------------------------------
test.assetsSelectKMeans =
function()
{
if (FALSE) {
require(cluster)
.assetsSelect =
function (x, k,
use = c("hclust", "kmeans", "agnes", "diana", "pam", "clara"),
doplot = TRUE, control = FALSE, ...)
{
# Settings:
X = as.matrix(x)
use = match.arg(use)
# Hierarchical Clustering:
if (use == "hclust") {
ans = hclust(dist(t(X)), ...)
index = rev(ans$order)[1:k]
if (doplot) plot(ans)
}
if (use == "agnes") {
ans = agnes(t(X), ...)
index = rev(ans$order)[1:k]
if (doplot) plot(ans)
}
if (use == "diana") {
ans = diana(t(X), ...)
index = rev(ans$order)[1:k]
if (doplot) plot(ans)
}
# K-Means Clustering:
if (use == "kmeans") {
ans = kmeans(x = X, centers = k, ...)
Dist = rep(Inf, times = k)
index = rep(NA, times = k)
Center = ans$center
Cluster = ans$cluster
for (i in 1:length(Cluster)) {
j = Cluster[i]
d = as.vector(dist(rbind(Center[j,], X[,i])))
if (d < Dist[j]) {
Dist[j] = d
index[j] = i
}
}
if (doplot) {
plot(t(X), col = ans$cluster)
points(ans$centers, col = 1:k, pch = 8, cex = 2)
}
}
if (use == "pam") {
ans = pam(t(X), k, ...)
index = ans$id.med
if (doplot) plot(ans)
}
if (use == "clara") {
ans = clara(t(X), k, ...)
index = ans$i.med
if (doplot) plot(ans)
}
# Select data and optionally add control:
data = x[, index]
if (control) attr(data, "control")<-ans
# Return Value:
data
}
# Data:
berndtInvest = as.timeSeries(data(berndtInvest))
X = 100 * berndtInvest[, -c(1, 10, 17)]
# Selection:
.assetsSelect(X, 4, "hclust", doplot = FALSE)
.assetsSelect(X, 4, "agnes", doplot = FALSE)
.assetsSelect(X, 4, "diana", doplot = FALSE)
.assetsSelect(X, 4, "kmeans", doplot = FALSE)
.assetsSelect(X, 4, "pam", doplot = FALSE)
.assetsSelect(X, 4, "clara", doplot = FALSE)
}
NA
# Return Value:
return()
}
################################################################################
fAssets/inst/unitTests/runit.AssetsPlots.R 0000644 0001760 0000144 00000013326 11370220754 020446 0 ustar ripley users
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU Library General
# Public License along with this library; if not, write to the
# Free Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307 USA
# Copyrights (C)
# for this R-port:
# 1999 - 2007, Diethelm Wuertz, GPL
# Diethelm Wuertz
# info@rmetrics.org
# www.rmetrics.org
# for the code accessed (or partly included) from other R-ports:
# see R's copyright and license files
# for the code accessed (or partly included) from contributed R-ports
# and other sources
# see Rmetrics's copyright file
################################################################################
# FUNCTION: TIME SERIES ASSETS PLOTS:
# assetsSeriesPlot Displays time series of individual assets
# assetsHistPlot Displays histograms of individual assets
# assetsDensityPlot Displays density plots of individual assets
# assetsQQNormPlot Displays normal qq-plots of individual assets
# FUNCTION: DENSITY BOX PLOTS:
# assetsBoxPlot Producess standard box plots
# assetsBoxPercentilePlot Producess side-by-side box-percentile plots
# FUNCTION: BIVARIATE ASSETS PLOTS:
# assetsPairsPlot Displays pairs of scatterplots of assets
# assetsCorgramPlot Displays correlations between assets
# assetsCorTestPlot Displays and tests pairwise correlations
# FUNCTION: BIVARIATE CORRELATION PLOTS:
# assetsCorEigenPlot Displays ratio of the largest two eigenvalues
# *assetsTreePlot Displays minimum spanning tree of assets
# assetsDendogramPlot Displays hierarchical clustering dendogram
# .assetsStarPlot Draws segment diagrams of a multivariate data set
################################################################################
# *moved to Rmetrics addon Package
test.assetsSeriesPlot =
function()
{
LPP = as.timeSeries(data(LPP2005REC))
par(mfrow = c(3, 3))
par(ask = FALSE)
assetsSeriesPlot(LPP)
# Return Value:
return()
}
# ------------------------------------------------------------------------------
test.assetsHistPlot =
function()
{
LPP = as.timeSeries(data(LPP2005REC))
par(mfrow = c(3, 3))
par(ask = FALSE)
assetsHistPlot(LPP)
# Return Value:
return()
}
# ------------------------------------------------------------------------------
test.assetsQQNormPlot =
function()
{
LPP = as.timeSeries(data(LPP2005REC))
par(mfrow = c(3, 3))
par(ask = FALSE)
assetsQQNormPlot(LPP)
# Return Value:
return()
}
################################################################################
test.assetsBoxPlot =
function()
{
LPP = as.timeSeries(data(LPP2005REC))
par(mfrow = c(3, 3))
par(ask = FALSE)
# Plot:
assetsBoxPlot(LPP)
# Return Value:
return()
}
# ------------------------------------------------------------------------------
test.assetsQQNormPlot =
function()
{
LPP = as.timeSeries(data(LPP2005REC))
par(mfrow = c(3, 3))
par(ask = FALSE)
# Plot:
assetsBoxPercentilePlot(LPP)
# Return Value:
return()
}
################################################################################
test.assetsPairsPlot =
function()
{
LPP = as.timeSeries(data(LPP2005REC))[, 1:6]
par(mfrow = c(1, 1))
par(ask = FALSE)
# Plot:
assetsPairsPlot(LPP)
# Return Value:
return()
}
# ------------------------------------------------------------------------------
test.assetsCorTestPlot =
function()
{
LPP = as.timeSeries(data(LPP2005REC))[, 1:6]
par(mfrow = c(1, 1))
par(ask = FALSE)
# Plot:
assetsCorTestPlot(LPP)
# Return Value:
return()
}
################################################################################
test.assetsCorgramPlot =
function()
{
LPP = as.timeSeries(data(LPP2005REC))[, 1:6]
par(mfrow = c(1, 1))
par(ask = FALSE)
# Plot:
assetsCorgramPlot(LPP)
# Return Value:
return()
}
# ------------------------------------------------------------------------------
test.assetsCorEigenPlot =
function()
{
LPP = as.timeSeries(data(LPP2005REC))[, 1:6]
par(mfrow = c(1, 1))
par(ask = FALSE)
# Plot:
assetsCorEigenPlot(LPP)
# Return Value:
return()
}
# ------------------------------------------------------------------------------
test.assetsTreePlot =
function()
{
LPP = as.timeSeries(data(LPP2005REC))[, 1:6]
par(mfrow = c(1, 1))
par(ask = FALSE)
# Plot:
assetsTreePlot(LPP)
# Return Value:
return()
}
# ------------------------------------------------------------------------------
assetsDendogramPlot =
function()
{
LPP = as.timeSeries(data(LPP2005REC))[, 1:6]
par(mfrow = c(1, 1))
par(ask = FALSE)
# Plot:
assetsDendrogramPlot(LPP)
# Return Value:
return()
}
################################################################################
fAssets/inst/unitTests/runit.AssetsTests.R 0000644 0001760 0000144 00000003222 11370220754 020441 0 ustar ripley users
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU Library General
# Public License along with this library; if not, write to the
# Free Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307 USA
# Copyrights (C)
# for this R-port:
# 1999 - 2007, Diethelm Wuertz, GPL
# Diethelm Wuertz
# info@rmetrics.org
# www.rmetrics.org
# for the code accessed (or partly included) from other R-ports:
# see R's copyright and license files
# for the code accessed (or partly included) from contributed R-ports
# and other sources
# see Rmetrics's copyright file
################################################################################
# FUNCTION: ASSETS NORMALITY TESTS:
# assetsTest TestSuite for multivariate Normal Assets
# mvshapiroTest Multivariate Shapiro Test
################################################################################
test.assetsTest <-
function()
{
# Default Method:
x = assetsSim(100)
assetsTest(x)
# Return Value:
return()
}
################################################################################
fAssets/inst/unitTests/runTests.R 0000644 0001760 0000144 00000004527 11370220754 016654 0 ustar ripley users pkg <- "fAssets"
if(require("RUnit", quietly = TRUE))
{
library(package=pkg, character.only = TRUE)
if(!(exists("path") && file.exists(path)))
path <- system.file("unitTests", package = pkg)
## --- Testing ---
## Define tests
testSuite <- defineTestSuite(name = paste(pkg, "unit testing"),
dirs = path)
if(interactive()) {
cat("Now have RUnit Test Suite 'testSuite' for package '",
pkg, "' :\n", sep='')
str(testSuite)
cat('', "Consider doing",
"\t tests <- runTestSuite(testSuite)", "\nand later",
"\t printTextProtocol(tests)", '', sep = "\n")
} else {
## run from shell / Rscript / R CMD Batch / ...
## Run
tests <- runTestSuite(testSuite)
if(file.access(path, 02) != 0) {
## cannot write to path -> use writable one
tdir <- tempfile(paste(pkg, "unitTests", sep="_"))
dir.create(tdir)
pathReport <- file.path(tdir, "report")
cat("RUnit reports are written into ", tdir, "/report.(txt|html)",
sep = "")
} else {
pathReport <- file.path(path, "report")
}
## Print Results:
printTextProtocol(tests, showDetails = FALSE)
printTextProtocol(tests, showDetails = FALSE,
fileName = paste(pathReport, "Summary.txt", sep = ""))
printTextProtocol(tests, showDetails = TRUE,
fileName = paste(pathReport, ".txt", sep = ""))
## Print HTML Version to a File:
## printHTMLProtocol has problems on Mac OS X
if (Sys.info()["sysname"] != "Darwin")
printHTMLProtocol(tests,
fileName = paste(pathReport, ".html", sep = ""))
## stop() if there are any failures i.e. FALSE to unit test.
## This will cause R CMD check to return error and stop
tmp <- getErrors(tests)
if(tmp$nFail > 0 | tmp$nErr > 0) {
stop(paste("\n\nunit testing failed (#test failures: ", tmp$nFail,
", R errors: ", tmp$nErr, ")\n\n", sep=""))
}
}
} else {
cat("R package 'RUnit' cannot be loaded -- no unit tests run\n",
"for package", pkg,"\n")
}
################################################################################
fAssets/inst/unitTests/runit.LowerPartialMoments.R 0000644 0001760 0000144 00000003127 11370220754 022130 0 ustar ripley users
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU Library General
# Public License along with this library; if not, write to the
# Free Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307 USA
# Copyrights (C)
# for this R-port:
# 1999 - 2007, Diethelm Wuertz, GPL
# Diethelm Wuertz
# info@rmetrics.org
# www.rmetrics.org
# for the code accessed (or partly included) from other R-ports:
# see R's copyright and license files
# for the code accessed (or partly included) from contributed R-ports
# and other sources
# see Rmetrics's copyright file
################################################################################
# FUNCTION: ASSETS STATISTICS:
# assetsLPM Computes Lower Partial Moments
################################################################################
test.assetsLPM =
function()
{
tS = as.timeSeries(data(LPP2005REC))[, 1:6]
assetsLPM(x = tS, tau = colMeans(tS), a = 1)
# Return Value:
return()
}
################################################################################
fAssets/tests/ 0000755 0001760 0000144 00000000000 12251673345 013064 5 ustar ripley users fAssets/tests/doRUnit.R 0000644 0001760 0000144 00000001636 11370220753 014571 0 ustar ripley users #### doRUnit.R --- Run RUnit tests
####------------------------------------------------------------------------
### Origianlly follows Gregor Gojanc's example in CRAN package 'gdata'
### and the corresponding section in the R Wiki:
### http://wiki.r-project.org/rwiki/doku.php?id=developers:runit
### MM: Vastly changed: This should also be "runnable" for *installed*
## package which has no ./tests/
## ----> put the bulk of the code e.g. in ../inst/unitTests/runTests.R :
if(require("RUnit", quietly=TRUE)) {
## --- Setup ---
wd <- getwd()
pkg <- sub("\\.Rcheck$", '', basename(dirname(wd)))
library(package=pkg, character.only=TRUE)
path <- system.file("unitTests", package = pkg)
stopifnot(file.exists(path), file.info(path.expand(path))$isdir)
source(file.path(path, "runTests.R"), echo = TRUE)
}
################################################################################
fAssets/src/ 0000755 0001760 0000144 00000000000 12254131717 012504 5 ustar ripley users fAssets/src/Makevars 0000644 0001760 0000144 00000000036 11370220753 014174 0 ustar ripley users PKG_LIBS=$(BLAS_LIBS) $(FLIBS) fAssets/src/ecodist.c 0000644 0001760 0000144 00000046666 12254131720 014316 0 ustar ripley users #include
#include
#include /* for dgemm */
#define RANDIN seed_in((long *)NULL)
#define RANDOUT seed_out((long *)NULL)
#define UNIF unif_rand()
#define S_EVALUATOR
void bootstrap(double *x, double *y, int *n, int *xlen, int *nboot, double *pboot, double *bootcor, int *rarray, int *rmat, double *xdif, double *ydif)
{
int i, j, k, l;
double r;
double nsamp;
double xmean, ymean;
double xsum;
double xxsum, yysum;
S_EVALUATOR
/* Set random seed using Splus function */
RANDIN;
for(i = 0; i < *nboot; i++) {
/* Set up rarray. */
for(j = 0; j < *n; j++) {
r = UNIF;
if(r > *pboot)
rarray[j] = 0;
else rarray[j] = 1;
}
/* Turn rarray into a lower-triangular sampling matrix. */
/* 1 means include, 0 means omit. */
l = 0;
for(j = 1; j < *n; j++) {
for(k = 0; k < j; k++) {
if(rarray[j] == 0 || rarray[k] == 0)
rmat[l] = 0;
else rmat[l] = 1;
l++;
}
}
nsamp = 0;
for(j = 0; j < *xlen; j++) {
nsamp += rmat[j];
}
/* Calculate means for x and y. */
xmean = 0;
ymean = 0;
for(j = 0; j < *xlen; j++) {
if(rmat[j] == 1) {
xmean += x[j];
ymean += y[j];
}
}
xmean = xmean/nsamp;
ymean = ymean/nsamp;
/* Calculate deviations for x and y. */
for(j = 0; j < *xlen; j++) {
if(rmat[j] == 1) {
xdif[j] = x[j] - xmean;
ydif[j] = y[j] - ymean;
}
else {
xdif[j] = 0;
ydif[j] = 0;
}
}
xsum = 0;
xxsum = 0;
yysum = 0;
for(j = 0; j < *xlen; j++) {
if(rmat[j] == 1) {
xsum += (xdif[j] * ydif[j]);
xxsum += (xdif[j] * xdif[j]);
yysum += (ydif[j] * ydif[j]);
}
}
bootcor[i] = (xsum) / sqrt(xxsum * yysum);
}
/* Reset random seed using an Splus function. */
RANDOUT;
}
/* DW renamed permute to permute2 */
void permute2(double *x, double *y, int *n, int *xlen, int *nperm,
double *zstats, double *tmat, int *rarray)
{
int i, k, l, m;
double cumsum;
int temp;
S_EVALUATOR
/* Set random seed using Splus function */
RANDIN;
/* Calculate first z-statistic (unpermuted data). */
cumsum = 0;
for(k = 0; k < *xlen; k++) {
cumsum += x[k] * y[k];
}
zstats[0] = cumsum / *xlen;
/* Start permutation routine */
for(i = 1; i < *nperm; i++) {
/* Set up rarray. */
for(k = 0; k < *n; k++) {
rarray[k] = k;
}
/* Convert x to a full matrix. */
m = 0;
for(k = 1; k < *n; k++) {
for(l = 0; l < k; l++) {
tmat[k * *n + l] = x[m];
tmat[l * *n + k] = x[m];
m++;
}
}
/* Randomize rarray using an Splus function. */
for(k = 0; k < (*n - 1); k++) {
l = *n - k - 1;
m = (int)((float)l * UNIF);
if(m > l) m = l;
temp = rarray[l];
rarray[l] = rarray[m];
rarray[m] = temp;
}
/* Reorder x. */
m = 0;
for(k = 1; k < *n; k++) {
for(l = 0; l < k; l++) {
x[m] = tmat[rarray[k] * *n + rarray[l]];
m++;
}
}
/* Calculate new sum of products. */
cumsum = 0;
for(k = 0; k < *xlen; k++) {
cumsum += x[k] * y[k];
}
zstats[i] = cumsum / *xlen;
}
/* Reset random seed using an Splus function. */
RANDOUT;
}
void permpart(double *hmat, double *bmat, double *omat, double *y, double *xcor, double *ycor, int *n, int *ncol, int *xlen, int *nperm, double *zstats, double *tmat, int *rarray)
{
int i, k, l, m;
double cumsum;
double bsum;
double w1, w2;
int temp;
S_EVALUATOR
/* Set random seed using Splus function */
RANDIN;
/* Calculate first z-statistic (unpermuted data). */
cumsum = 0;
for(k = 0; k < *xlen; k++) {
cumsum += xcor[k] * ycor[k];
}
zstats[0] = cumsum / *xlen;
/* Start permutation routine */
for(i = 1; i < *nperm; i++) {
/* Set up rarray. */
for(k = 0; k < *n; k++) {
rarray[k] = k;
}
/* Convert y to a full matrix. */
m = 0;
for(k = 1; k < *n; k++) {
for(l = 0; l < k; l++) {
tmat[k * *n + l] = y[m];
tmat[l * *n + k] = y[m];
m++;
}
}
/* Randomize rarray using an Splus function. */
for(k = 0; k < (*n - 1); k++) {
l = *n - k - 1;
m = (int)((float)l * UNIF);
if(m > l) m = l;
temp = rarray[l];
rarray[l] = rarray[m];
rarray[m] = temp;
}
/* Reorder y. */
m = 0;
for(k = 1; k < *n; k++) {
for(l = 0; l < k; l++) {
y[m] = tmat[rarray[k] * *n + rarray[l]];
m++;
}
}
/* Calculate residuals for y */
/* Calculate bmat */
for(k = 0; k < *ncol; k++) {
bmat[k] = 0;
}
for(k = 0; k < *ncol; k++) {
for(l = 0; l < *xlen; l++) {
bmat[k] = bmat[k] + hmat[l * *ncol + k] * y[l];
}
}
/* Calculate ycor (residuals) */
for(k = 0; k < *xlen; k++) {
ycor[k] = 0;
}
for(k = 0; k < *xlen; k++) {
bsum = 0;
for(l = 0; l < *ncol; l++) {
bsum = bsum + bmat[l] * omat[l * *xlen + k];
}
ycor[k] = y[k] - bsum;
}
/* Standardize residuals so z = r */
w1 = 0;
w2 = 0;
for(k = 0; k < *xlen; k++) {
w1 = w1 + ycor[k];
w2 = w2 + ycor[k] * ycor[k];
}
w1 = w1 / *xlen;
w2 = sqrt(w2 / *xlen - w1 * w1);
for(k = 0; k < *xlen; k++) {
ycor[k] = (ycor[k] - w1) / w2;
}
/* Calculate new sum of products. */
cumsum = 0;
for(k = 0; k < *xlen; k++) {
cumsum += xcor[k] * ycor[k];
}
zstats[i] = cumsum / *xlen;
}
/* Reset random seed using an Splus function. */
RANDOUT;
}
void xbootstrap(double *x, double *y, int *n, int *xlen, int *nboot, double *pboot, double *bootcor, int *rarray, int *rmat, double *xdif, double *ydif)
{
int i, j, k;
double r;
double nsamp;
double xmean, ymean;
double xsum;
double xxsum, yysum;
S_EVALUATOR
/* Set random seed using Splus function */
RANDIN;
for(i = 0; i < *nboot; i++) {
/* Set up rarray. */
for(j = 0; j < *n; j++) {
r = UNIF;
if(r > *pboot)
rarray[j] = 0;
else rarray[j] = 1;
}
/* Turn rarray into a square sampling matrix. */
/* 1 means include, 0 means omit. */
for(j = 0; j < *xlen; j++) {
rmat[j] = 1;
}
for(j = 0; j < *n; j++) {
for(k = 0; k <= j; k++) {
if(rarray[j] == 0 || rarray[k] == 0) {
rmat[j * *n + k] = 0;
rmat[k * *n + j] = 0;
}
}
}
nsamp = 0;
for(j = 0; j < *xlen; j++) {
nsamp += rmat[j];
}
/* Calculate means for x and y. */
xmean = 0;
ymean = 0;
for(j = 0; j < *xlen; j++) {
if(rmat[j] == 1) {
xmean += x[j];
ymean += y[j];
}
}
xmean = xmean/nsamp;
ymean = ymean/nsamp;
/* Calculate deviations for x and y. */
for(j = 0; j < *xlen; j++) {
if(rmat[j] == 1) {
xdif[j] = x[j] - xmean;
ydif[j] = y[j] - ymean;
}
else {
xdif[j] = 0;
ydif[j] = 0;
}
}
xsum = 0;
xxsum = 0;
yysum = 0;
for(j = 0; j < *xlen; j++) {
if(rmat[j] == 1) {
xsum += (xdif[j] * ydif[j]);
xxsum += (xdif[j] * xdif[j]);
yysum += (ydif[j] * ydif[j]);
}
}
bootcor[i] = (xsum) / sqrt(xxsum * yysum);
}
/* Reset random seed using an Splus function. */
RANDOUT;
}
void xpermute(double *x, double *y, int *n, int *xlen, int *nperm,
double *zstats, double *tmat, int *rarray)
{
int i, k, l, m;
double cumsum;
int temp;
S_EVALUATOR
/* Set random seed using Splus function */
RANDIN;
/* Calculate first z-statistic (unpermuted data). */
cumsum = 0;
for(k = 0; k < *xlen; k++) {
cumsum += x[k] * y[k];
}
zstats[0] = cumsum;
/* Start permutation routine */
for(i = 1; i < *nperm; i++) {
/* Set up rarray. */
for(k = 0; k < *n; k++) {
rarray[k] = k;
}
/* Randomize rarray using an Splus function. */
for(k = 0; k < (*n - 1); k++) {
l = *n - k - 1;
m = (int)((float)l * UNIF);
if(m > l) m = l;
temp = rarray[l];
rarray[l] = rarray[m];
rarray[m] = temp;
}
/* Reorder x. */
for(k = 0; k < *n; k++) {
for(l = 0; l <= k; l++) {
x[k * *n + l] = tmat[rarray[k] * *n + rarray[l]];
x[l * *n + k] = tmat[rarray[l] * *n + rarray[k]];
}
}
/* Calculate new sum of products. */
cumsum = 0;
for(k = 0; k < *xlen; k++) {
cumsum += x[k] * y[k];
}
zstats[i] = cumsum;
}
/* Reset random seed using an Splus function. */
RANDOUT;
}
void xpermpart(double *hmat, double *y, double *xcor, double *ycor, int *n, int *xlen, int *nperm, double *zstats, double *tmat, int *rarray)
{
int i, k, l, m;
double cumsum;
int temp;
S_EVALUATOR
/* Set random seed using Splus function */
RANDIN;
/* Calculate residuals for y */
for(k = 0; k < *xlen; k++) {
ycor[k] = 0;
}
for(k = 0; k < *xlen; k++) {
for(l = 0; l < *xlen; l++) {
ycor[k] = ycor[k] + hmat[k * *xlen + l] * y[l];
}
}
/* Calculate first z-statistic (unpermuted data). */
cumsum = 0;
for(k = 0; k < *xlen; k++) {
cumsum += xcor[k] * ycor[k];
}
zstats[0] = cumsum;
/* Start permutation routine */
for(i = 1; i < *nperm; i++) {
/* Set up rarray. */
for(k = 0; k < *n; k++) {
rarray[k] = k;
}
/* Randomize rarray using an Splus function. */
for(k = 0; k < (*n - 1); k++) {
l = *n - k - 1;
m = (int)((float)l * UNIF);
if(m > l) m = l;
temp = rarray[l];
rarray[l] = rarray[m];
rarray[m] = temp;
}
/* Reorder y. */
for(k = 0; k < *n; k++) {
for(l = 0; l <= k; l++) {
y[k * *n + l] = tmat[rarray[k] * *n + rarray[l]];
y[l * *n + k] = tmat[rarray[l] * *n + rarray[k]];
}
}
/* Calculate residuals for y */
for(k = 0; k < *xlen; k++) {
ycor[k] = 0;
}
for(k = 0; k < *xlen; k++) {
for(l = 0; l < *xlen; l++) {
ycor[k] = ycor[k] + hmat[k * *xlen + l] * y[l];
}
}
/* Calculate new sum of products. */
cumsum = 0;
for(k = 0; k < *xlen; k++) {
cumsum += xcor[k] * ycor[k];
}
zstats[i] = cumsum;
}
/* Reset random seed using an Splus function. */
RANDOUT;
}
void bcdist(double *x, int *pnrow, int *pncol, double *dist)
{
int i, j, k, l;
int nrow, ncol;
double sumi, sumj;
double minsum;
l = 0;
nrow = *pnrow;
ncol = *pncol;
for(i = 0; i < (nrow - 1); i++) {
for(j = (i + 1); j < (nrow); j++) {
minsum = 0;
sumi = 0;
sumj = 0;
for(k = 0; k < ncol; k++) {
if(x[i * ncol + k] < x[j * ncol + k])
minsum += x[i * ncol + k];
else
minsum += x[j * ncol + k];
sumi += x[i * ncol + k];
sumj += x[j * ncol + k];
}
if((sumi + sumj) == 0)
dist[l] = 0;
else
dist[l] = (1 - (2 * minsum) / (sumi + sumj));
l++;
}
}
}
void weight(int *n, double *datadist, double *d1, double *d2, double *w)
{
int i;
double m1, m2;
double w1, w2;
double pi;
pi = 2 * acos(0);
for(i = 0; i < *n * *n; i++) {
if(datadist[i] != 0) {
if(d1[i] < datadist[i])
m1 = d1[i] / datadist[i];
else m1 = 1;
if(d2[i] < datadist[i])
m2 = d2[i] / datadist[i];
else m2 = 1;
}
else {
m1 = 0;
m2 = 0;
}
w1 = 1 - (acos(m1) + acos(m2)) / pi;
if(datadist[i] != 0) {
m1 = d1[i] / datadist[i];
if(m1 > 1)
m1 = 1;
m2 = d2[i] / datadist[i];
if(m2 > 1)
m2 = 1;
}
else {
m1 = 0;
m2 = 0;
}
w2 = 0.75 - (acos(m1) + acos(m2)) / (2 * pi);
if((datadist[i] * datadist[i]) >= (d1[i] * d1[i] + d2[i] * d2[i]))
w1 = 0;
if((datadist[i] * datadist[i]) < (d1[i] * d1[i] + d2[i] * d2[i]))
w2 = 0;
w[i] = w1 + w2;
}
}
void newpermone(double *x, int *dclass, int *n, int *xlen, int *nperm, double *zstats, double *tmat, int *rarray)
{
int i, k, l, m;
double cumsum;
int temp;
S_EVALUATOR
/* Set random seed using Splus function */
RANDIN;
/* Calculate first z-statistic (unpermuted data). */
cumsum = 0;
for(k = 0; k < *xlen; k++) {
if(dclass[k] == 0) {
cumsum += x[k];
}
}
zstats[0] = cumsum;
/* Start permutation routine */
for(i = 1; i < *nperm; i++) {
/* Set up rarray. */
for(k = 0; k < *n; k++) {
rarray[k] = k;
}
/* Convert x to a full matrix. */
m = 0;
for(k = 1; k < *n; k++) {
for(l = 0; l < k; l++) {
tmat[k * *n + l] = x[m];
tmat[l * *n + k] = x[m];
m++;
}
}
/* Randomize rarray using an Splus function. */
for(k = 0; k < (*n - 1); k++) {
l = *n - k - 1;
m = (int)((float)l * UNIF);
if(m > l) m = l;
temp = rarray[l];
rarray[l] = rarray[m];
rarray[m] = temp;
}
/* Reorder x. */
m = 0;
for(k = 1; k < *n; k++) {
for(l = 0; l < k; l++) {
x[m] = tmat[rarray[k] * *n + rarray[l]];
m++;
}
}
/* Calculate new sum of products. */
cumsum = 0;
for(k = 0; k < *xlen; k++) {
if(dclass[k] == 0) {
cumsum += x[k];
}
}
zstats[i] = cumsum;
}
/* Reset random seed using an Splus function. */
RANDOUT;
}
void newpermtwo(double *x, double *y, int *n, int *xlen, int *nperm, double *zstats, double *tmat, int *rarray)
{
int i, k, l, m;
double cumsum;
int temp;
float naval = -9999;
S_EVALUATOR
/* Set random seed using Splus function */
RANDIN;
/* Calculate first z-statistic (unpermuted data). */
cumsum = 0;
for(k = 0; k < *xlen; k++) {
if(x[k] != naval) {
cumsum += x[k] * y[k];
}
}
zstats[0] = cumsum;
/* Start permutation routine */
for(i = 1; i < *nperm; i++) {
/* Set up rarray. */
for(k = 0; k < *n; k++) {
rarray[k] = k;
}
/* Convert x to a full matrix. */
m = 0;
for(k = 1; k < *n; k++) {
for(l = 0; l < k; l++) {
tmat[k * *n + l] = x[m];
tmat[l * *n + k] = x[m];
m++;
}
}
/* Randomize rarray using an Splus function. */
for(k = 0; k < (*n - 1); k++) {
l = *n - k - 1;
m = (int)((float)l * UNIF);
if(m > l) m = l;
temp = rarray[l];
rarray[l] = rarray[m];
rarray[m] = temp;
}
/* Reorder x. */
m = 0;
for(k = 1; k < *n; k++) {
for(l = 0; l < k; l++) {
x[m] = tmat[rarray[k] * *n + rarray[l]];
m++;
}
}
/* Calculate new sum of products. */
cumsum = 0;
for(k = 0; k < *xlen; k++) {
if(x[k] != naval) {
cumsum += x[k] * y[k];
}
}
zstats[i] = cumsum;
}
/* Reset random seed using an Splus function. */
RANDOUT;
}
void psum(double *x, int *pnrow, int *pncol, double *dist)
{
int row1, row2, col1;
int nrow, ncol;
int l;
double thisval, thatval;
l = 0;
nrow = *pnrow;
ncol = *pncol;
for(col1 = 0; col1 < ncol; col1++) {
for(row1 = 0; row1 < nrow; row1++) {
thatval = x[row1 * ncol + col1];
for(row2 = 0; row2 < nrow; row2++) {
thisval = x[row2 * ncol + col1];
dist[l] = thisval + thatval;
l++;
}
}
}
}
void pdiff(double *x, int *pnrow, int *pncol, double *dist)
{
int row1, row2, col1;
int nrow, ncol;
int l;
double thisval, thatval;
l = 0;
nrow = *pnrow;
ncol = *pncol;
for(col1 = 0; col1 < ncol; col1++) {
for(row1 = 0; row1 < nrow; row1++) {
thatval = x[row1 * ncol + col1];
for(row2 = 0; row2 < nrow; row2++) {
thisval = x[row2 * ncol + col1];
dist[l] = thisval - thatval;
l++;
}
}
}
}
void jpres(double *x, int *pnrow, int *pncol, double *dist)
{
int row1, row2, col1;
int nrow, ncol;
int l;
double thisval, thatval;
l = 0;
nrow = *pnrow;
ncol = *pncol;
for(col1 = 0; col1 < ncol; col1++) {
for(row1 = 0; row1 < nrow; row1++) {
thatval = x[row1 * ncol + col1];
for(row2 = 0; row2 < nrow; row2++) {
thisval = x[row2 * ncol + col1];
if((thisval > 0) & (thatval > 0)) {
dist[l] = 1;
}
else {
dist[l] = 0;
}
l++;
}
}
}
}
void jabs(double *x, int *pnrow, int *pncol, double *dist)
{
int row1, row2, col1;
int nrow, ncol;
int l;
double thisval, thatval;
l = 0;
nrow = *pnrow;
ncol = *pncol;
for(col1 = 0; col1 < ncol; col1++) {
for(row1 = 0; row1 < nrow; row1++) {
thatval = x[row1 * ncol + col1];
for(row2 = 0; row2 < nrow; row2++) {
thisval = x[row2 * ncol + col1];
if((thisval == 0) & (thatval == 0)) {
dist[l] = 1;
}
else {
dist[l] = 0;
}
l++;
}
}
}
}
void jfirst(double *x, int *pnrow, int *pncol, double *dist)
{
int row1, row2, col1;
int nrow, ncol;
int l;
double thisval, thatval;
l = 0;
nrow = *pnrow;
ncol = *pncol;
for(col1 = 0; col1 < ncol; col1++) {
for(row1 = 0; row1 < nrow; row1++) {
thatval = x[row1 * ncol + col1];
for(row2 = 0; row2 < nrow; row2++) {
thisval = x[row2 * ncol + col1];
if((thisval > 0) & (thatval == 0)) {
dist[l] = 1;
}
else {
dist[l] = 0;
}
l++;
}
}
}
}
void jsec(double *x, int *pnrow, int *pncol, double *dist)
{
int row1, row2, col1;
int nrow, ncol;
int l;
double thisval, thatval;
l = 0;
nrow = *pnrow;
ncol = *pncol;
for(col1 = 0; col1 < ncol; col1++) {
for(row1 = 0; row1 < nrow; row1++) {
thatval = x[row1 * ncol + col1];
for(row2 = 0; row2 < nrow; row2++) {
thisval = x[row2 * ncol + col1];
if((thisval == 0) & (thatval > 0)) {
dist[l] = 1;
}
else {
dist[l] = 0;
}
l++;
}
}
}
}
void mrmperm(double *x, double *y, int *p, int *nd, int *n, int *nperm, double *r2all, double *ball, double *fall, double *tmat, int *rarray, double *XX, double *XY, double *YY, double *b)
{
int i, k, l;
int m;
int temp;
double SSE=0.0, SSTO=0.0, SSR=0.0;
double r2=0, f=0;
double btemp=0.0;
int bcount = 0;
char *transt = "T", *transn = "N";
double one = 1.0, zero = 0.0;
int onei = 1;
S_EVALUATOR
/* Set random seed using Splus function */
RANDIN;
/* Start permutation routine */
for(i = 0; i < *nperm; i++) {
/* first do the unpermuted values */
/* F77_CALL(dgemm)(transa, transb, &ncx, &ncy, &nrx, &one,
x, &nrx, y, &nry, &zero, z, &ncx); */
/* take crossproduct t(X) %*% Y - WORKS */
F77_CALL(dgemm)(transt, transn,
p, &onei, nd,
&one, x, nd, y, nd,
&zero, XY, p);
/* take crossproduct t(Y) %*% (Y) - WORKS */
F77_CALL(dgemm)(transt, transn,
&onei, &onei, nd,
&one, y, nd, y, nd,
&zero, YY, &onei);
/* calculate regression coefficients XX %*% XY - WORKS */
F77_CALL(dgemm)(transn, transn,
p, &onei, p,
&one, XX, p, XY, p,
&zero, b, p);
/* calculate regression components - WORKS */
F77_CALL(dgemm)(transt, transn,
&onei, &onei, p,
&one, b, p, XY, p,
&zero, &btemp, &onei);
/* SSE - WORKS */
SSE = YY[0] - btemp;
/* SSTO - WORKS */
SSTO = 0;
for(k = 0; k < *nd; k++) {
SSTO = SSTO + y[k];
}
SSTO = YY[0] - (SSTO * SSTO) / *nd;
SSR = SSTO - SSE;
/* calculate R2 - WORKS */
r2 = 1 - SSE / SSTO;
/* calculate F* - WORKS */
f = (SSR / (*p - 1)) / (SSE / (*nd - *p));
r2all[i] = r2;
fall[i] = f;
/* calculate pseudo-t for regression coefficients - WORKS*/
/* b / sqrt(1 - R2) */
for(k=0; k<*p; k++) {
ball[bcount] = b[k] / sqrt(1 - r2);
bcount++;
}
/* permute Y */
/* Set up rarray. */
for(k = 0; k < *n; k++) {
rarray[k] = k;
}
/* Convert y to a full matrix. */
m = 0;
for(k = 1; k < *n; k++) {
for(l = 0; l < k; l++) {
tmat[k * *n + l] = y[m];
tmat[l * *n + k] = y[m];
m++;
}
}
/* Randomize rarray using an Splus function. */
for(k = 0; k < (*n - 1); k++) {
l = *n - k - 1;
m = (int)((float)l * UNIF);
if(m > l) m = l;
temp = rarray[l];
rarray[l] = rarray[m];
rarray[m] = temp;
}
/* Reorder y. */
m = 0;
for(k = 1; k < *n; k++) {
for(l = 0; l < k; l++) {
y[m] = tmat[rarray[k] * *n + rarray[l]];
m++;
}
}
}
/* Reset random seed using an Splus function. */
RANDOUT;
}
fAssets/src/energy.c 0000644 0001760 0000144 00000041146 12254131720 014141 0 ustar ripley users
/*
energy.c: energy package
Author: Maria Rizzo
Created: 4 Jan 2004 for R-1.8.1
Revised: 20 March 2004 (E2, twosampleIEtest added)
Revised: 13 June 2004 (distance() changed, some utilities added)
mvnEstat() computes the E-test of multivariate normality
ksampleEtest() performs the multivariate E-test for equal distributions,
complete version, from data matrix
twosampleIEtest() incomplete version
E2sample() computes the 2-sample E-statistic without creating distance
poisMstat() computes the mean distance test of Poissonity
sumdist() sums the distance matrix without creating the matrix
*/
#include
#include
void mvnEstat(double *y, int *byrow, int *nobs, int *dim, double *stat);
void poisMstat(int *x, int *nx, double *stat);
void ksampleEtest(double *x, int *byrow, int *nsamples, int *sizes, int *dim,
int *R, double *e0, double *e, double *pval);
void twosampleIEtest(double *x, int *byrow, int *sizes, int *dim, int *iN,
int *R, double *e0, double *e, double *pval);
void E2sample(double *x, int *sizes, int *dim, double *stat);
double edist(double **D, int m, int n);
double multisampleE(double **D, int nsamples, int *sizes, int *perm);
double twosampleE(double **D, int m, int n, int *xrows, int *yrows);
double E2(double **x, int *sizes, int *start, int ncol, int *perm);
double Eksample(double *x, int *byrow, int r, int d, int K, int *sizes, int *ix);
void distance(double **bxy, double **D, int N, int d);
void sumdist(double *x, int *byrow, int *nrow, int *ncol, double *lowersum);
double **alloc_matrix(int r, int c);
int **alloc_int_matrix(int r, int c);
void free_matrix(double **matrix, int r, int c);
void free_int_matrix(int **matrix, int r, int c);
void permute(int *J, int n);
void roworder(double *x, int *byrow, int r, int c);
void vector2matrix(double *x, double **y, int N, int d, int isroworder);
void mvnEstat(double *y, int *byrow, int *nobs, int *dim, double *stat)
{
/*
compute E test statistic for multivariate normality
y is *standardized* multivariate sample
best to have y in row order: e.g. y=as.double(t(y))
*/
int d=(*dim), n=(*nobs);
int i, j, k, p, maxterms=2000;
double D=(double)(*dim);
double meanyy, meanyz, meanzz;
double delta, eps=1.0e-7;
double normy, yy, dif, sum, sum0, term;
double lg0, lg1,logak, loggk;
if (*byrow == FALSE)
roworder(y, byrow, n, d);
lg0 = lgammafn(D/2.0);
lg1 = lgammafn((D+1.0)/2.0);
meanzz = 2.0 * exp(lg1 - lg0); /* second mean */
meanyz = 0.0; /* computing the first mean as series */
for (i=0; i eps && k < maxterms) {
sum0 = sum;
logak = (k+1)*log(yy) - lgammafn(k+1) - k*M_LN2 -
log(2*k+1) - log(2*k+2);
loggk = lg1 + lgammafn(k+1.5) - lgammafn(k+D/2+1);
term = exp(logak + loggk);
if (k % 2 == 0)
sum += term;
else
sum -= term;
delta = fabs(sum - sum0);
k++;
}
if (delta < eps)
meanyz += meanzz/M_SQRT2 + M_SQRT_2dPI * sum;
else {
meanyz += normy;
Rf_warning("E|y-Z| did not converge, replaced by %f", normy);
}
}
meanyz /= (double) n;
sumdist(y, byrow, nobs, dim, &meanyy); /* computing third mean */
meanyy *= (2.0/(double)(n*n));
*stat = ((double) n)*(2.0*meanyz - meanzz - meanyy);
return;
}
void poisMstat(int *x, int *nx, double *stat)
{
/* computes the Poisson mean distance statistic */
int i, j, k, n=(*nx);
double eps=1.0e-10;
double cvm, d, lambda, m, q;
double Mcdf1, Mcdf0, Mpdf1, cdf1, cdf0;
lambda = 0;
for (i=0; i 1) Mcdf1 = 1.0;
cdf1 = ppois(i, lambda, TRUE, FALSE); /* MLE of F(i) */
d = Mcdf1 - cdf1;
cvm += d * d * (cdf1 - cdf0);
cdf0 = cdf1;
Mcdf0 = Mcdf1;
}
cvm *= n;
*stat = cvm;
}
void E2sample(double *x, int *sizes, int *dim, double *stat) {
/*
compute test statistic *stat for testing H:F=G
does not store distance matrix
x must be in row order: x=as.double(t(x)) where
x is pooled sample in matrix sum(en) by dim
*/
int m=sizes[0], n=sizes[1], d=(*dim);
int i, j, k, p, q;
double dif, dsum, sumxx, sumxy, sumyy, w;
sumxy = 0.0;
for (i=0; i 0) {
data = alloc_matrix(N, d); /* sample matrix */
vector2matrix(x, data, N, d, *byrow);
distance(data, D, N, d);
free_matrix(data, N, d);
}
else
vector2matrix(x, D, N, N, *byrow);
*e0 = multisampleE(D, K, sizes, perm);
/* bootstrap */
if (B > 0) {
ek = 0;
GetRNGstate();
for (b=0; b N ? N : sizes[0];
I[1] = sizes[1] > N ? N : sizes[1];
if (*byrow == FALSE)
roworder(x, byrow, nrow, ncol);
data = alloc_matrix(nrow, ncol);
vector2matrix(x, data, nrow, ncol, *byrow);
perm = Calloc(nrow, int);
for (i=0; i 0) {
ek = 0;
for (b = 0; b < B; b++) {
permute(perm, nrow);
e[b] = E2(data, I, start, ncol, perm);
if ((*e0) < e[b]) ek++;
}
*pval = (double) ek / (double) B;
}
Free(data);
Free(perm);
return;
}
void sumdist(double *x, int *byrow, int *nrow, int *ncol, double *lowersum)
{
/*
sum all pairwise distances between rows of x
equivalent to this in R: h <- sum(dist(x))
x must be in row order: x=as.double(t(x))
*/
int i, j, k, p, q, n=(*nrow), d=(*ncol);
double sum, dsum, dif;
if (*byrow == FALSE)
roworder(x, byrow, n, d);
sum = 0.0;
for (i=1; i