Title: | R Commander Plug-in for Risk Demonstration |
---|---|
Description: | R Commander plug-in to demonstrate various actuarial and financial risks. It includes valuation of bonds and stocks, portfolio optimization, classical ruin theory, demography and epidemic. |
Authors: | Arto Luoma |
Maintainer: | Arto Luoma <[email protected]> |
License: | GPL-2 |
Version: | 3.2 |
Built: | 2024-11-03 04:52:29 UTC |
Source: | https://github.com/cran/RcmdrPlugin.RiskDemo |
R Commander plug-in to demonstrate various actuarial and financial risks. It includes valuation of bonds and stocks, portfolio optimization, classical ruin theory, demography and epidemic.
Package: | RcmdrPlugin.RiskDemo |
Type: | Package |
Version: | 3.0 |
Date: | 2021-04-03 |
License: | GPL (>= 2) |
LazyLoad: | yes |
Arto Luoma
Maintainer: Arto Luoma <[email protected]>
This function draws forward and yields curves, for AAA-rated central governement bonds and/or all central governement bonds.
bondCurve(date1, date2 = NULL, yield = TRUE, forward = TRUE, AAA = TRUE, all = TRUE, params)
bondCurve(date1, date2 = NULL, yield = TRUE, forward = TRUE, AAA = TRUE, all = TRUE, params)
date1 |
The date for which the curves are drawn |
date2 |
Optional second date for which the curves are drawn |
yield |
Is the yield curve shown (TRUE/FALSE)? |
forward |
Is the forward curve shown (TRUE/FALSE)? |
AAA |
Are the curves drawn for the AAA-rated bonds (TRUE/FALSE)? |
all |
Are the curves drawn for the bonds with all ratings (TRUE/FALSE)? |
params |
The data frame of curve parameters |
No value. Only a figure is produced.
Arto Luoma
https://bit.ly/2zfs0G8
data(params) bondCurve(as.Date("2004-09-06"),params=params)
data(params) bondCurve(as.Date("2004-09-06"),params=params)
This function plots the bond price as a function of interest rate. It also shows, using dotted lines, the yield to maturity rate corresponding to the face value, and the flat price corresponding to the yield to maturity.
bondFigure(buyDate, matDate, rateCoupon, yieldToMat = NULL, bondPr = NULL, nPay)
bondFigure(buyDate, matDate, rateCoupon, yieldToMat = NULL, bondPr = NULL, nPay)
buyDate |
the date when the coupon is bought (settlement date) |
matDate |
maturity date |
rateCoupon |
coupon rate (in decimals) |
yieldToMat |
yield to maturity (in decimals) |
bondPr |
the flat price of the bond |
nPay |
number of coupon payments per year |
either yieldToMat or bondPr should be given as input.
This function only plots a figure.
Arto Luoma <[email protected]>
Bodie, Kane, and Marcus (2014) Investments, 10th Global Edition, McGraw-Hill Education, (see Section 14.2 Bond Pricing).
bondFigure("2012-7-31","2018-7-31",rateCoupon=0.0225,yieldToMat=0.0079, nPay=2) bondFigure("2012-7-31","2018-7-31",rateCoupon=0.0225,bondPr=90,nPay=2)
bondFigure("2012-7-31","2018-7-31",rateCoupon=0.0225,yieldToMat=0.0079, nPay=2) bondFigure("2012-7-31","2018-7-31",rateCoupon=0.0225,bondPr=90,nPay=2)
This function computes the bond price, given the yield to maturity.
bondPrice(buyDate, matDate, rateCoupon, yieldToMat, nPay)
bondPrice(buyDate, matDate, rateCoupon, yieldToMat, nPay)
buyDate |
the date at which the bond is bought (settlement date). |
matDate |
maturity date |
rateCoupon |
annual coupon date |
yieldToMat |
yield to maturity |
nPay |
number of coupon payments per day |
All the rates are given in decimals.
A list with the following components:
yieldToMaturity |
yield to maturity |
flatPrice |
flat price |
daysSinceLastCoupon |
days since previous coupon payment |
daysInCouponPeriod |
days in a coupon period |
accruedInterest |
accrued interest since last coupon payment |
invoicePrice |
invoice price (= flat price + accrued interest) |
With Excel functions PRICE, DATE, COUPDAYBS and COUPDAYS you can do the same.
Arto Luoma <[email protected]>
Bodie, Kane, and Marcus (2014) Investments, 10th Global Edition, McGraw-Hill Education, (see Bond Pricing between Coupon Dates in Section 14.2).
bondPrice("2012-7-31","2018-7-31",0.0225,0.0079,2) bondPrice("2012-7-31","2018-7-31",0.0225,0.0079,4) bondPrice("2012-7-31","2030-5-15",0.0625,0.02117,2)
bondPrice("2012-7-31","2018-7-31",0.0225,0.0079,2) bondPrice("2012-7-31","2018-7-31",0.0225,0.0079,4) bondPrice("2012-7-31","2030-5-15",0.0625,0.02117,2)
This function uses classical ruin theory to compute either ruin probability, safety loading or initial capital, given two of them. The time horizon is infinite. Gamma distribution is used to model claim sizes.
computeRuin(U0 = NULL, theta = NULL, eps = NULL, alpha, beta)
computeRuin(U0 = NULL, theta = NULL, eps = NULL, alpha, beta)
U0 |
initial capital |
theta |
safety loading |
eps |
ruin probability |
alpha |
shape parameter of gamma distribution |
beta |
rate parameter of gamma distribution |
The value is a list with the following components:
LundbergExp |
Lundberg's exponent R |
initialCapital |
initial capital |
safetyLoading |
safety loading |
ruinProb |
ruin probability |
Arto Luoma <[email protected]>
Gray and Pitts (2012) Risk Modelling in General Insurance: From Principles to Practice, Cambridge University Press.
computeRuin(U0=1000,theta=0.01,alpha=1,beta=0.1) computeRuin(eps=0.005,theta=0.01,alpha=1,beta=0.1) computeRuin(U0=5399.24,eps=0.005,alpha=1,beta=0.1)
computeRuin(U0=1000,theta=0.01,alpha=1,beta=0.1) computeRuin(eps=0.005,theta=0.01,alpha=1,beta=0.1) computeRuin(U0=5399.24,eps=0.005,alpha=1,beta=0.1)
This function uses classical ruin theory to compute either ruin probability, safety loading or initial capital, given two of them. The time horizon is finite. Gamma distribution is used to model claim sizes.
computeRuinFinite(T0, U0 = NULL, theta = NULL, eps = NULL, lambda, alpha, beta)
computeRuinFinite(T0, U0 = NULL, theta = NULL, eps = NULL, lambda, alpha, beta)
T0 |
time horizon (in years) |
U0 |
initial capital |
theta |
safety loading |
eps |
ruin probability |
lambda |
claim intensity (mean number of claims per year) |
alpha |
shape parameter of gamma distribution |
beta |
rate parameter of gamma distribution |
The value is a list with the following components:
LundbergExp |
Lundberg's exponent R |
initialCapital |
initial capital |
safetyLoading |
safety loading |
ruinProb |
ruin probability |
Arto Luoma <[email protected]>
computeRuinFinite(T0=100,U0=1000,theta=0.01,lambda=100,alpha=1,beta=0.1) computeRuinFinite(T0=1,eps=0.005,theta=0.001,lambda=100,alpha=1,beta=0.1) computeRuinFinite(T0=500,U0=5347,eps=0.005,lambda=100,alpha=1,beta=0.1)
computeRuinFinite(T0=100,U0=1000,theta=0.01,lambda=100,alpha=1,beta=0.1) computeRuinFinite(T0=1,eps=0.005,theta=0.001,lambda=100,alpha=1,beta=0.1) computeRuinFinite(T0=500,U0=5347,eps=0.005,lambda=100,alpha=1,beta=0.1)
Mortality data for 10 countries (period death rates and exposures) retrieved from Human Mortality Database. The data are rounded to three significant digits and include the Nordic countries, China, U.S., Russia, Japan and Germany.
data("countries.mort")
data("countries.mort")
List of objects of class demogdata.
HMD. Human Mortality Database. Max Planck Institute for Demographic Research (Germany), University of California, Berkeley (USA), and French Institute for Demographic Studies (France). Available at www.mortality.org. (Data downloaded Nov 13, 2023.)
data(countries.mort) plot(countries.mort[[1]])
data(countries.mort) plot(countries.mort[[1]])
This function does Kalman smoothing for the simple model that is used to predict new COVID-19 cases.
covidSmooth(par, y)
covidSmooth(par, y)
par |
Logarithms of the variance parameters of drift, seasonal component, and error term |
y |
Univariate numeric time series of new COVID-19 cases |
See loglikCovid.
Xif |
Matrix of filtered values, where the state vectors are given as rows |
Xis |
Matrix of smoothed values, where the state vectors are given as rows |
Pmat |
Array of state uncertainty matrices, evaluated at time t-1. The first array index is for time. |
Pfmat |
Array of state uncertainty matrices, evaluated at time t. The first array index is for time. |
Psmat |
Array of state uncertainty matrices, evaluated at time n, where n is the number of observations. The first array index is for time. |
Arto Luoma
#Preparing a time series library(zoo) data(dataCovidFin) timeindex <- dataCovidFin[dataCovidFin$Alue=="Kaikki Alueet","Aika"] series <- dataCovidFin[dataCovidFin$Alue=="Kaikki Alueet","val"] series <- window(zoo(series,order.by=timeindex),start="2020-03-01", end="2021-03-01") #Fitting a state space model and smoothing the components p0 <- c(-9,-7,-3.3) fit <- nlm(loglikCovid,p=p0,y=series) out <- covidSmooth(fit$estimate,y=series) #Plotting the filtered and smoothed components smoothed <- zoo(out$Xis[,1:3],order.by=time(series)) filtered <- zoo(out$Xif[,1:3],order.by=time(series)) colnames(smoothed) <- colnames(filtered) <- c("Level","Drift","Seasonal") plot(filtered,xlab="Time",main="Filtered components of the time series") plot(smoothed,xlab="Time",main="Smoothed components of the time series") #Plotting the original time series, and the filtered and smoothed local level #series after transforming them to original scale plot(series,xlab="Time",ylab="Time series") lines(exp(filtered[,1])-2,col=3) lines(exp(smoothed[,1])-2,col=2) legend("topleft",c("original","filtered","smoothed"),col=c(1,3,2),lty=1)
#Preparing a time series library(zoo) data(dataCovidFin) timeindex <- dataCovidFin[dataCovidFin$Alue=="Kaikki Alueet","Aika"] series <- dataCovidFin[dataCovidFin$Alue=="Kaikki Alueet","val"] series <- window(zoo(series,order.by=timeindex),start="2020-03-01", end="2021-03-01") #Fitting a state space model and smoothing the components p0 <- c(-9,-7,-3.3) fit <- nlm(loglikCovid,p=p0,y=series) out <- covidSmooth(fit$estimate,y=series) #Plotting the filtered and smoothed components smoothed <- zoo(out$Xis[,1:3],order.by=time(series)) filtered <- zoo(out$Xif[,1:3],order.by=time(series)) colnames(smoothed) <- colnames(filtered) <- c("Level","Drift","Seasonal") plot(filtered,xlab="Time",main="Filtered components of the time series") plot(smoothed,xlab="Time",main="Smoothed components of the time series") #Plotting the original time series, and the filtered and smoothed local level #series after transforming them to original scale plot(series,xlab="Time",ylab="Time series") lines(exp(filtered[,1])-2,col=3) lines(exp(smoothed[,1])-2,col=2) legend("topleft",c("original","filtered","smoothed"),col=c(1,3,2),lty=1)
This data set consists of several statistics about the COVID-19 pandemic in 45 countries.
data("dataCovid")
data("dataCovid")
A data frame with 18400 observations on the following 27 variables.
location
a character vector
date
a Date
new_cases
a numeric vector
new_cases_per_million
a numeric vector
new_cases_smoothed_per_million
a numeric vector
new_cases_smoothed
a numeric vector
new_deaths_per_million
a numeric vector
new_deaths
a numeric vector
new_deaths_smoothed_per_million
a numeric vector
new_deaths_smoothed
a numeric vector
total_deaths_per_million
a numeric vector
total_deaths
a numeric vector
total_cases
a numeric vector
total_cases_per_million
a numeric vector
hosp_patients
a numeric vector
hosp_patients_per_million
a numeric vector
icu_patients_per_million
a numeric vector
icu_patients
a numeric vector
reproduction_rate
a numeric vector
new_tests
a numeric vector
new_tests_per_thousand
a numeric vector
tests_per_case
a numeric vector
positive_rate
a numeric vector
new_tests_smoothed
a numeric vector
new_tests_smoothed_per_thousand
a numeric vector
total_tests
a numeric vector
total_tests_per_thousand
a numeric vector
This is a subset of the complete data set available online, downloaded on March 31, 2021.
https://covid.ourworldindata.org/data/owid-covid-data.csv
library(zoo) data(dataCovid) casesFin <- subset(dataCovid,subset=location=="Finland", select=c(date,new_cases)) plot(zoo(casesFin$new_cases,order.by=casesFin$date),ylab="New COVID-19 cases in Finland", xlab="")
library(zoo) data(dataCovid) casesFin <- subset(dataCovid,subset=location=="Finland", select=c(date,new_cases)) plot(zoo(casesFin$new_cases,order.by=casesFin$date),ylab="New COVID-19 cases in Finland", xlab="")
This data set provides the confirmed COVID-19 cases in 21 Finnish hospital districts, in addition to the total number.
data("dataCovidFin")
data("dataCovidFin")
A data frame with 16082 observations on the following 3 variables.
Aika
Date
Alue
character vector: hospital district
val
numeric vector: number of new confirmed cases
The data were downloaded on March 31, 2021, via THL's open data API.
https://bit.ly/2PO1DnS
https://bit.ly/3ryfwE4
library(zoo) data(dataCovidFin) casesFin <- subset(dataCovidFin, subset = Alue=="Kaikki Alueet") plot(zoo(casesFin$val,order.by=casesFin$Aika),ylab="New COVID-19 cases in Finland",xlab="")
library(zoo) data(dataCovidFin) casesFin <- subset(dataCovidFin, subset = Alue=="Kaikki Alueet") plot(zoo(casesFin$val,order.by=casesFin$Aika),ylab="New COVID-19 cases in Finland",xlab="")
This function plots several epidemic statistics for selected countries.
drawBars(data, countries, start = "2020-06-01", end = "last", measure = "new_cases", atop = TRUE, perMillion = FALSE, drawMean = TRUE, bars = TRUE)
drawBars(data, countries, start = "2020-06-01", end = "last", measure = "new_cases", atop = TRUE, perMillion = FALSE, drawMean = TRUE, bars = TRUE)
data |
data frame similar to (or including the same columns as) |
countries |
vector of characters srings indicating the countries for which the selected statistic is plotted |
start |
beginning date of the time window for which the statistic is plotted |
end |
ending date of the time window for which the statistic is plotted |
measure |
statistic to be plotted |
atop |
logical indicating if the bars of different countries are plotted on top of one another |
perMillion |
logical indicating if the statistic is proportioned to a population of million |
drawMean |
logical indicating if a smoothed curve is drawn |
bars |
logical indicating if bars are plotted |
No value.
Arto Luoma <[email protected]>
data(dataCovid) drawBars(data=dataCovid, countries=c('Finland','France'),start='2020-6-1', measure='new_cases',perMillion=TRUE)
data(dataCovid) drawBars(data=dataCovid, countries=c('Finland','France'),start='2020-6-1', measure='new_cases',perMillion=TRUE)
This function plots the new cases or total cases of an epidemic for selected regions in Finland.
drawBarsFin(data, pop, regions, start = "2020-06-01", end = "last", measure = "new_cases", atop = TRUE, perMillion = FALSE, drawMean = TRUE, bars = TRUE)
drawBarsFin(data, pop, regions, start = "2020-06-01", end = "last", measure = "new_cases", atop = TRUE, perMillion = FALSE, drawMean = TRUE, bars = TRUE)
data |
data frame including columns |
pop |
data frame including columns |
regions |
vector of characters strings indicating the regions for which the selected statistic is plotted |
start |
beginning date of the time window for which the curve is plotted |
end |
ending date of the time window for which the curve is plotted |
measure |
statistic to be plotted |
atop |
logical indicating if the bars of different regions are plotted on top of one another |
perMillion |
logical indicating if the statistic is proportioned to a population of million |
drawMean |
logical indicating if a smoothed curve (rolling mean of 7 observations) is plotted |
bars |
logical indicating if bars are plotted |
No value.
Arto Luoma <[email protected]>
data(dataCovidFin) data(popRegionsFin) drawBarsFin(dataCovidFin,popRegionsFin,regions=popRegionsFin$Alue[1:7])
data(dataCovidFin) data(popRegionsFin) drawBarsFin(dataCovidFin,popRegionsFin,regions=popRegionsFin$Alue[1:7])
Plots the efficient frontiers of risky investments and all investments. The optimum points corresponding to the risk aversion coefficient are indicated by dots. Further, the function plots a predictive return distribution figure.
drawFigure(symbol, yield, vol, beta, r = 1, total = 1, indexVol = 20, nStocks = 7, balanceInt = 12, A = 10, riskfree = FALSE, bor = FALSE)
drawFigure(symbol, yield, vol, beta, r = 1, total = 1, indexVol = 20, nStocks = 7, balanceInt = 12, A = 10, riskfree = FALSE, bor = FALSE)
symbol |
character vector of the symbols of the risky investments |
yield |
vector of yields (%) |
vol |
vector of volatilities (%) |
beta |
vector of betas (%) |
r |
risk-free interest rate (%) |
total |
total investment (for example in euros) |
indexVol |
volatility of market portfolio (%) |
nStocks |
number of risky investments in the portfolio |
balanceInt |
balancing interval of the portfolio in months |
A |
risk aversion coefficient (see details) |
riskfree |
is risk-free investment included in the portfolio (logical) |
bor |
is borrowing (negative risk-free investment) allowed (logical) |
The function uses the single-index model and Markovitz portfolio optimization model to find the optimum risky portfolio. The returns are assumed to be log-normally distributed. The maximized function is mu - 0.5*A*var where mu is expected return, A is risk aversion coefficient, and var is return variance.
portfolio |
allocation of the total investment (in euros) |
returnExpectation |
expected portfolio return |
returnDeviation |
standard deviation of the portfolio |
Arto Luoma <[email protected]>
Bodie, Kane, and Marcus (2014) Investments, 10th Global Edition, McGraw-Hill Education, (see Section 7.4 The Markowitz Portfolio Optimization Model and Section 8.2 The Single-Index Model).
data(stockData, package="RcmdrPlugin.RiskDemo") with(stockData,drawFigure(symbol=rownames(stockData),yield=divYield, vol=vol,beta=beta,r=1,total=100,indexVol=10, nStocks=5,balanceInt=12,A=10,riskfree=TRUE,bor=FALSE))
data(stockData, package="RcmdrPlugin.RiskDemo") with(stockData,drawFigure(symbol=rownames(stockData),yield=divYield, vol=vol,beta=beta,r=1,total=100,indexVol=10, nStocks=5,balanceInt=12,A=10,riskfree=TRUE,bor=FALSE))
This function plots incidence curves of an epidemic for selected countries. The incidences are new cases per 100 000 inhabitants within one or two weeks.
drawIncidence(data, countries, start = "2020-06-01", end = "last", weeks = 2, log = TRUE)
drawIncidence(data, countries, start = "2020-06-01", end = "last", weeks = 2, log = TRUE)
data |
data frame including columns |
countries |
vector of characters srings indicating the countries for which the curves are plotted |
start |
beginning date of the time window for which the curve is plotted |
end |
ending date of the time window for which the curve is plotted |
weeks |
Integer telling how many weeks' observations are used to calculate the incidence. Usually 1 or 2. |
log |
logical indicating if a log scale is used in the plot |
No value
Arto Luoma <[email protected]>
data(dataCovid) Europe <- c("Germany","France","United Kingdom","Italy","Spain","Poland","Romania", "Netherlands","Belgium","Greece") drawIncidence(dataCovid,countries=Europe)
data(dataCovid) Europe <- c("Germany","France","United Kingdom","Italy","Spain","Poland","Romania", "Netherlands","Belgium","Greece") drawIncidence(dataCovid,countries=Europe)
This function plots incidence curves of an epidemic for selected regions of Finland. The incidences are new cases per 100 000 inhabitants within one or two weeks.
drawIncidenceFin(data, pop, regions, start = "2020-06-01", end = "last", weeks = 2, includeAllRegions = TRUE, log = TRUE)
drawIncidenceFin(data, pop, regions, start = "2020-06-01", end = "last", weeks = 2, includeAllRegions = TRUE, log = TRUE)
data |
data frame including columns |
pop |
data frame including columns |
regions |
vector of characters srings indicating the regions for which the curves are plotted |
start |
beginning date of the time window for which the curve is plotted |
end |
ending date of the time window for which the curve is plotted |
weeks |
Integer telling how many weeks' observations are used to calculate the incidence. Usually 1 or 2. |
includeAllRegions |
logical indicating if a curve for total incidence is included |
log |
logical indicating if a log scale is used in the plot |
No value
Arto Luoma <[email protected]>
data(dataCovidFin) data(popRegionsFin) drawIncidenceFin(data = dataCovidFin, pop = popRegionsFin, regions = popRegionsFin$Alue[1:5], start = "2020-06-01", end="last", weeks=2, includeAllRegions = TRUE)
data(dataCovidFin) data(popRegionsFin) drawIncidenceFin(data = dataCovidFin, pop = popRegionsFin, regions = popRegionsFin$Alue[1:5], start = "2020-06-01", end="last", weeks=2, includeAllRegions = TRUE)
This function plots a time series of either the positive rate of COVID-19 tests or the number of tests per case.
drawPositiveRate(data, countries, start = "2020-06-01", end = "last", measure = "positive_rate", curve = TRUE, bars = FALSE, log = FALSE)
drawPositiveRate(data, countries, start = "2020-06-01", end = "last", measure = "positive_rate", curve = TRUE, bars = FALSE, log = FALSE)
data |
data frame including columns |
countries |
vector of characters srings indicating the countries for which the selected statistic is plotted |
start |
beginning date of the time window for which the time series are plotted |
end |
ending date of the time window for which the time series are plotted |
measure |
statistic for which the time series are plotted |
curve |
logical indicating if smoothed curves are drawn |
bars |
logical indicating if bars are plotted |
log |
logical indicating if a log scale is used in the plot |
No value.
Arto Luoma <[email protected]>
data(dataCovid) drawPositiveRate(dataCovid,countries=c("Finland","France"))
data(dataCovid) drawPositiveRate(dataCovid,countries=c("Finland","France"))
This function plots simulation paths of a surpluss process. The claims are assumed to arrive according to a Poisson process and the claim sizes are assumed to be gamma distributed.
drawRuin(nsim = 10, Tup = 10, U0 = 1000, theta = 0.01, lambda = 100, alpha = 1, beta = 0.1)
drawRuin(nsim = 10, Tup = 10, U0 = 1000, theta = 0.01, lambda = 100, alpha = 1, beta = 0.1)
nsim |
number of simulations |
Tup |
maximum value in the time axis |
U0 |
initial capital |
theta |
risk loading |
lambda |
intensity of claim process (mean number of claims per year) |
alpha |
shape parameter of gamma distribution |
beta |
rate parameter of gamma distribution |
No value; only a figure is plotted.
Arto Luoma <[email protected]>
Kaas, Goovaerts, Dhaene, Denuit (2008) Modern actuarial risk theory using R, 2nd ed., Springer.
computeRuinFinite(T0=10,U0=1000,eps=0.05,lambda=100,alpha=1,beta=0.1) drawRuin(nsim=10,Tup=10,U0=1000,theta=0.0125,lambda=100,alpha=1,beta=0.1)
computeRuinFinite(T0=10,U0=1000,eps=0.05,lambda=100,alpha=1,beta=0.1) drawRuin(nsim=10,Tup=10,U0=1000,theta=0.0125,lambda=100,alpha=1,beta=0.1)
This function plots time series of new and total COVID-19 tests, possibly in proportion to population.
drawTests(data, countries, start = "2020-06-01", end = "last", measure = "new_tests", atop = TRUE, perThousand = FALSE, drawMean = TRUE, bars = TRUE, log = FALSE)
drawTests(data, countries, start = "2020-06-01", end = "last", measure = "new_tests", atop = TRUE, perThousand = FALSE, drawMean = TRUE, bars = TRUE, log = FALSE)
data |
data frame similar to (or including the same columns as) |
countries |
vector of characters strings indicating the countries for which the time series are plotted |
start |
beginning date of the time window for which the time series are plotted |
end |
ending date of the time window for which the time series are plotted |
measure |
statistic for which the time series are plotted |
atop |
logical indicating if the bars of different countries are plotted on top of one another |
perThousand |
logical indicating if the statistic is proportioned to a population of thousand |
drawMean |
logical indicating if a smoothed curve is drawn |
bars |
logical indicating if bars are plotted |
log |
logical indicating if a log scale is used in the plot |
No value.
Arto Luoma <[email protected]>
data(dataCovid) drawTests(dataCovid,countries=c("Finland","France"),perThousand=TRUE)
data(dataCovid) drawTests(dataCovid,countries=c("Finland","France"),perThousand=TRUE)
Mortality data for Finland Series: female male total Years: 1878 - 2015 Ages: 0 - 110
data("fin")
data("fin")
object of class demogdata
This is part of the countries.mort data (countries.mort[[11]]).
HMD. Human Mortality Database. Max Planck Institute for Demographic Research (Germany), University of California, Berkeley (USA), and French Institute for Demographic Studies (France). Available at www.mortality.org. (Data downloaded Nov 13, 2023.)
data(fin) print(fin) plot(fin)
data(fin) print(fin) plot(fin)
Finnish mortality forecast 50 years ahead (2023-2072) for 0 - 100 years old. The forecast is based on an estimated Lee-Carter model. The kt coefficients were forecast using a random walk with drift. Fitted rates were used as the starting value.
data("fin.fcast")
data("fin.fcast")
An object of class "fmforecast"; for details, see documentation of package "demography".
The forecast was produced using function "forecast.lca" of package "demography".
data(fin.fcast) print(fin.fcast) plot(fin.fcast)
data(fin.fcast) print(fin.fcast) plot(fin.fcast)
Lee-Carter model fit obtained by function "lca" of package "demography". The fit is based on Finnish mortality data for ages from 0 to 100 and years from 1950 to 2022.
data("fin.lca")
data("fin.lca")
object of class "lca"
Both sexes were included in the input mortality data.
data(fin.lca) plot(fin.lca)
data(fin.lca) plot(fin.lca)
This function computes -2 times the log-likelihood of the simple model that is used to predict new COVID-19 cases and to estimate the effective reproduction number.
loglikCovid(y, par, it = TRUE)
loglikCovid(y, par, it = TRUE)
y |
Univariate numeric time series of new COVID-19 cases |
par |
Logarithms of the variance parameters of drift, seasonal component, and error term |
it |
A logical value indicating if only the log-likelihood is returned. |
Some multiplicative and additive constants are omitted when the negative log-likelihood is computed. Before computing the log-likelihood, the transformation y=log(x+a), where a=2, is applied to the time series. The model is a simple local linear model with local level, drift and seasonal component. The variance parameters of the level and seasonal component are estimated while the variance of the level component is computed as max(exp(xi[1]) - a, 0.1)/exp(xi[1])^2, where xi[1] is the current estimate of the level. This is based on the assumption that the number of new cases is approximately Poisson distributed, so that the variance equals the level. The max operation is taken in order to prevent the exression from being negative. In order to facilitate estimation, a penalty term is added which corresponds to a prior of N(-9,1) for the logarithm of the drift variance.
loglik |
-2 times the penalized log likelihood apart from some additive constants |
ll |
Vector of the increments of the log-likelihood corresponding to individual observations |
Xi |
Matrix of one-step predictions of the state vector. The vectors at different time points are given as rows. |
Xif |
Matrix of filtered values, where the state vectors are given as rows |
Pfmat |
Array of state uncertainty matrices, evaluated at time t. The first array index is for time. |
Q |
Covariance matrix of the error vector of the state equation |
Arto Luoma <[email protected]>
Hamilton (1994) Time Series Analysis, Princeton University Press, (see Chapter 13 The Kalman Filter).
#See examples for covidSmooth.
#See examples for covidSmooth.
Yield curve parameters from the European Central Bank (ECB), downloaded on Nov 4, 2023
data("params")
data("params")
A data frame with 4902 observations on the following 13 variables.
date
a Date
b0
a numeric vector
b1
a numeric vector
b2
a numeric vector
b3
a numeric vector
t1
a numeric vector
t2
a numeric vector
c0
a numeric vector
c1
a numeric vector
c2
a numeric vector
c3
a numeric vector
d1
a numeric vector
d2
a numeric vector
The parameters b0 to b3 are the beta-parameters, and t1 and t2 the tau-parameters for AAA-rated government bonds. The parameters c0 to c3 are the beta-parameters, and d1 and d2 the tau-parameters for all government bonds.
https://bit.ly/2zfs0G8
data(params) bondCurve(as.Date("2004-09-06"),params=params)
data(params) bondCurve(as.Date("2004-09-06"),params=params)
This function forecasts the numbers of new covid cases using a simple linear state space model.
plotForecast(data, region, start = NULL, end = NULL, np = 30, predInt = 0.95, log = TRUE)
plotForecast(data, region, start = NULL, end = NULL, np = 30, predInt = 0.95, log = TRUE)
data |
data frame including columns |
region |
characters string indicating the region for which the forecast is made |
start |
beginning date of the observations used in the estimation of the forecasting model |
end |
ending date of the observations used in the estimation of the forecasting model |
np |
integer indicating the forecasting horizon in days |
predInt |
decimal indicating the probability of the forecasting interval |
log |
logical indicating if a log scale is used in the plot |
No value.
Arto Luoma <[email protected]>
data(dataCovidFin) plotForecast(data=dataCovidFin, region='All regions', start="2020-09-01")
data(dataCovidFin) plotForecast(data=dataCovidFin, region='All regions', start="2020-09-01")
This function plots a time series of the effective reproduction number R and its confidence interval.
plotR(data, region, start = NULL, end = NULL, confInt = 0.95)
plotR(data, region, start = NULL, end = NULL, confInt = 0.95)
data |
data frame including columns |
region |
characters string indicating the region for which the R series is computed |
start |
beginning date of the time window for which the R is computed |
end |
ending date of the time window for which the R is computed |
confInt |
decimal between 0 and 1, indicating the level of the confidence interval of R |
No value
Arto Luoma <[email protected]>
data(dataCovidFin) plotR(data=dataCovidFin, region='All regions')
data(dataCovidFin) plotR(data=dataCovidFin, region='All regions')
Population forecasting using mortality forecast and simple time series forecast for age 0 population
pop.pred(mort, mort.fcast)
pop.pred(mort, mort.fcast)
mort |
mortality data of class 'demogdata' |
mort.fcast |
mortality forecast of class 'fmforecast' |
ARIMA(0,2,2)-model is used to forecast age 0 populaton.
population forecast of class 'demogdata'
Arto Luoma <[email protected]>
data(fin) data(fin.fcast) fin.pcast <- pop.pred(fin,fin.fcast) plot(fin,plot.type="functions",series="total",transform=FALSE, datatype="pop",ages=c(0:100), years=c(1990+0:5*10), xlab="Age") lines(fin.pcast,plot.type="functions",series="total",transform=FALSE, datatype="pop",ages=c(0:100), years=c(1990+0:5*10), lty=2)
data(fin) data(fin.fcast) fin.pcast <- pop.pred(fin,fin.fcast) plot(fin,plot.type="functions",series="total",transform=FALSE, datatype="pop",ages=c(0:100), years=c(1990+0:5*10), xlab="Age") lines(fin.pcast,plot.type="functions",series="total",transform=FALSE, datatype="pop",ages=c(0:100), years=c(1990+0:5*10), lty=2)
This data set provides the populations of the 21 hospital districts, in addition to the total Finnish population.
data("popRegionsFin")
data("popRegionsFin")
A data frame with 22 observations on the following 2 variables.
Alue
character vector: hospital district
val
numeric vector: population
The data were downloaded on March 31, 2021, via THL's open data API.
https://bit.ly/39uZy7C
https://bit.ly/3ryfwE4
data(popRegionsFin) print(popRegionsFin)
data(popRegionsFin) print(popRegionsFin)
Finds an optimal portfolio for long-term investments and plots a return distribution.
portfOptim(i, symbol, yield, vol, beta, indexVol = 0.2, nStocks = 7, total = 1, balanceInt = 1, C = 0.05, riskProportion = 1, riskfreeRate = 0, sim = FALSE)
portfOptim(i, symbol, yield, vol, beta, indexVol = 0.2, nStocks = 7, total = 1, balanceInt = 1, C = 0.05, riskProportion = 1, riskfreeRate = 0, sim = FALSE)
i |
vector of the indices of the included risky investments |
symbol |
character vector of the symbols of the risky investments |
yield |
vector of expected yields (in euros) |
vol |
vector of volatilities |
beta |
vector of betas |
indexVol |
portfolio index volatility |
nStocks |
number of stocks in the portfolio |
total |
total sum invested (in euros) |
balanceInt |
balancing interval of the portfolio (in years) |
C |
expected portfolio return (in euros) |
riskProportion |
proportion of risky investments |
riskfreeRate |
risk-free interest rate |
sim |
is the return distribution simulated and plotted (logical value)? |
The arguments vol, beta, indexVol, riskProportion and riskfreeRate are given in decimals. The portfolio is optimized by minimizing the variance of the portfolio yield for a given expected yield. The returns are assumed to be log-normally distributed. The covariance matrix is computed using the single index model and the properties of the log-normal distribution.
portfolio |
numeric vector of allocations to each stock (in euros) |
returnExpectation |
expected value of the return distribution (in euros) |
returnDeviation |
standard deviation of the return distribution (in euros) |
VaR |
0.5%,1%,5%,10% and 50% percentiles of the return distribution (in euros) |
This function is usually called by drawFigure.
Arto Luoma <[email protected]>
Bodie, Kane, and Marcus (2014) Investments, 10th Global Edition, McGraw-Hill Education, (see Section 7.4 The Markowitz Portfolio Optimization Model and Section 8.2 The Single-Index Model).
data(stockData, package="RcmdrPlugin.RiskDemo") with(stockData,portfOptim(i=1:5,symbol=rownames(stockData), yield=divYield/100,vol=vol/100,beta=beta/100,total=100, sim=TRUE))
data(stockData, package="RcmdrPlugin.RiskDemo") with(stockData,portfOptim(i=1:5,symbol=rownames(stockData), yield=divYield/100,vol=vol/100,beta=beta/100,total=100, sim=TRUE))
Computing expected returns and their covariance matrix when the returns are lognormal.
returns(volvec, indexvol, beta)
returns(volvec, indexvol, beta)
volvec |
vector of volatilities |
indexvol |
volatility of the portfolio index |
beta |
vector of betas |
The arguments are given in decimals. The single index model is used to compute the covariance matrix of a multivariate normal distribution. The mean vector is assumed to be zero. The properties of the log-normal distribution are then used to compute the mean vector and covariance matrix of the corresponding multivariate log-normal distribution.
mean |
vector of expected returns |
cov |
covariance matrix of returns |
Arto Luoma <[email protected]>
Bodie, Kane, and Marcus (2014) Investments, 10th Global Edition, McGraw-Hill Education, (see Section 8.2 The Single-Index Model).
returns(volvec=c(0.1,0.2,0.3),indexvol=0.2, beta=c(0.5,-0.1,1.1))
returns(volvec=c(0.1,0.2,0.3),indexvol=0.2, beta=c(0.5,-0.1,1.1))
This function solves Lund's exponent or adjustment coefficient. The claim sizes are assumed to be gamma distributed.
solveLund(alpha, beta, theta)
solveLund(alpha, beta, theta)
alpha |
shape parameter of gamma distribution |
beta |
rate parameter of gamma distribution |
theta |
safety loading |
Lundberg's exponent (or adjustment coefficient)
Arto Luoma <[email protected]>
Gray and Pitts (2012) Risk Modelling in General Insurance: From Principles to Practice, Cambridge University Press.
computeRuin
, computeRuinFinite
solveLund(1,1,0.1)
solveLund(1,1,0.1)
This function computes the yield to maturity, given the (flat) bond price.
solveYield(buyDate, matDate, rateCoupon, bondPr, nPay)
solveYield(buyDate, matDate, rateCoupon, bondPr, nPay)
buyDate |
settlement date (the date when the bond is bought) |
matDate |
maturity date |
rateCoupon |
annual coupon rate |
bondPr |
bond price. The flat price without accrued interest. |
nPay |
number of payments per year |
all the rates are given in decimals
A list with the following components:
yieldToMaturity |
yield to maturity |
flatPrice |
flat price |
daysSinceLastCoupon |
days since previous coupon payment |
daysInCouponPeriod |
days in a coupon period |
accruedInterest |
accrued interest since last coupon payment |
invoicePrice |
invoice price (= flat price + accrued interest) |
With Excel function YIELD you can do the same.
Arto Luoma <[email protected]>
Bodie, Kane, and Marcus (2014) Investments, 10th Global Edition, McGraw-Hill Education, (see Bond Pricing between Coupon Dates in Section 14.2).
solveYield("2012-7-31","2018-7-31",0.0225,100,2)
solveYield("2012-7-31","2018-7-31",0.0225,100,2)
This function computes the intrinsic stock price using the constant growth dividend discount model.
stock.price(dividend, k = NULL, g = NULL, ROE = NULL, b = NULL, riskFree = NULL, marketPremium = NULL, beta = NULL)
stock.price(dividend, k = NULL, g = NULL, ROE = NULL, b = NULL, riskFree = NULL, marketPremium = NULL, beta = NULL)
dividend |
expected dividend(s) for the next year(s) (in euros), separated by commas |
k |
required rate of return |
g |
growth rate of dividends |
ROE |
return on investment |
b |
plowback ratio |
riskFree |
riskfree rate |
marketPremium |
market risk premium |
beta |
beta |
All the above rates are given in percentages (except the dividends). One should provide either k or the following three: riskFree, marketPremium, beta. Further, one should provide either g or the following two: ROE and b. In the output, k and g are given in decimals.
dividend |
expected dividend(s) for the next year(s) (in euros) |
k |
required rate of return |
g |
growth rate of dividends |
PVGO |
present value of growths opportunities |
stockPrice |
intrinsic stock price |
Arto Luoma <[email protected]>
Bodie, Kane, and Marcus (2014) Investments, 10th Global Edition, McGraw-Hill Education, (see Dividend Discount Models in Section 18.3).
stock.price(dividend=c(1),k=12,g=10) stock.price(dividend=c(1),ROE=50,b=20,riskFree=5,marketPremium=8, beta=90)
stock.price(dividend=c(1),k=12,g=10) stock.price(dividend=c(1),ROE=50,b=20,riskFree=5,marketPremium=8, beta=90)
Stock data on large companies in Helsinki Stock Exchange, downloaded from Kauppalehti web page (www.kauppalehti.fi), on May 13, 2017
data("stockData")
data("stockData")
A data frame with 35 observations on the following 7 variables.
names
name of the firm
abbrs
abbreviation of the firm
quote
closing quote
vol
volatility (%)
beta
beta (%)
div
dividend (eur/stock)
divYield
dividend yield (%)
www.kauppalehti.fi
data(stockData) plot(stockData[,-(1:2)])
data(stockData) plot(stockData[,-(1:2)])