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

# Chapter 1. Financial Markets, Prices and Risk

### Matlab and Julia

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 = csvread('index.csv', 1, 0);
y=diff(log(price)); % calculate returns
plot(y)             % plot returns
title("S&P500 returns")

##### Listing 1.1/1.2
using CSV
using DataFrames;
y = diff(log.(price[:,1]))
using Plots;
plot(y, title = "S&P500 returns", legend = false)


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

##### Sample statistics in Julia
using Statistics, StatsBase;
println("Standard deviation: ", std(y), "\n")
println("Minimum value: ", minimum(y), "\n")
println("Maximum value: ", maximum(y), "\n")
println("Skewness: ", skewness(y), "\n")
println("Kurtosis: ", kurtosis(y), "\n")
println("Autocorrelation of returns:", "\n", autocor(y, 1:20), "\n")
println("Autocorrelation of returns squared:", "\n", autocor(y.^2, 1:20), "\n")
using HypothesisTests;
println(JarqueBeraTest(y))
println(LjungBoxTest(y,20))
println(LjungBoxTest(y.^2, 20))


##### % 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);

##### ACF plots and the Ljung-Box test in Julia
q1 = autocor(y, 1:20)
q2 = autocor(y.^2, 1:20)
plot(bar(q1, title = "ACF of returns"),
bar(q2, title = "ACF of returns squared"), legend = false)


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

##### QQ plots in Julia
using StatsPlots, Distributions;
plot(qqplot(Normal,float(y),qqline=:quantile, title = "QQPlot vs Normal"),
qqplot(TDist(5),float(y),qqline=:quantile, title = "QQPlot vs Student-t(5)"),
qqplot(TDist(4),float(y),qqline=:quantile, title = "QQPlot vs Student-t(4)"),
qqplot(TDist(3),float(y),qqline=:quantile, title = "QQPlot vs Student-t(3)"))


##### Listing 1.9/1.10
price = csvread('stocks.csv', 1, 0);
y=diff(log(price));
corr(y) % correlation matrix

##### Listing 1.9/1.10
price = CSV.read("stocks.csv", DataFrame)