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


Copyright 2011 - 2022 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&P500 data in Python
Last updated July 2020

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.1/1.2: Download S&P 500 data in Julia
Last updated June 2022

using CSV, DataFrames;
price = CSV.read("index.csv",DataFrame)
y = diff(log.(price[:,1]))
using Plots;
plot(y, title = "S&P500 returns", legend = false)
		

Listing 1.3/1.4: Sample statistics in Python
Last updated July 2020

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.3/1.4: Sample statistics in Julia
Last updated July 2020

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))
		

Listing 1.5/1.6: ACF plots and the Ljung-Box test in Python
Last updated July 2020

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.5/1.6: ACF plots and the Ljung-Box test in Julia
Last updated July 2020

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)
		

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

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.7/1.8: QQ plots in Julia
Last updated July 2020

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: Download stock prices in Python
Last updated July 2020

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
## rowvar=False indicates that columns are variables
		
Listing 1.9/1.10: Download stock prices in Julia
Last updated June 2022

price = CSV.read("stocks.csv", DataFrame)
y1 = diff(log.(price[:,1]))
y2 = diff(log.(price[:,2]))
y3 = diff(log.(price[:,3]))
y = hcat(y1,y2,y3)
println(cor(y)) # correlation matrix