R and Matlab Chapter 1. Financial Markets, Prices and Risk

# Chapter 1. Financial Markets, Prices and Risk

### R and Matlab

Copyright 2011 - 2023 Jon Danielsson. This code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This code 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 General Public License for more details. The GNU General Public License is available at: www.gnu.org/licenses.

##### Listing 1.1/1.2
price = read.csv('index.csv')
y=diff(log(price\$Index))  # calculate returns
plot(y)             # plot returns

##### Listing 1.1/1.2
price = csvread('index.csv', 1, 0);
y=diff(log(price)); % calculate returns
plot(y)             % plot returns
title("S&P500 returns")


##### Sample statistics in R
library(moments)
library(tseries)
mean(y)
sd(y)
min(y)
max(y)
skewness(y)
kurtosis(y)
jarque.bera.test(y)

##### % Sample statistics in MATLAB
mean(y)
std(y)
min(y)
max(y)
skewness(y)
kurtosis(y)
[h,pValue,stat]=jbtest(y);


##### ACF plots and the Ljung-Box test in R
library(MASS)
library(stats)
par(mfrow=c(1,2), pty="s")
q = acf(y,20)
q1 = acf(y^2,20)
Box.test(y, lag = 20, type = c("Ljung-Box"))
Box.test(y^2, lag = 20, type = c("Ljung-Box"))

##### % ACF plots and the Ljung-Box test in MATLAB
subplot(1,2,1)
autocorr(y, 20)
subplot(1,2,2)
autocorr(y.^2, 20)
[h,pValue,stat]=lbqtest(y,'lags',20);
[h,pValue,stat]=lbqtest(y.^2,'lags',20);


##### QQ plots in R
library(car)
par(mfrow=c(1,2), pty="s")
qqPlot(y)
qqPlot(y,distribution="t",df=5)

##### % QQ plots in MATLAB
subplot(1,2,1)
qqplot(y)
subplot(1,2,2)
qqplot(y, fitdist(y,'tLocationScale'))


##### Listing 1.9/1.10
p = read.csv('stocks.csv')
y=apply(log(p),2,diff)
print(cor(y)) # correlation matrix

##### Listing 1.9/1.10
price = csvread('stocks.csv', 1, 0);