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

Chapter 1. Financial Markets, Prices and Risk

R and Python

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
Download S&P500 data in R
price = read.csv('index.csv')
y=diff(log(price$Index))  # calculate returns
plot(y)             # plot returns
Listing 1.1/1.2
Download S&P500 data in Python
import numpy as np
import matplotlib.pyplot as plt
price = np.loadtxt('index.csv', delimiter = ',', skiprows = 1)
y = np.diff(np.log(price), n=1, axis=0)
plt.plot(y)
plt.title("S&P500 Returns")
plt.show()
plt.close()

Listing 1.3/1.4
Sample statistics in R
library(moments)
library(tseries)
mean(y)
sd(y)
min(y)
max(y)
skewness(y)
kurtosis(y)
jarque.bera.test(y)
Listing 1.3/1.4
Sample statistics in Python
from scipy import stats
print (np.mean(y))
print (np.std(y, ddof=1))
print (np.min(y))
print (np.max(y))
print (stats.skew(y))
print (stats.kurtosis(y, fisher = False))
print (stats.jarque_bera(y))

Listing 1.5/1.6
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"))
Listing 1.5/1.6
ACF plots and the Ljung-Box test in Python
import statsmodels.api as sm
import matplotlib.pyplot as plt
from statsmodels.stats.diagnostic import acorr_ljungbox
q = sm.tsa.stattools.acf(y, nlags=20)
plt.bar(x = np.arange(1,len(q)), height = q[1:])
plt.title("Autocorrelation of returns")
plt.show()
plt.close()
q = sm.tsa.stattools.acf(np.square(y), nlags=20)
plt.bar(x = np.arange(1,len(q)), height = q[1:])
plt.title("Autocorrelation of returns squared")
plt.show()
plt.close()
print (acorr_ljungbox(y, lags=20))
print (acorr_ljungbox(np.square(y), lags=20))

Listing 1.7/1.8
QQ plots in R
library(car)
par(mfrow=c(1,2), pty="s")
qqPlot(y)
qqPlot(y,distribution="t",df=5)
Listing 1.7/1.8
QQ plots in Python
from statsmodels.graphics.gofplots import qqplot
fig1 = qqplot(y, line='q', dist = stats.norm, fit = True)               
plt.show()
plt.close()
fig2 = qqplot(y, line='q', dist = stats.t, distargs=(5,), fit = True)
plt.show()
plt.close()

Listing 1.9/1.10
Download stock prices in R
p = read.csv('stocks.csv')
y=apply(log(p),2,diff)
print(cor(y)) # correlation matrix
Listing 1.9/1.10
Download stock prices in Python
p = np.loadtxt('stocks.csv',delimiter=',',skiprows = 1)
y = np.diff(np.log(p), n=1, axis=0)
print(np.corrcoef(y, rowvar=False)) # correlation matrix


Financial Risk Forecasting
Market risk forecasting with R, Julia, Python and Matlab. Code, lecture slides, implementation notes, seminar assignments and questions.
© All rights reserved, Jon Danielsson,