# Chapter 1. Financial Markets, Prices and Risk (in MATLAB/Julia)

Copyright 2011 - 2019 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: https://www.gnu.org/licenses/.

##### Listing 1.1/1.2: Download S&P 500 data in MATLAB Last updated August 2016

y=diff(log(price));                 % calculate returns
plot(y)                             % plot returns

##### Listing 1.1/1.2: Download S&P 500 data in Julia Last updated June 2018

using CSV;
price = CSV.read("index.csv", nullable = false);
y = diff(log.(price[:,1]));
using Plots;
plot(y)


##### Listing 1.3/1.4: Sample statistics in MATLAB Last updated June 2018

%% the function sacf uses Kevin Sheppard's MFE toolbox
mean(y)
std(y)
min(y)
max(y)
skewness(y)
kurtosis(y)
sacf(y,1,[],0)
sacf(y.^2,1,[],0)
[h,pValue,stat]=jbtest(y);
[h,pValue,stat]=lbqtest(y,'lags',20);
[h,pValue,stat]=lbqtest(y.^2,'lags',20);
%% NOTE: in MATLAB 2018a, some functions require name-value pairs
%% e.g. MATLAB 2016a: [h,pValue,stat] = lbqtest(y,20)

##### Listing 1.3/1.4: Sample statistics in Julia Last updated June 2018

using StatsBase;
println(std(y))
println(minimum(y))
println(maximum(y))
println(skewness(y))
println(kurtosis(y))
println(autocor(y, 1:20))
println(autocor(y.^2, 1:20))
using HypothesisTests;
println(JarqueBeraTest(y))
println(LjungBoxTest(y,20))
println(LjungBoxTest(y.^2, 20))


##### Listing 1.5/1.6: ACF plots and the Ljung-Box test in MATLAB Last updated August 2016

%% subplots here are just for ease of visualization
subplot(1,2,1)
autocorr(y, 20)
subplot(1,2,2)
autocorr(y.^2, 20)

##### Listing 1.5/1.6: ACF plots and the Ljung-Box test in Julia Last updated June 2018

using Plots;
q1 = autocor(y, 1:20)
q2 = autocor(y.^2, 1:20)
plot(bar(q1), bar(q2))


##### Listing 1.7/1.8: QQ plots in MATLAB Last updated 2011

%% subplots here are just for ease of visualization
subplot(1,2,1)
qqplot(y)
subplot(1,2,2)
qqplot(y, fitdist(y,'tLocationScale'))

##### Listing 1.7/1.8: QQ plots in Julia Last updated June 2018

using Plots, StatPlots, Distributions;
plot(qqplot(Normal,float(y),qqline=:quantile), qqplot(TDist(5),float(y),qqline=:quantile))