# Chapter 1. Financial Markets, Prices and Risk

Copyright 2016 Jon Danielsson. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at. http://www.apache.org/licenses/LICENSE-2.0. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
The original 2011 R code will not fully work on a recent R because there have been some changes to libraries. The latest version of the Matlab code only uses functions from Matlab toolboxes.
##### Listing 1.1: Download S&P-500 data in R Last edited: August 2016

library(tseries)
library(zoo)
price = get.hist.quote(instrument = "^gspc", start = "2000-01-01", quote="AdjClose")
y=diff(log(price))
plot(y)
y=coredata(y)

##### Listing 1.2: Download S&P-500 data in Matlab Last edited: August 2016

price = hist_stock_data('01012000','30082016','^gspc');
y=diff(log(price.Close(end:-1:1)))
plot(y)

##### Listing 1.3: Sample statistics in R Last edited: August 2016

library(moments)
mean(y)
sd(y)
min(y)
max(y)
skewness(y)
kurtosis(y)
acf(y,1)
acf(y^2,1)
jarque.bera.test(y)
Box.test(y, lag = 20, type = c("Ljung-Box"))
Box.test(y^2, lag = 20, type = c("Ljung-Box"))

##### Listing 1.4: Sample statistics in Matlab Last edited: August 2016

mean(y)
std(y)
min(y)
max(y)
skewness(y)
kurtosis(y)
[h,pValue,stat]=lbqtest(y,20)
[h,pValue,stat]=lbqtest(y.^2,20)
[h,pValue,stat]=lbqtest(y,'lags',20)
[h,pValue,stat]=lbqtest(y.^2,'lags',20)

##### Listing 1.5: ACF plots and the Box-Ljung test in R Last edited: August 2016

library(MASS)
library(stats)
q = acf(y,20)
q1 = acf(y^2,20)
plot(q,main="ACF of daily returns")
plot(q1,main="ACF of squared daily returns")

##### Listing 1.6: ACF plots and the Box-Ljung test in Matlab Last edited: August 2016

autocorr(y,'numLags',20)
autocorr(y.^2,'numLags',20)

##### Listing 1.7: QQ plots in R Last edited: August 2016

library(car)
qqPlot(y)
qqPlot(y,distribution="t",df=5)

##### Listing 1.8: QQ plots in Matlab Last edited: 2011

qqplot(y)

price1 = get.hist.quote(instrument = c("msft"),start = "2007-06-01",end = "2009-12-31",quote="AdjClose")
price2 = get.hist.quote(instrument = c("ms"),  start = "2007-06-01",end = "2009-12-31",quote="AdjClose")
price3 = get.hist.quote(instrument = c("GS"),  start = "2007-06-01",end = "2009-12-31",quote="AdjClose")
p=cbind(price1,price2,price3)
y=diff(log(p))
print(cor(y))