Category Archives: Crash courses

Course on “Big Data for Economics”

In July, I will give a lecture at the 2018 edition of the Summer School at the UB School of Economics, in Barcelona. It will be a four day crash course. Registration should be opened.

Lecture 1: Introduction : Why Big Data brings New Questions
Lecture 2: Simulation Based Techniques & Bootstrap
Lecture 3: Loss Functions : from OLS to Quantile Regression
Lecture 4: Nonlinearities and Discontinuities
Lecture 5: Cross-Validation and Out-of-Sample diagnosis
Lecture 6: Variable and model selection
Lecture 7: New Tools for Classification Problems
Lecture 8: New Tools for Time Series & Forecasting

Devoir, Méthodes de Prévisions (consommation électrique)

Pour le projet de l’UE de prévision, je demande une prévision de la consommation d’électricité. Pour construire les modèles, je donne accès à un gros fichier qui donne, pour toute la France, la consommation d’électricité, entre 2012 et 2014, heure par heure.

  • comme en cours, la première étape sera de proposer une série de 52 prévisions pour chaque semaine de 2015,
  • la seconde étape sera de proposer deux séries de 31 prévisions, pour chaque jour d’août 2015 et de décembre 2015
  • enfin, la dernière étape sera une prévision de 168 prévisions, pour chaque heure de la semaine du 19 au 25 octobre 2015

Pour aider (?), je mets un lien vers la température en France  dans quelques villes, paris, toulouse, grenoble, nantes, dunkerque (via ftp.ncdc.noaa.gov). Il sera possible d’utiliser la vraie température de 2015 pour faire les prévisions de consommation électrique.  Idéalement, je veux un fichier html (markdown) et 4 fichiers csv avec les 4 séries de prévision.

Consommation et production électrique

Une version temporaire des slides est en ligne. Pour le TP, on continuera à utiliser les données suivante

url="http://freakonometrics.free.fr/elec.RData"
download.file(url,"elec.RData")
load("elec.RData")
k=620
n=nrow(electricite)
passe=1:k
futur=(k+1):n
y=electricite$Load[passe]
plot(y,type="l")

La semaine passée, nous avions commencé de modéliser la série de température (cette dernière ayant un impact important comme déterminant de la consommation électrique)

y=electricite$Temp[passe]
plot(y,type="l")
Y=ts(y,start=1996,frequency=52)
library(forecast)

plot(y[(53:k)-52],y[53:k])
abline(lm(y[53:k]~y[(53:k)-52]),col="red")
abline(a=0,b=1,lty=2)

La série temporelle est relativement autocorrélée, à l’ordre 52

acf(y,lag=120)

model1=auto.arima(Y)
acf(residuals(model1),120)

On va garder ce modèle en mémoire, et regarder par la suite ses prévisions. Tentons ici un SARIMA, à la main

model2=arima(Y,order = c(0,0,0), 
seasonal = list(order = c(1,0,0)))
summary(model2)
model2=arima(Y,order = c(0,0,0), 
seasonal = list(order = c(2,0,0)))
summary(model2)
acf(residuals(model2),120)
model2=arima(Y,order = c(2,0,0), 
seasonal = list(order = c(1,0,0)))            
model2=arima(Y,order = c(1,0,0), 
seasonal = list(order = c(1,1,0)))
summary(model2)
acf(residuals(model2),120)

Tentons ensuite avec une racine unité saisonnière

Z=diff(Y,52)
model3=arima(Z,order = c(0,0,1), 
seasonal = list(order = c(0,0,1)))
summary(model3)
model3=arima(Z,order = c(0,0,2), 
seasonal = list(order = c(0,0,1)))
summary(model3)
acf(residuals(model3),120)
model3=arima(Y,order = c(0,0,2), 
seasonal = list(order = c(0,1,1)))
summary(model3)

On peut ensuite tenter un modèle à la Buys-Ballot

reg=lm(Temp~0+as.factor(NumWeek),
data=electricite[passe,])
cycle=predict(reg,newdata=electricite[passe,])
plot(y,type="l")
lines(cycle,col="red")
E=residuals(reg)
plot(E,type="l")
acf(E,120)
model4=arima(E,order = c(1,0,0))
summary(model4)

horizon=n-k
prev4E=predict(model4,n.ahead = horizon)$pred
prev4C=predict(reg,newdata=electricite[futur,])
prev4 =prev4E+prev4C
plot(y,type="l",xlim=c(0,n))
abline(v=k,col="red")
lines(prev4,col="blue")

prev1=predict(model1,n.ahead = horizon)$pred
plot(y,type="l",xlim=c(0,n))
abline(v=k,col="red")
lines(futur,prev1,col="purple")

prev2=predict(model2,n.ahead = horizon)$pred
plot(y,type="l",xlim=c(0,n))
abline(v=k,col="red")
lines(futur,prev2,col="green")

prev3=predict(model3,n.ahead = horizon)$pred
plot(y,type="l",xlim=c(0,n))
abline(v=k,col="red")
lines(futur,prev3,col="orange")

MODELES = data.frame(y1=prev1,
y2=prev2,y3=prev3,y4=prev4, 
y =electricite$Temp[futur])
plot(MODELES$y,type="l")
lines(1:111,MODELES$y1,col="purple")
lines(1:111,MODELES$y2,col="green")
lines(1:111,MODELES$y3,col="orange")
lines(1:111,MODELES$y4,col="blue")

 

Optimal Portfolios Exam

Pour l’examen du cours de Gestion d’Actifs (optimal portfolios) un cas pratique avec des vraies données, disponibles sur

loc="http://freakonometrics.free.fr/base_portefeuille.csv"
base=read.csv2(loc,sep=";")
base[,1]=as.Date(as.character(base[,1]),"%Y-%m-%d")
for(i in 2:10) base[,i]=as.numeric(as.character(base[,i]))

Pour le rendu, je demande un markdown dont la trame est en ligne ici,  exam_portfolio.Rmd, et la sortie est exam_portfolio.html. Il faut télécharger le fichier Rmd, l’ouvrir avec RStudio, puis me renvoyer le fichier rempli (ainsi que le fichier html compilé) pour midi, à arthur.charpentier@univ-rennes1.fr.

Optimal Portfolios, or sort of…

Last week, we got our first class on portfolio optimization. We’ve seen Markowitz’s theory where expected returns and the covariance matrix are given,

> download.file(url="http://freakonometrics.free.fr/portfolio.r",destfile = "portfolio.r")
> source("portfolio.r")
> library(zoo)
> library(FRAPO)
> library(IntroCompFinR)
> library(rrcov)
> data( StockIndex )
> pzoo = zoo ( StockIndex , order.by = rownames ( StockIndex ) )
> rzoo = ( pzoo / lag ( pzoo , k = -1) - 1 ) * 100
> Moments <- function ( x , method = c ( "CovClassic" , "CovMcd" , "CovMest" , "CovMMest" , "CovMve" , "CovOgk" , "CovSde" , "CovSest" ) , ... ) {
method <- match.arg ( method )
ans <- do.call ( method , list ( x = x , ... ) ) + return ( getCov ( ans ) )} > covmat=Moments(as.matrix(rzoo),"CovClassic")
> (covmat=round(covmat,1))
SP500 N225 FTSE100 CAC40 GDAX HSI
SP500   17.8 12.7 13.8 17.8 19.5 18.9
N225    12.7 36.6 10.8 15.0 16.2 16.7
FTSE100 13.8 10.8 17.3 18.8 19.4 19.1
CAC40   17.8 15.0 18.8 30.9 29.9 22.8
GDAX    19.5 16.2 19.4 29.9 38.0 26.1
HSI     18.9 16.7 19.1 22.8 26.1 58.1
> er=apply(as.matrix(rzoo),2,mean)
> (er=round(er,1))
SP500 N225 FTSE100 CAC40 GDAX HSI
0.6 -0.2 0.4 0.5 0.8 1.0
> ef <- efficient.frontier(er, covmat, alpha.min=-2.5, alpha.max=2.5, nport=50)

We can now visualize the efficient frontier (and admissible portfolios) below

> u=c(12,ef$sd,12,12)
> v=c(5,ef$er,-1,5)
> plot(ef$sd,ef$er,type="l",xlab="Standard Deviation",ylab="Expected Return", xlim=c(3.5,11),ylim=c(0,2.5),col="red",lwd=1.5)
> points(sqrt(diag(covmat)),er,pch=19,col="blue")
> text(sqrt(diag(covmat)),er,names(er),pos=4, col="blue",cex=.6)
> polygon(u,v,border=NA,col=rgb(0,0,1,.3))

https://freakonometrics.hypotheses.org/files/2017/11/image-voronoi-post-026-1.png

That was the starting point of our class. We did also mention that something important was actually hard to visualize on that graph : the correlation between returns. It is not in the points (which are univariate, with expected return and standard deviation), but in the efficient frontier. For instance, here is our correlation matrix

> (cormat=covmat/(sqrt(diag(covmat) %*% t(diag(covmat)))))
SP500 N225 FTSE100 CAC40 GDAX HSI
SP500   1.00 0.50 0.79 0.76 0.75 0.59
N225    0.50 1.00 0.43 0.45 0.43 0.36
FTSE100 0.79 0.43 1.00 0.81 0.76 0.60
CAC40   0.76 0.45 0.81 1.00 0.87 0.54
GDAX    0.75 0.43 0.76 0.87 1.00 0.56
HSI     0.59 0.36 0.60 0.54 0.56 1.00

We can actually change the correlation between FT500 and FTSE100 (which is here .786)

courbe=function(r=.786){
R=cormat
R[1,3]=R[3,1]=r
covmat2=(sqrt(diag(covmat) %*% t(diag(covmat))))*R
ef <- efficient.frontier(er, covmat2, alpha.min=-2.5, alpha.max=2.5, nport=50)
plot(ef$sd,ef$er,type="l",xlab="Standard Deviation",ylab="Expected Return",
xlim=c(3.5,11),ylim=c(0,2.5),col="red",lwd=1.5)
points(sqrt(diag(covmat)),er,pch=19,col=c("blue","red")[c(2,1,2,1,1,1)])
text(sqrt(diag(covmat)),er,names(er),pos=4,col=c("blue","red")[c(2,1,2,1,1,1)],cex=.6)
polygon(u,v,border=NA,col=rgb(0,0,1,.3))
}

for instance, with a correlation of 0.6, we get the following efficient frontier

> courbe(.6)

and with a stronger correlation

> courbe(.9)

So clearly, correlation does matter. A lot. But more important, one should keep in mind that expected returns and covariances are not given, but estimated. Previously, we did use the standard estimator for the variance matrix. But another (more robust) estimator can be considered

covmat=Moments(as.matrix(rzoo),"CovSde")
er=apply(as.matrix(rzoo),2,mean)
ef <- efficient.frontier(er, covmat, alpha.min=-2.5, alpha.max=2.5, nport=50)
plot(ef$sd,ef$er,type="l",xlab="Standard Deviation",ylab="Expected Return",xlim=c(3.5,11),ylim=c(0,2.5),col="red",lwd=1.5)
points(sqrt(diag(covmat)),er,pch=19,col="blue")
text(sqrt(diag(covmat)),er,names(er),pos=4,col="blue",cex=.6)
polygon(u,v,border=NA,col=rgb(0,0,1,.3))

It did influence (horizontal) position of points, since variances are now different, as well as the efficient frontier, with clearly much lower variances that can be reached.

And to illustrate a last point, to illustrate the fact that we do have estimators based on observed returns, what if we had observed different ones? A way to get an idea of what might happened is to use bootstrap, e.g. of daily returns.

> covmat=Moments(as.matrix(rzoo),"CovClassic")
> er=apply(as.matrix(rzoo),2,mean)
> ef <- efficient.frontier(er, covmat, alpha.min=-2.5, alpha.max=2.5, nport=50) > a=sqrt(diag(covmat))
> b=er
> k=1
> plot(ef$sd,ef$er,type="l",xlab="Standard Deviation",ylab="Expected Return", xlim=c(3.5,11),ylim=c(0,2.5),col="white",lwd=1.5)
> polygon(u,v,border=NA,col=rgb(0,0,1,.3))
> for(i in 1:100){
+ id=sample(nrow(rzoo),replace=TRUE)
+ covmat=Moments(as.matrix(rzoo)[id,],"CovClassic")
+ er=apply(as.matrix(rzoo)[id,],2,mean)
+ points(sqrt(diag(covmat))[k],er[k],cex=.5)
+ }

or for another asset

Here is what we got on the (estimated) efficient frontier

> covmat=Moments(as.matrix(rzoo),"CovClassic")
> er=apply(as.matrix(rzoo),2,mean)
> ef <- efficient.frontier(er, covmat, alpha.min=-2.5, alpha.max=2.5, nport=50) > plot(ef$sd,ef$er,type="l",xlab="Standard Deviation",ylab="Expected Return", xlim=c(3.5,11),ylim=c(0,2.5),col="white",lwd=1.5)
> points(sqrt(diag(covmat)),er,pch=19,col="blue")
> text(sqrt(diag(covmat)),er,names(er),pos=4, col="blue",cex=.6)
> polygon(u,v,border=NA,col=rgb(0,0,1,.3))
> for(i in 1:100){
+ id=sample(nrow(rzoo),replace=TRUE)
+ covmat=Moments(as.matrix(rzoo)[id,],"CovClassic")
+ er=apply(as.matrix(rzoo)[id,],2,mean)
+ ef <- efficient.frontier(er, covmat, alpha.min=-2.5, alpha.max=2.5, nport=50)
+ lines(ef$sd,ef$er,col="red")
+ }

Thus, it is somehow rather difficult to assess wheter a portfolio is optimal, or not… At least from a statistical perspective….

Optimal Portfolios #1

This afternoon, I will start a crash course on financial portfolio optimization, with application in R. This week, we start with simple things, with the theoretical setup, without and with a risk free asset. We will discuss then the problem of estimating parameters, in a robust way. Then we introduce the idea of consider a more general criteria to quantify risk than the variance (but it means more general distributions… this point will be discussed further next time). The slides are available here, and R codes from there (in a Markdown)

Graduate Course on Advanced Methods in Econometrics

I will give a short graduate course for PhD students, in Rennes, on Thurday mornings, in March (2nd, 9th, 23rd and 30th). The agenda will be

  1. Nonlinear Regression Models and Smoothing Techniques

  2. Bootstrapping and Regression

  3. Penalized Regression Models and LASSO

  4. Quantile Regression and Expectiles

There will be slides available by the end of February.

 

Supports de cours en R

Lundi, second cours de R pour la formation Actuaire: Data Science. Pour la première fois, je quitte mon format de slides (au format pdf) pour autre chose. Plus pratique pour présenter du code R. Une solution est de passer par R Markdown, et plus spécifiquement Slidify (qui permet de créer des slides)

On a un document, dans l’éditeur de RStudio, et la structure est assez simple. On a un préambule, et ensuite du texte,

C’est du Markdown, tout simplement. Mais on peut aussi mettre du code R, pour générer des tableaux, des sorties, des graphes,

Ensuite, au  lieu de faire run pour exécuter le code, on utilise Knit HTML, qui va permettre de générer les slides

Plus précisément, ces derniers vont s’ouvrir dans une fenêtre RStudio, mais qu’on peut aussi visualiser dans un browser,

C’est  avec ces fonctions que les slides ont été générés.

Une autre solution est de passer par Jupyter. L’installation prend un peu de temps (mais c’est relativement bien documenté). En lançant Jupyter, on crée un notebook en R,

Par défaut, on a un premier bloc de lignes de commandes

Pour en rajouter avant, ou après, rien de plus simple

On a alors un second blog, après l’affichage d’une sortie de régression, afin de générer un graphique

On peut soit garder les instructions, telles quelles, soit les exécuter, afin de visualiser les sorties

qui peuvent être des sorties de régression, ou des graphiques

On peut aussi insérer des blocs qui seront un Markdown (du texte, quoi), et pas seulement du code

On peut par exemple insérer un ‘titre’ de section

Et là encore, on exécute, pour afficher.

Cette année, pour mon cours de R, j’ai opté pour Slidify, mais peut être que Jupyter pourrait être une alternative intéressante, pour rendre le cours plus interactif. On en reparlera…

R Crash Course, Data Science for Actuaries, Year 2

This Monday, we will start the second year of the Actuary: Data Science (ADS) program, supported by the (French) Institute of Actuaries. I will be there on monday morning for the opening, and we will start the R & Datamining course. The slides are now online,

In order to get nice slides, I have been using slidify. The R code is available online, as well as some pdf version of the slides.