Title: | Y&R Miscellaneous R Functions |
---|---|
Description: | Miscellaneous functions for data analysis, portfolio management, graphics, data manipulation, statistical investigation, including descriptive statistics, creating leading and lagging variables, portfolio return analysis, time series difference and percentage change calculation, stacking data for higher efficient analysis. |
Authors: | Manuel Russon <[email protected]>, Xuanhua (Peter) Yin <[email protected]> |
Maintainer: | Xuanhua (Peter) Yin <[email protected]> |
License: | GPL (>= 2) |
Version: | 0.1.6 |
Built: | 2025-02-21 03:28:58 UTC |
Source: | https://github.com/cran/YRmisc |
Calculating correlation of two vectors with lag and lead periods. The correlations are used to determine the lag or lead effect between two variables. The correlation function uses "na.or.complete" method and calculate the Pearson's correlation.
cor.lag(x,y,lag,lead)
cor.lag(x,y,lag,lead)
x |
:the moving vector |
y |
:the fixed vector |
lag |
:number of lag periods |
lead |
:number of lead periods |
cor.lag(mtcars[,1],mtcars[,2],3,3)
cor.lag(mtcars[,1],mtcars[,2],3,3)
Calculate Spearman Rank Correlation, which is the nonparametric version of the Pearson product-moment correlation.
cor.spearman(x,y)
cor.spearman(x,y)
x |
:a numeric variable |
y |
:a numeric variable |
cor.spearman(mtcars[,1], mtcars[,3])
cor.spearman(mtcars[,1], mtcars[,3])
Calculate future value of an ordinary annuity or an annuity due.
cv.annu.fv(pmt,i,n,type = 0)
cv.annu.fv(pmt,i,n,type = 0)
pmt |
:the equal amount of payment of each period |
i |
:interest rate according to the period |
n |
:number of periods |
type |
:type = 0 for ordinary annuity, type = 1 for annuity due |
cv.annu.fv(100,0.0248,10,0)
cv.annu.fv(100,0.0248,10,0)
Calculate present value of an ordinary annuity or an annuity due.
cv.annu.pv(pmt,i,n,k)
cv.annu.pv(pmt,i,n,k)
pmt |
:the equal amount of payment of each period |
i |
:interest rate according to the period |
n |
:number of periods |
k |
:number of periods deferred until first payment |
cv.annu.pv(100,0.0248,10,4)
cv.annu.pv(100,0.0248,10,4)
Create a new variable with the base of a random number and power of the selected variable
cv.axp(dataframe, var, n, range)
cv.axp(dataframe, var, n, range)
dataframe |
:a data frame |
var |
:the variable selected |
n |
:number of new variables created |
range |
:the range of base |
cv.axp(mtcars,"wt",5,c(1, 2))
cv.axp(mtcars,"wt",5,c(1, 2))
Calculate the plain vanilla bond price
cv.bondprice(par,c,yield,n,m)
cv.bondprice(par,c,yield,n,m)
par |
:the face value of the bond |
c |
:the annual coupon rate of the bond |
yield |
:the annual yield to maturity of a bond |
n |
:number of years |
m |
:compounding period in a year |
cv.bondprice(1000,0.0248,0.0248,10,2)
cv.bondprice(1000,0.0248,0.0248,10,2)
Calculate the difference of a time series, with a specific lag period. The difference is used to show the change in value over set period.
cv.diff(x,n)
cv.diff(x,n)
x |
: a numeric vector |
n |
: number of lag periods |
cv.diff(mtcars[,2],1)
cv.diff(mtcars[,2],1)
Calculate largest draw down of a series of returns. This function calculates the maximum decrease in percentage over time, which can be used to test portfolio returns.
cv.drawdown(x)
cv.drawdown(x)
x |
: a numeric vector of returns |
# rnorm() is used to simulate portfolio returns returns <- rnorm(100) cv.drawdown(returns)
# rnorm() is used to simulate portfolio returns returns <- rnorm(100) cv.drawdown(returns)
Create a lag variable, with a choice of lag periods. The lag variable can be used to test lag effects between variables.
cv.lag(x,n)
cv.lag(x,n)
x |
:a vector |
n |
:number of lag periods |
cv.lag(mtcars[,2],3) data.frame(mtcars,cv.lag(mtcars[,3], 1))
cv.lag(mtcars[,2],3) data.frame(mtcars,cv.lag(mtcars[,3], 1))
Create a lead variable, with a choice of lead periods. The lead variable can be used to test lead effects between variables.
cv.lead(x,n)
cv.lead(x,n)
x |
:a vector |
n |
:number of lead periods |
cv.lead(mtcars[,2],3) data.frame(mtcars,cv.lead(mtcars[,3], 3))
cv.lead(mtcars[,2],3) data.frame(mtcars,cv.lead(mtcars[,3], 3))
Create a new variable that is the logarithm of the selected variable with the base of a random number
cv.logs(dataframe, var, n, range)
cv.logs(dataframe, var, n, range)
dataframe |
:a data frame |
var |
:the variable selected |
n |
:number of new variables created |
range |
:the range of base |
cv.logs(mtcars,"wt",5,c(1, 2))
cv.logs(mtcars,"wt",5,c(1, 2))
Calculating the percentage change of a time series vector for further analysis, including calculating beta of companies, plotting to see the trend of the stock for technical analysis.
cv.pctcng(x,n)
cv.pctcng(x,n)
x |
:a numeric vector |
n |
: number of lag periods |
cv.pctcng(mtcars[,1],1)
cv.pctcng(mtcars[,1],1)
Create a new variable that is the nth power of the selected variable
cv.powers(dataframe, var, n, range)
cv.powers(dataframe, var, n, range)
dataframe |
:a data frame |
var |
:the variable selected |
n |
:number of new variables created |
range |
:the range of power |
cv.powers(mtcars,"wt",5,c(1, 2))
cv.powers(mtcars,"wt",5,c(1, 2))
Sort a data frame by a column of choice. The column of choice is specified by the number of the column.
df.sortcol(x,n,desc)
df.sortcol(x,n,desc)
x |
:a data frame |
n |
:number column to sort |
desc |
:the order of sorting, default set to TRUE; for ascending order set to FALSE |
df.sortcol(mtcars,2,desc = TRUE)
df.sortcol(mtcars,2,desc = TRUE)
Stack data frame by one classifier. This function takes the first column as a ordering variable. Then it take the variables names and repeat as the second column. The last column will be data under each variable name. This function is created to enable easier investigation with apply functions.
df.stack(df,name)
df.stack(df,name)
df |
: a data frame used to stack |
name |
: new variable names of the data frame |
df <- data.frame(matrix(nrow=100,ncol=100)) for(i in 1:100){ df[,i] <- rep(runif(1,1,100),100) } dim(df) hdf <- df.stack(df,c("date","tkr","price"))
df <- data.frame(matrix(nrow=100,ncol=100)) for(i in 1:100){ df[,i] <- rep(runif(1,1,100),100) } dim(df) hdf <- df.stack(df,c("date","tkr","price"))
Calculating the correlation matrix of a data frame and return in a data frame object
ds.corm(x,n)
ds.corm(x,n)
x |
:a data frame |
n |
:number of decimal points |
ds.corm(mtcars,3)
ds.corm(mtcars,3)
Kurtosis
ds.kurt(x)
ds.kurt(x)
x |
:a numeric variable |
ds.kurt(mtcars[,2])
ds.kurt(mtcars[,2])
Calculating mode for numeric data.
ds.mode(x)
ds.mode(x)
x |
:a numeric variable |
ds.mode(mtcars[,2])
ds.mode(mtcars[,2])
Calculating Pearson's skewness in three types: mode, median, and mean.
ds.skew(x, type = 3)
ds.skew(x, type = 3)
x |
:a numeric variable |
type |
:type = 1 for mode skewness; type = 2 for median skewness; type = 3 for mean skewness |
ds.skew(mtcars[,1])
ds.skew(mtcars[,1])
Calculating the descriptive statistics of a data frame and exporting in a data frame. The report data frame contains: number of observations, maximum value, minimum value, mean, median, mode, variance, standard deviation, skewness and kurtosis.
ds.summ(x,n)
ds.summ(x,n)
x |
:a data frame |
n |
:number of decimal points rounded |
ds.summ(mtcars,3)
ds.summ(mtcars,3)
Plotting two time series in one plot, with title.
pl.2ts(ts1,ts2,title)
pl.2ts(ts1,ts2,title)
ts1 |
:time series variable one |
ts2 |
:time series variable two |
title |
:title for the plot |
DAX <- EuStockMarkets[,1] FTSE <- EuStockMarkets[,4] pl.2ts(DAX,FTSE, "Times Series Plot of DAX and FTSE")
DAX <- EuStockMarkets[,1] FTSE <- EuStockMarkets[,4] pl.2ts(DAX,FTSE, "Times Series Plot of DAX and FTSE")
Plotting two time series in one plot, with title and label. If both variables are time series object, they will be merged by time. If both variables are not time series object, they will be merged by order. The first variable is set to be a solid line and the second variable is set to be a dashed line. If the variables are of different type a warning message will be given.
pl.2tsgg(ts1,ts2,title,ylab)
pl.2tsgg(ts1,ts2,title,ylab)
ts1 |
:a time series variable or a numeric variable |
ts2 |
:a time series variable or a numeric variable |
title |
:title for the plot |
ylab |
:y-axis label |
DAX <- EuStockMarkets[,1] FTSE <- EuStockMarkets[,4] pl.2tsgg(DAX,FTSE, "Times Series Plot of DAX and FTSE", "Index")
DAX <- EuStockMarkets[,1] FTSE <- EuStockMarkets[,4] pl.2tsgg(DAX,FTSE, "Times Series Plot of DAX and FTSE", "Index")
Generate a scatter plot with text overlay, with a smooth curve fitted by loess.
pl.3smoothtxt(x,y,txt,ce)
pl.3smoothtxt(x,y,txt,ce)
x |
: a numeric vector |
y |
: a numeric vector |
txt |
: a vector used as labels |
ce |
: text size, which default is set as 0.5 |
pl.3smoothtxt(mtcars[,1], mtcars[,3], row.names(mtcars))
pl.3smoothtxt(mtcars[,1], mtcars[,3], row.names(mtcars))
Generate a scatter plot with text overlay, with a smooth curve fitted by loess.
pl.3smoothtxtgg(x,y,txt,size,title,xlab,ylab)
pl.3smoothtxtgg(x,y,txt,size,title,xlab,ylab)
x |
:a numeric vector |
y |
:a numeric vector |
txt |
:a vector used as labels |
size |
:text size, which default is set as 3 |
title |
:graph title |
xlab |
:x-axis label |
ylab |
:y-axis label |
pl.3smoothtxtgg(mtcars[,1], mtcars[,3], row.names(mtcars), 3, "MPG v. DISP","mpg","disp")
pl.3smoothtxtgg(mtcars[,1], mtcars[,3], row.names(mtcars), 3, "MPG v. DISP","mpg","disp")
Generate a scatter plot with text overlay. This plot is to better show the effect of the text variable in the domain of x and y variable.
pl.3txt(x,y,txt,title)
pl.3txt(x,y,txt,title)
x |
:a numeric vector |
y |
:a numeric vector |
txt |
:a vector used as labels |
title |
:title of the graph |
pl.3txt(mtcars[,1], mtcars[,3], row.names(mtcars),"mpg v. cyl")
pl.3txt(mtcars[,1], mtcars[,3], row.names(mtcars),"mpg v. cyl")
Generate a scatter plot with text overlay with ggplot2. This plot is to better show the effect of the text variable in the domain of x and y variable.
pl.3txtgg(x,y,txt,size,title,xlab,ylab)
pl.3txtgg(x,y,txt,size,title,xlab,ylab)
x |
:a numeric vector |
y |
:a numeric vector |
txt |
:a vector used as labels |
size |
:text size, which default is set as 3 |
title |
:title of the graph |
xlab |
:x-axis label |
ylab |
:y-axis label |
pl.3txtgg(mtcars[,1], mtcars[,3], row.names(mtcars), 3,"mpg v. cyl", "mpg", "cyl")
pl.3txtgg(mtcars[,1], mtcars[,3], row.names(mtcars), 3,"mpg v. cyl", "mpg", "cyl")
Generate 4 scatter plots of x and y divided by variable z, with a fitted line using a simple linear regression method.
pl.coplot(x,y,z,varN)
pl.coplot(x,y,z,varN)
x |
:x-axis value |
y |
:y-axis value |
z |
:classification variable used to condition plots based on ascending values of z |
varN |
:variable name of z |
pl.coplot(mtcars[,1], mtcars[,3], mtcars[,4], "hp")
pl.coplot(mtcars[,1], mtcars[,3], mtcars[,4], "hp")
Plotting histograms for a data frame, with titles and label numbers.
pl.hist(x, l = 1)
pl.hist(x, l = 1)
x |
:a data frame |
l |
: the beginning label number in the title (default set to 1) |
pl.hist(mtcars,1)
pl.hist(mtcars,1)
Plotting histograms for a data frame with 4 per page, with titles and label numbers automatically generated.
pl.histgg(x,l,bin)
pl.histgg(x,l,bin)
x |
:a data frame |
l |
:the beginning label number in the title (default set to 1) |
bin |
:bin width of histogram (default set to 30) |
pl.histgg(as.data.frame(EuStockMarkets),1)
pl.histgg(as.data.frame(EuStockMarkets),1)
Plotting histograms or scatter plots of your choice for a data frame. Also the function will name the graphs and number them. The purpose of the function is to save time when plotting graphs for a regression analysis or other usage. The function can plot, name and number the graphs at one step.
pl.hs(x,a,dependent,l)
pl.hs(x,a,dependent,l)
x |
:a data frame |
a |
:the type of graph you want; a = 1 for histograms; a = 2 for scatter plots; a = 0 for both |
dependent |
:the dependent variable for scatterplots |
l |
: the beginning label number in the title (default set to 1) |
pl.hs(mtcars,0,"mpg",1)
pl.hs(mtcars,0,"mpg",1)
Plotting histogram with density for a data frame, with titles and label numbers.
pl.hsd(dataframe,l)
pl.hsd(dataframe,l)
dataframe |
:a data frame |
l |
: the beginning label number in the title (default set to 1) |
pl.hsd(mtcars,1)
pl.hsd(mtcars,1)
Plotting histograms for a data frame with 4 per page, with titles and label numbers automatically generated.
pl.hsdgg(x,l,bin)
pl.hsdgg(x,l,bin)
x |
:a data frame |
l |
:the beginning label number in the title (default set to 1) |
bin |
:bin width of the graph |
pl.hsdgg(as.data.frame(EuStockMarkets),1,100)
pl.hsdgg(as.data.frame(EuStockMarkets),1,100)
This function is used to plot the result of portfolio simulation by pt.mv().
pl.mv(port)
pl.mv(port)
port |
:portfolio simulation result from pt.mv() |
set.seed(1) rtn <- data.frame(runif(120,-1,1),runif(120,-1,1),runif(120,-1,1),runif(120,-1,1)) names(rtn) <- c("asset1","asset2","asset3","asset4") portfolio <- pt.hismv(rtn,1000,0) pl.mv(portfolio)
set.seed(1) rtn <- data.frame(runif(120,-1,1),runif(120,-1,1),runif(120,-1,1),runif(120,-1,1)) names(rtn) <- c("asset1","asset2","asset3","asset4") portfolio <- pt.hismv(rtn,1000,0) pl.mv(portfolio)
Plotting scatter plots for a data frame, with titles and label numbers.
pl.s(x,dependent,l)
pl.s(x,dependent,l)
x |
:a data frame, which includes the dependent variable |
dependent |
:the dependent variable for scatter plot |
l |
: the beginning label number in the title (default set to 1) |
pl.s(mtcars,"mpg",1)
pl.s(mtcars,"mpg",1)
Plotting scatter plots for a data frame using ggplot2, with titles and label numbers. The output will be 4 graphs per page.
pl.sgg(x,dependent,l)
pl.sgg(x,dependent,l)
x |
:a data frame, which includes the dependent variable |
dependent |
:the dependent variable for scatter plot |
l |
: the beginning label number in the title (default set to 1) |
pl.sgg(mtcars,"mpg",1)
pl.sgg(mtcars,"mpg",1)
Plotting scatter smooth plots for a data frame, with titles and label numbers.
pl.sm(x,dependent,l)
pl.sm(x,dependent,l)
x |
:a data frame, which includes the dependent variable |
dependent |
:the dependent variable for scatter smooth plots |
l |
: the beginning label number in the title (default set to 1) |
pl.sm(mtcars,"mpg",1)
pl.sm(mtcars,"mpg",1)
Plotting scatter plots for a data frame using ggplot2, with titles and label numbers. A smooth line will be added using a chosen method. The output will be 4 graphs per page.
pl.smgg(x,dependent,l,mtd)
pl.smgg(x,dependent,l,mtd)
x |
:a data frame, which includes the dependent variable |
dependent |
:the dependent variable for scatter plot |
l |
:the beginning label number in the title (default set to 1) |
mtd |
:sommthing method to use, accepts either a character vector or a function, e.g. MASS::rlm, base::lm, base::loess, mgcv::gam |
pl.smgg(mtcars,"mpg",1,lm) pl.smgg(mtcars,"mpg",1,loess)
pl.smgg(mtcars,"mpg",1,lm) pl.smgg(mtcars,"mpg",1,loess)
Plotting time series plots for a data frame, with titles and label numbers.
pl.ts(x, l = 1)
pl.ts(x, l = 1)
x |
:a data frame |
l |
: the beginning label number in the title (default set to 1) |
pl.ts(mtcars,1)
pl.ts(mtcars,1)
Plotting time series plot for a data frame with 4 per page, with titles and label numbers automatically generated.
pl.tsgg(x,l)
pl.tsgg(x,l)
x |
:a data frame |
l |
: the beginning label number in the title (default set to 1) |
pl.tsgg(as.data.frame(EuStockMarkets),1)
pl.tsgg(as.data.frame(EuStockMarkets),1)
This function will return a time series plot with up to 6 variables, each with different line type.
pl.tss(dataframe,ylb,title)
pl.tss(dataframe,ylb,title)
dataframe |
:a data frame |
ylb |
:y-axis label |
title |
:plot title |
pl.tss(EuStockMarkets,"Price","Daily Closing Prices of Major European Stock Indices")
pl.tss(EuStockMarkets,"Price","Daily Closing Prices of Major European Stock Indices")
Alpha is the intercept of a fitted line when dependent variable is the benchmark return and independent variable is a asset return of the same period. It is a measure of the active return on an investment. Alpha, along with beta, is one of the two key coefficients in the CAPM used modern portfolio theory.
pt.alpha(ar,br)
pt.alpha(ar,br)
ar |
:a vector of a risk asset return |
br |
:a vector of benchmark return |
brtn <- runif(100, -1, 1) artn <- runif(100, -1, 1) pt.alpha(artn,brtn)
brtn <- runif(100, -1, 1) artn <- runif(100, -1, 1) pt.alpha(artn,brtn)
Annualized excess return is the difference between the annualized and cumulative return of the two series. Usually, one series are portfolio returns and the other is a benchmark returns.
pt.annexrtn(ar,br)
pt.annexrtn(ar,br)
ar |
:a vector of a risk asset return |
br |
:a vector of benchmark return |
artn <- runif(100, -1, 1) brtn <- runif(100, -1, 1) pt.annexrtn(artn, brtn)
artn <- runif(100, -1, 1) brtn <- runif(100, -1, 1) pt.annexrtn(artn, brtn)
This function takes a series of annual returns and calculate the annualized return.
pt.annrtn(r,n)
pt.annrtn(r,n)
r |
:annual returns |
n |
:number of years |
r <- runif(100,-1,1) # generate random number to simulate returns annualizedreturn <- pt.annrtn(r,100)
r <- runif(100,-1,1) # generate random number to simulate returns annualizedreturn <- pt.annrtn(r,100)
The annualized standard deviation is the standard deviation multiplied by the square root of the number of periods in one year.
pt.annsd(r,n)
pt.annsd(r,n)
r |
:a vector of a risk asset return |
n |
:number of periods in a year |
rtn <- runif(30, -1, 1) n <- 30 pt.annsd(rtn,n)
rtn <- runif(30, -1, 1) n <- 30 pt.annsd(rtn,n)
Beta is the slope of a fitted line when dependent variable is the benchmark return and independent variable is an asset return of the same period. It is a measure the risk arising from exposure to general market movements.
pt.beta(ar,br)
pt.beta(ar,br)
ar |
:a vector of a risk asset return |
br |
:a vector of benchmark return |
brtn <- runif(100, -1, 1) artn <- runif(100, -1, 1) pt.beta(artn, brtn)
brtn <- runif(100, -1, 1) artn <- runif(100, -1, 1) pt.beta(artn, brtn)
The bias ratio is an indicator used in finance analyze the returns of a portfolio, and in performing due diligence.
pt.bias(r)
pt.bias(r)
r |
:a vector of a risk asset return |
r <- runif(100,0,1) # generate random number to simulate returns pt.bias(r)
r <- runif(100,0,1) # generate random number to simulate returns pt.bias(r)
The batting average of the asset is the ratio between the number of periods where the asset outperforms a benchmark and the total number of periods.
pt.btavg(ar,br)
pt.btavg(ar,br)
ar |
:a vector of a risk asset return |
br |
:a vector of a benchmark return |
artn <- runif(100,-1,1) brtn <- runif(100,-1,1) pt.btavg(artn,brtn)
artn <- runif(100,-1,1) brtn <- runif(100,-1,1) pt.btavg(artn,brtn)
Cumulative return is the compounded return in a given period. The excess return is the difference between the cumulative return of a risky asset and the cumulative return of a benchmark.
pt.cmexrtn(ar,br)
pt.cmexrtn(ar,br)
ar |
:a vector of risky asset returns |
br |
:a vector of benchmark returns |
brtn <- runif(12, -1, 1) artn <- runif(12, -1, 1) pt.cmexrtn(artn,brtn)
brtn <- runif(12, -1, 1) artn <- runif(12, -1, 1) pt.cmexrtn(artn,brtn)
Cumulative return is the compounded return in a given period.
pt.cmrtn(r)
pt.cmrtn(r)
r |
:a vector of periodic returns |
rt <- runif(12,-1,1) # generate random number to simulate returns pt.cmrtn(rt)
rt <- runif(12,-1,1) # generate random number to simulate returns pt.cmrtn(rt)
Dual-alpha method is to divide market alpha into downside beta and upside alpha. The principle behind is that upside and downside alphas are not the same.
pt.dalpha(ar,mr,rf)
pt.dalpha(ar,mr,rf)
ar |
:a vector of a risk asset return |
mr |
:a vector of market return |
rf |
:risk free rate |
artn <- runif(24,0,1) # generate random number to simulate returns mrtn <- runif(24,-1,1) pt.dalpha(artn,mrtn,0.024)
artn <- runif(24,0,1) # generate random number to simulate returns mrtn <- runif(24,-1,1) pt.dalpha(artn,mrtn,0.024)
Dual-beta method is to divide market beta into downside beta and upside beta. The principle behind is that upside and downside betas are not the same.
pt.dbeta(ar,mr,rf)
pt.dbeta(ar,mr,rf)
ar |
:a vector of a risk asset return |
mr |
:a vector of market return |
rf |
:risk free rate |
artn <- runif(24,0,1) # generate random number to simulate returns mrtn <- runif(24,-1,1) pt.dbeta(artn,mrtn,0.024)
artn <- runif(24,0,1) # generate random number to simulate returns mrtn <- runif(24,-1,1) pt.dbeta(artn,mrtn,0.024)
This function give the expected loss of given asset returns.
pt.exploss(r,p)
pt.exploss(r,p)
r |
:a vector of periodic returns |
p |
:target return |
rt <- runif(12,-1,1) # generate random number to simulate returns pt.exploss(rt,0) pt.exploss(rt,1)
rt <- runif(12,-1,1) # generate random number to simulate returns pt.exploss(rt,0) pt.exploss(rt,1)
This function will perform portfolio simulation with historical average returns and standard deviatoins. Mean-variance model, or modern portfolio theory, is a mathmatical framework for accessing a portfolio. It uses the variance of asset returns as a risk proxy. This function will return a number of simulated portfolio with different weights.
pt.hismv(r,n,mini)
pt.hismv(r,n,mini)
r |
:a data frame of asset returns |
n |
:number of portfolio simulated |
mini |
:minimal weight; choose 0 if long only; choose 1 for possible short position |
set.seed(20) rtn <- data.frame(runif(120,-1,1),runif(120,-1,1),runif(120,-1,1),runif(120,-1,1)) names(rtn) <- c("asset1","asset2","asset3","asset4") portfolio <- pt.hismv(rtn,1000,0) plot(portfolio[,6], portfolio[,5], xlab = "standart deviation", ylab = "expected return")
set.seed(20) rtn <- data.frame(runif(120,-1,1),runif(120,-1,1),runif(120,-1,1),runif(120,-1,1)) names(rtn) <- c("asset1","asset2","asset3","asset4") portfolio <- pt.hismv(rtn,1000,0) plot(portfolio[,6], portfolio[,5], xlab = "standart deviation", ylab = "expected return")
The information ratio of asset's returns versus benchmark returns, is the quotient of the annualized excess return and the annualized standard deviation of the excess return.
pt.info(ar,br,n)
pt.info(ar,br,n)
ar |
:a vector of a risk asset return |
br |
:a vector of benchmark return |
n |
:number of years |
brtn <- runif(100, -1, 1) artn <- runif(100, 0, 1) pt.info(artn,brtn,100)
brtn <- runif(100, -1, 1) artn <- runif(100, 0, 1) pt.info(artn,brtn,100)
Jensen's alpha is a financial statistic used to quantify the abnormal return of a security or portfolio over the theoretical expected return. Unlike, standard alpha, it uses theoretical performance return instead of a market return.
pt.jalpha(pr,mr,rf,beta)
pt.jalpha(pr,mr,rf,beta)
pr |
:portfolio return |
mr |
:market return |
rf |
:risk free rate |
beta |
:portfolio beta |
prtn <- runif(24, -1, 1) mrtn <- runif(24, -1, 1) rf <- 0.024 pt.jalpha(mean(prtn), mean(mrtn), rf, pt.beta(prtn,mrtn))
prtn <- runif(24, -1, 1) mrtn <- runif(24, -1, 1) rf <- 0.024 pt.jalpha(mean(prtn), mean(mrtn), rf, pt.beta(prtn,mrtn))
Modigliani risk-adjusted performance is a financial measure of risk-adjusted returns of a portfolio. It measures the returns of the portfolio after adjusting it relative to some benchmark.
pt.m2(pr,br,rf)
pt.m2(pr,br,rf)
pr |
:portfolio return |
br |
:benchmark return |
rf |
:risk free rate |
prtn <- runif(12,-1,1) brtn <- runif(12,-1,1) rf <- 0.024 pt.m2(prtn,brtn,rf)
prtn <- runif(12,-1,1) brtn <- runif(12,-1,1) rf <- 0.024 pt.m2(prtn,brtn,rf)
This function give the probability of loss of given asset returns.
pt.probloss(r,p)
pt.probloss(r,p)
r |
:a vector of periodic returns |
p |
:target return |
rt <- runif(12,-1,1) # generate random number to simulate returns pt.probloss(rt,0) pt.probloss(rt,0.05)
rt <- runif(12,-1,1) # generate random number to simulate returns pt.probloss(rt,0) pt.probloss(rt,0.05)
Roy's safety-first criterion is a risk management technique that allows to choose a portfolio based on the criterion that the probability of the portfolio's return falling below a minimum desired threshold is minimized.
pt.roy(r,mar)
pt.roy(r,mar)
r |
:a vector of a risk asset return |
mar |
:minimum acceptable return |
r <- runif(100,0,1) # generate random number to simulate returns pt.roy(r,0.024)
r <- runif(100,0,1) # generate random number to simulate returns pt.roy(r,0.024)
The standard deviation of excess return is simply the standard deviation of the asset return over the benchmark return.
pt.sdexrtn(ar,br)
pt.sdexrtn(ar,br)
ar |
:a vector of a risk asset return |
br |
:a vector of benchmark return |
artn <- runif(12, -1, 1) brtn <- runif(12,-1,1) pt.sdexrtn(artn,brtn)
artn <- runif(12, -1, 1) brtn <- runif(12,-1,1) pt.sdexrtn(artn,brtn)
This function give the semivariance of a losing scenario.
pt.semivar(r,p)
pt.semivar(r,p)
r |
:a vector of periodic returns |
p |
:target return |
rt <- runif(12,-1,1) # generate random number to simulate returns pt.semivar(rt,0) pt.semivar(rt,0.03)
rt <- runif(12,-1,1) # generate random number to simulate returns pt.semivar(rt,0) pt.semivar(rt,0.03)
The Sharpe Ratio of an asset return is the quotient of the annualized excess return of the asset minus the annualized risk-free rate over the annualized standard deviation of the asset return.
pt.sharp(r,n,m,rf)
pt.sharp(r,n,m,rf)
r |
:a vector of asset returns |
n |
:number of years |
m |
:number of periods in a year; m = 12 if r is monthly returns |
rf |
:annulized risk-free rate |
set.seed(20) rtn <- runif(12,-0.5,1) # generate random number to simulate monthly returns rfr <- 0.024 # set risk free rate at 2.4% annual pt.sharp(rtn,1,12,rfr) # the return is for one year
set.seed(20) rtn <- runif(12,-0.5,1) # generate random number to simulate monthly returns rfr <- 0.024 # set risk free rate at 2.4% annual pt.sharp(rtn,1,12,rfr) # the return is for one year
The Sortino ratio is an analog to the sharp ratio, with standard deviation replaced by the downside deviation.
pt.sortino(r,p,n,rf)
pt.sortino(r,p,n,rf)
r |
:a vector of a risk asset return |
p |
:target return, aka minimum acceptable return(MAR) |
n |
:number of years of asset return, used to calculate annualized return |
rf |
:risk free rate |
rtn <- runif(12, -1, 1) pt.sortino(rtn,0.3,1,0.024)
rtn <- runif(12, -1, 1) pt.sortino(rtn,0.3,1,0.024)
Tracking error, in finance, is a measure of risk in a portfolio that is due to active management decisions made by the manager. It indicates how closely the portfolio follows the benchmark of choosing.
pt.te(pr,br)
pt.te(pr,br)
pr |
:portfolio return |
br |
:benchmark return |
prtn <- runif(12,-1,1) brtn <- runif(12,-1,1) pt.te(prtn,brtn)
prtn <- runif(12,-1,1) brtn <- runif(12,-1,1) pt.te(prtn,brtn)
The Treynor ratio is an analog to the sharp ratio, with standard deviation replaced by the asset beta to benchmark.
pt.treynor(ar,br,n,rf)
pt.treynor(ar,br,n,rf)
ar |
:a vector of a risk asset return |
br |
:a vector of benchmark return |
n |
:number of years of asset return, used to calculate annualized return |
rf |
:risk free rate |
rtn <- runif(24, -1, 1) brtn <- runif(24,-1,1) pt.treynor(rtn,brtn,2,0.024)
rtn <- runif(24, -1, 1) brtn <- runif(24,-1,1) pt.treynor(rtn,brtn,2,0.024)
This function calculates the average up and down returns from a series of returns.
pt.udrtn(r)
pt.udrtn(r)
r |
:a vector of periodic returns |
r <- runif(100,-1,1) # generate random number to simulate returns pt.udrtn(r)
r <- runif(100,-1,1) # generate random number to simulate returns pt.udrtn(r)
The up and down capture is a measure of how an asset was able to improve on benchmark returns or how it underperforms over the benchmark.
pt.updwcap(ar,br,n)
pt.updwcap(ar,br,n)
ar |
:a vector of a risk asset return |
br |
:a vector of benchmark return |
n |
:number of years of asset return, used to calculate annualized return |
artn <- runif(12, -1, 1) brtn <- runif(12,-1,1) pt.updwcap(artn,brtn,1)
artn <- runif(12, -1, 1) brtn <- runif(12,-1,1) pt.updwcap(artn,brtn,1)
Calculate Adjusted R-squared for the outcome of lm.fit. This function is built for reg.linreg() for higher efficiency only. It can't be used for calculating Adjusted R-squared in general operation.
reg.adj.r.squared(r,n,p)
reg.adj.r.squared(r,n,p)
r |
:R-squared for regression |
n |
:number of observations aka. sample size |
p |
:number of explanatory variables in the model |
X <- as.matrix(cbind(1,EuStockMarkets[,1:2])) # create the design matrix Y <- as.data.frame(EuStockMarkets)$FTSE fit <- lm.fit(x = X, y = Y) SSR <- sum((fit$fitted.values - mean(Y))^2) SSTO <- sum((Y - mean(Y))^2) r <- reg.r.squared(SSR,SSTO) n <- dim(X)[1]; p <- dim(X)[2] reg.adj.r.squared(r,n,p)
X <- as.matrix(cbind(1,EuStockMarkets[,1:2])) # create the design matrix Y <- as.data.frame(EuStockMarkets)$FTSE fit <- lm.fit(x = X, y = Y) SSR <- sum((fit$fitted.values - mean(Y))^2) SSTO <- sum((Y - mean(Y))^2) r <- reg.r.squared(SSR,SSTO) n <- dim(X)[1]; p <- dim(X)[2] reg.adj.r.squared(r,n,p)
Calculate AIC for the outcome of AIC. This function is built for reg.linreg for higher efficiency only. It can't be used for calculating AIC in general operation.
reg.aic(fit,w)
reg.aic(fit,w)
fit |
:the outcome of lm.fit |
w |
:wright |
X <- as.matrix(cbind(1,EuStockMarkets[,1:2])) # create the design matrix Y <- as.data.frame(EuStockMarkets)$FTSE fit <- lm.fit(x = X, y = Y) w <- rep(1,length(Y)) reg.aic(fit,w)
X <- as.matrix(cbind(1,EuStockMarkets[,1:2])) # create the design matrix Y <- as.data.frame(EuStockMarkets)$FTSE fit <- lm.fit(x = X, y = Y) w <- rep(1,length(Y)) reg.aic(fit,w)
Calculate BIC for the outcome of lm.fit This function is built for reg.linreg() for higher efficiency only. It can't be used for calculating BIC in general operation.
reg.bic(fit,w)
reg.bic(fit,w)
fit |
:the outcome of lm.fit |
w |
:wright |
X <- as.matrix(cbind(1,EuStockMarkets[,1:2])) # create the design matrix Y <- as.data.frame(EuStockMarkets)$FTSE fit <- lm.fit(x = X, y = Y) w <- rep(1,length(Y)) reg.bic(fit,w)
X <- as.matrix(cbind(1,EuStockMarkets[,1:2])) # create the design matrix Y <- as.data.frame(EuStockMarkets)$FTSE fit <- lm.fit(x = X, y = Y) w <- rep(1,length(Y)) reg.bic(fit,w)
Calculate degree of freedom for the outcome of lm.fit(). This function is built for reg.linreg for higher efficiency only. It can't be used for calculating degree of freedom in general operation.
reg.dof(fit)
reg.dof(fit)
fit |
:outcome of lm.f |
X <- as.matrix(cbind(1,EuStockMarkets[,1:2])) # create the design matrix Y <- as.data.frame(EuStockMarkets)$FTSE fit <- lm.fit(x = X, y = Y) reg.dof(fit)
X <- as.matrix(cbind(1,EuStockMarkets[,1:2])) # create the design matrix Y <- as.data.frame(EuStockMarkets)$FTSE fit <- lm.fit(x = X, y = Y) reg.dof(fit)
Performs the Durbin-Watson Test for a regression model
reg.dw(fit)
reg.dw(fit)
fit |
:a lm object |
fit <- lm(mpg~wt, mtcars, na.action = na.omit) reg.dw(fit)
fit <- lm(mpg~wt, mtcars, na.action = na.omit) reg.dw(fit)
This function will take a data frame and the dependent variable and fit all possible combinations of models. The result will be a data frame of models and test statistics for all the models possible. The test statistics are current set and contain all the following: R-squared, Adjusted R-squared, Degree of freedom, Residual standard error, AIC, BIC, Durbin-Watson statistic.
reg.linreg(dataframe,dependent)
reg.linreg(dataframe,dependent)
dataframe |
:a data frame, which includes the dependent variable |
dependent |
:dependent variable |
reg.linreg(mtcars,"mpg")
reg.linreg(mtcars,"mpg")
This function will take a data frame and generate all the combinations of linear model
reg.model(dataframe,dependent)
reg.model(dataframe,dependent)
dataframe |
:a data frame |
dependent |
: dependent variable |
reg.model(mtcars,"mpg")
reg.model(mtcars,"mpg")
Calculate R-squared for the outcome of lm.fit(). This function is built for reg.linreg for higher efficiency only. It can't be used for calculating R-squared in general operation.
reg.r.squared(SSR,SSTO)
reg.r.squared(SSR,SSTO)
SSR |
:regression sum of squares or explained of squares |
SSTO |
:total sum of squares |
X <- as.matrix(cbind(1,EuStockMarkets[,1:2])) # create the design matrix Y <- as.data.frame(EuStockMarkets)$FTSE fit <- lm.fit(x = X, y = Y) me <- mean(Y) SSR <- sum((fit$fitted.values - me)^2) SSTO <- sum((Y - me)^2) reg.r.squared(SSR,SSTO)
X <- as.matrix(cbind(1,EuStockMarkets[,1:2])) # create the design matrix Y <- as.data.frame(EuStockMarkets)$FTSE fit <- lm.fit(x = X, y = Y) me <- mean(Y) SSR <- sum((fit$fitted.values - me)^2) SSTO <- sum((Y - me)^2) reg.r.squared(SSR,SSTO)
Calculate standard error for the outcome of lm.fit(). This function is built for reg.linreg for higher efficiency only. It can't be used for calculating standard error in general operation.
reg.std.err(SSE,dof)
reg.std.err(SSE,dof)
SSE |
:error sum of squared aka. residual sum of squared |
dof |
:degree of freedom |
X <- as.matrix(cbind(1,EuStockMarkets[,1:2])) # create the design matrix Y <- as.data.frame(EuStockMarkets)$FTSE fit <- lm.fit(x = X, y = Y) SSE <- sum((Y - fit$fitted.values)^2) dof <- reg.dof(fit) reg.std.err(SSE,dof)
X <- as.matrix(cbind(1,EuStockMarkets[,1:2])) # create the design matrix Y <- as.data.frame(EuStockMarkets)$FTSE fit <- lm.fit(x = X, y = Y) SSE <- sum((Y - fit$fitted.values)^2) dof <- reg.dof(fit) reg.std.err(SSE,dof)
Generate sigmoid curve series, which is a specific case of logistic function, with a control of top and bottom acceleration.
tr.log(x,top,a,b)
tr.log(x,top,a,b)
x |
:a numeric vector |
top |
:a numeric value as vertical scaler |
a |
:a number to control top acceleration of the curve |
b |
:a number to control bottom acceleration of the curve |
sigc <- round(tr.log(seq(-3, 3, 0.1), 1, -3, 3), 3) ts.plot(sigc)
sigc <- round(tr.log(seq(-3, 3, 0.1), 1, -3, 3), 3) ts.plot(sigc)
Generate logistic series, with set top and bottom value and acceleration.
tr.logtb(x,top,bot,a,b)
tr.logtb(x,top,bot,a,b)
x |
:a vector |
top |
:higher level y asymptote |
bot |
:lower level y asymptote |
a |
:a number to control top acceleration of the curve |
b |
:a number to control bottom acceleration of the curve |
tr.logtb(seq(-3, 3, 0.1), 1, 0.4, -3, 3)
tr.logtb(seq(-3, 3, 0.1), 1, 0.4, -3, 3)
Calculate normal density function value at x with a mean of mu and standard deviation of sig.
tr.nd(x,mu,sig)
tr.nd(x,mu,sig)
x |
:x value |
mu |
:mean value |
sig |
:standard deviation |
tr.nd(seq(-3, 3, 0.1), 0, 1)
tr.nd(seq(-3, 3, 0.1), 0, 1)
Compute the value of the unit normal loss integral, with discontinuity and dispersion
tr.unli(x,disc,disp)
tr.unli(x,disc,disp)
x |
:a vector |
disc |
:discontinuity |
disp |
:dispersion |
tr.unli(-3:10, 1, 3)
tr.unli(-3:10, 1, 3)
This function returns a data from the Federal Reserve Bank of St. Louis database. It can take one ticker or a string of tickers, which will output a merged data frame with all observations.
xd.fred(tkr, start_date, end_date)
xd.fred(tkr, start_date, end_date)
tkr |
:one data ticker or a string of tickers used by the database |
start_date |
:starting date of the data(default is set as 1900-01-01) |
end_date |
:ending date of the data(default is set as 2018-01-01) |
cpi <- xd.fred("CPIAUCSL") # CPI data head(cpi) tail(cpi) #Frequently used tickers: #CPIAUCSL: Consumer Price Index for All Urban Consumers: All Items #A191RL1Q225SBEA: Real Gross Domestic Product #DGS10: 10-Year Treasury Constant Maturity Rate #UNRATE: Civilian Unemployment Rate
cpi <- xd.fred("CPIAUCSL") # CPI data head(cpi) tail(cpi) #Frequently used tickers: #CPIAUCSL: Consumer Price Index for All Urban Consumers: All Items #A191RL1Q225SBEA: Real Gross Domestic Product #DGS10: 10-Year Treasury Constant Maturity Rate #UNRATE: Civilian Unemployment Rate
This function returns a data contains information of data name, type and tickers
xd.fred.tickers()
xd.fred.tickers()
xd.fred.tickers()
xd.fred.tickers()