SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Financial markets
modeling in R

Arbuzov V.

Perm State National Research
University

arbuzov@prognoz.ru
20 November 2013

Perm R group
r-group.mifit.ru

ITE.LAB “MathEconomics” Open Course
Russia, Perm, 20 November 2013

workshop
Basic knowledgement
about R
3

R console
Coding
Simple
calculation
4+3
5-1
4*6
10/2
2^10
9%%2
9%/%2
abs(-1)
exp(1)
sqrt(25)
sin(1)
pi
cos(pi)
sign(-106)
log(1)

Mathematical functions in R
Coding
x<-1:10
Coding
Useful commands
to create a vector
1:10
seq(1,10)
rep(1,10)
working with vectors
A<-1:10
B<-c(2,4,8)
A*B
A>B

assignment operator
<- or ->
x<-10
10->X
case sensitive
X
x

R is a case sensitive language. FOO, Foo, and foo are three
different objects!
Coding

Matrix
y <- matrix(nrow=2,ncol=2)
y[1,1] <- 1
y[2,1] <- 2
y[1,2] <- 3
y[2,2] <- 4
x <- matrix(1:4, 2, 2)

A matrix is a vector
with two additional
attributes: the
number of rows and
the
number of columns

Matrix Operations
x %*% y
x* y
3*y
x+y
x+3
x[,2]
x[1,]
rbind(x,y)->z
cbind(x,y)
z[1:2,]
z[z[,1]>1,]
z[which(z[,1]>1),1]
Coding
Data Frame

List

kids <- c("Jack","Jill")
ages <- c(12,10)
d <- data.frame(kids,ages)
d[1,]
d[,1]
d[[1]]

j <- list(name="Joe", salary=55000, union=T)
j$salary
j[["salary"]]
j[[2]]
j$name [2]<-”Poll”
j$salary[2]<-10000
j$union [2]<-”F”
Arrays
In contrast to a
vector, in which all
elements
must be of the same
mode, R’s list
structure can
combine objects of
different
types.

my.array <- array(1:24, dim=c(3,4,2))

a data frame is like a
matrix, with a two-dimensional rowsandcolumns
structure. However, it differs from
a matrix in that each column may have a
different
mode.
Coding
Loops
for
x <- c(5,12,13)
for (n in x) print(n^2)

for (i in 1:10)
{
x<-i*3
cos(x)->x
print(x)
}

if-else
i<-3
if (i == 4) x <- 1 else x <- 3

while
i <- 1
while (i <= 10) i <- i+4
i <- 1
while (i <= 10)
{
x<-i*3
cos(x)->x
print(c(x,i))
i <- i+1
}
Import/Export data
Import from text files or csv
mydata <read.table("d:/my.data.txt", header=TRUE
,
sep=",")
Import from Excel
library(xlsx)
mydata<-read.xlsx("d:/my.data.xlsx",1)
Exporting Data
write.table(mydata, "c:/mydata.txt", sep="t")

write.xlsx(mydata, "c:/mydata.xls")
Import/Export Data to clipboard
read.table("clipboard",sep="t")
write.table(arg1,"clipboard",sep="t")

rb <- function(arg1){read.table("clipboard",sep="t")}

P.S. cb <- function(arg1){write.table(arg1,"clipboard",sep="t")}
Basic Graphs

Creating a Graph
attach(mtcars)
plot(wt, mpg)
abline(lm(mpg~wt))
title("Regression of MPG on Weight")

Bar Plot
counts <- table(mtcars$gear)
barplot(counts, main="Car Distribution",
xlab="Number of Gears")

Pie Charts

Boxplot

slices <- c(10, 12,4, 16, 8)
lbls <c("US", "UK", "Australia", "Germany",
"France")
pie(slices, labels = lbls, main="Pie
Chart of Countries")

boxplot(mpg~cyl,data=mtcars, mai
n="Car Milage Data",
xlab="Number of Cylinders",
ylab="Miles Per Gallon")
Advanced
knowledgement
about R
Select data from matrix
x <- matrix(0,50,2)
x[,1]
x[1,]
x[,1]<-rnorm(50)
x
x[1,]<-rnorm(2)
x
x <- matrix(rnorm(100),50,2)
x[which(x[,1]>0),]
Operators
and
&
or
|
Distributions
Basic distributions in R

Beta

?beta

Binomial

?binom

Cauchy

?cauchy

Chi-squared

?chisq

Exponential

?exp

F

?f

Gamma

?gamma

Geometric

?geom

Hypergeometric

?hyper

Log-normal

?lnorm

Multinomial

?multinom

Negative binomial

?nbinom

Normal

?norm

Poisson

?pois

Student's t

?t

Uniform

?unif

Weibull

?weibull

d – density
q – quantile
r – random
Distributions

Plot density of chosen distribution…

x <- seq(-4, 4, length=100)
dx <- d?????(x)
plot(x, hx, type=“l”)

Generate random variables of chosen
distribution …

x<-rnorm(1000)
Distributions
What is this distribution ?
hist (?)
density (?)

?
Estimation of parameters
Let’s estimate parameters of
chosen distribution….
library(MASS)
fitdistr(x,"normal")

params<-fitdistr(x,"normal")$estimate
Compare theoretical and empirical
distributions…
hist(x, freq = FALSE,ylim=c(0,0.4))
curve(dnorm(x, params[1], params[2]), col = 2, add = TRUE)
Correlations

y<-rnorm(1000)
cor(x,y)
cor(x,y, ,method = ?????)
acf(y)
Linear least-squares method

x<-seq(0,10,length=1000)
y<-1+2*x+sin(x)*rnorm(1000,0,2)
plot(x,y)

How to estimate this parameters?

lm(y ~ x)
summary(lm(y ~ x))
abline(lm(y ~ x),col="red",lwd=3)
Nonlinear least-squares method

x<-seq(0,10,length=1000)
y<-2*sin(3*x)+rnorm(1000,0,0.8)

How to estimate this parameters?

help(nls)

nls(y ~ A*sin(B*x))
nls(y ~ A*sin(B*x),start=list(A=1.8,B=3.1))
Advanced graphics

Add few diagrams to graph

par(mfrow=c(2,2))
plot(rnorm(100),rbeta(100,12,1))
Add legend to graph

legend("topright", inset=.05, title="legend",
c("4","6","8"), horiz=TRUE)
Package lattice
library(lattice)

bwplot(sign(rnorm(30))~rnorm(30)|runif(3))

xyplot(rnorm(100)~rnorm(100)|rnorm(4))

cloud(y~x*y)

densityplot(rnorm(4))
Package ggplot2
qplot(rnorm(100))

qplot(rnorm(100),rnorm(100))

library(ggplot2)
qplot(rnorm(100),geom='density')

qplot(rnorm(100),rnorm(100),
size=sign(rnorm(100))+1)
Download Data
Package quantmod

Package rusquant

getSymbols("GOOG",src="yahoo",
from = "2007-01-01“, to =
Sys.Date())

getSymbols("SPFB.RTS", from="2011-0101", src="Finam“, period="hour"
, auto.assign=FALSE)

getSymbols("USD/EUR",src="oanda")

1min, 5min, 10min, 15min,
30min, hour, day, week, month
Working with package quantmod

Data visualization

Add technical indicators

barChart(AAPL)
candleChart(AAPL,multi.col=TRUE,theme="white")

addMACD()

chartSeries(AAPL,up.col='white',dn.col='blue')

addBBands()

Select data

AAPL['2007']
AAPL['2007-03/2007']
AAPL['/2007']
AAPL['2007-01-03']

Data management

to.weekly(AAPL)
to.monthly(AAPL)
dailyReturn(AAPL)
weeklyReturn(AAPL)
monthlyReturn(AAPL)
Load Data from Database
Package RODBC
library(RODBC)

odbcDriverConnect(“”)
channel <- odbcConnect("psu_schs",“student","Qwerty1")
sqlQuery(channel, “select * from LPPL_MODELS”)
Practice
Practice № 1. Working with data

1. AAPL
2. BAC
3. GOOG
4. GE
5. GM
6. PG
7. JNJ
8. JPM
9. LNKD
10. MSFT
11. NOK
12. IBM
13. AMZN
14. V

TASK:
a. Download Data of your instrument
b. Plot price
c. Add technical indicators
d. Calculate price returns

Commands to help :
barChart(AAPL)
chartSeries(AAPL,up.col='white',dn.col='blue')
AAPL['2007-03/2007']
addMACD()
dailyReturn(AAPL)
Practice № 2. Distribution of price returns

1. AAPL
2. BAC
3. GOOG
4. GE
5. GM
6. PG
7. JNJ
8. JPM
9. LNKD
10. MSFT
11. NOK
12. IBM
13. AMZN
14. V

TASK :
a. Download Data of your instrument
b. Calculate returns of close prices
c. Plot density of distribution
d. Estimate parameters of distribution
e. Plot in one graph empirical and theoretical
distributions

Commands to help :
getSymbols("AAPL", auto.assign=FALSE)
library(MASS)
fitdistr(x,"normal")
hist(x)
density(x)
curve(dnorm(x, params[1], params[2]), col = 2, add = TRUE)
Practice № 3. Estimation of correlation

1. AAPL
2. BAC
3. GOOG
4. GE
5. GM
6. PG
7. JNJ
8. JPM
9. LNKD
10. MSFT
11. NOK
12. IBM
13. AMZN
14. V

TASK :
a. Download Index Data (ticker: “MICEX”)
b. Download Data of your instrument
c. Calculate returns of close prices
d. Calculate correlation of returns
e. Calculate correlation of returns in 2012 year
f. Calculate correlation of returns in 2008 year
g. Calculate autocorrelation function of returns
Commands to help :
getSymbols(" MICEX ",
src="Finam", period="day" , auto.assign=FALSE)

AAPL['2007']
AAPL['2007-03/2007']
AAPL['/2007']
AAPL['2007-01-03']
Practice № 4. Volatility estimation

1. AAPL
2. BAC
3. GOOG
4. GE
5. GM
6. PG
7. JNJ
8. JPM
9. LNKD
10. MSFT
11. NOK
12. IBM
13. AMZN
14. V

TASK :
a. Download Data of your instrument
b. Calculate returns of close prices
c. Plot clusterization of volatility
d. Estimate model garch
e. garchFit(data=x) @sigma.t

Commands to help :
AAPL['2007']
AAPL['2007-03/2007']
AAPL['/2007']
AAPL['2007-01-03']
The practical task №5. Calculation of VaR

1. AAPL
2. BAC
3. GOOG
4. GE
5. GM
6. PG
7. JNJ
8. JPM
9. LNKD
10. MSFT
11. NOK
12. IBM
13. AMZN
14. V

TASK :
a. Download Data of your instrument
b. Calculate returns of close prices
c. Calculate historical VaR
d. Calculate parametric VaR
e. library(PerformanceAnalytics)
f. help(VaR)

Commands to help :
quantile(x,0.95, na.rm=TRUE)
AAPL['2007']
AAPL['2007-03/2007']
AAPL['/2007']
AAPL['2007-01-03']
The practical task № 6. Estimate LPPL model
TASK :
a. Download Nikkei Index Data(ticker: “^N225”) from June 2012 to June 2013
b. Estimate parameters of model LPPL

MODEL LPPL:

Commands to help :
help(nsl)
Q&A

arbuzov@prognoz.ru

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning ProgrammersIntroduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning ProgrammersKimikazu Kato
 
(2015 06-16) Three Approaches to Monads
(2015 06-16) Three Approaches to Monads(2015 06-16) Three Approaches to Monads
(2015 06-16) Three Approaches to MonadsLawrence Evans
 
The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)Eric Torreborre
 
Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303Namgee Lee
 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator PatternEric Torreborre
 
Statistical inference for (Python) Data Analysis. An introduction.
Statistical inference for (Python) Data Analysis. An introduction.Statistical inference for (Python) Data Analysis. An introduction.
Statistical inference for (Python) Data Analysis. An introduction.Piotr Milanowski
 
Scientific Computing with Python Webinar March 19: 3D Visualization with Mayavi
Scientific Computing with Python Webinar March 19: 3D Visualization with MayaviScientific Computing with Python Webinar March 19: 3D Visualization with Mayavi
Scientific Computing with Python Webinar March 19: 3D Visualization with MayaviEnthought, Inc.
 
Q plot tutorial
Q plot tutorialQ plot tutorial
Q plot tutorialAbhik Seal
 
Surface3d in R and rgl package.
Surface3d in R and rgl package.Surface3d in R and rgl package.
Surface3d in R and rgl package.Dr. Volkan OBAN
 
Data Visualization with R.ggplot2 and its extensions examples.
Data Visualization with R.ggplot2 and its extensions examples.Data Visualization with R.ggplot2 and its extensions examples.
Data Visualization with R.ggplot2 and its extensions examples.Dr. Volkan OBAN
 
H2O World - Consensus Optimization and Machine Learning - Stephen Boyd
H2O World - Consensus Optimization and Machine Learning - Stephen BoydH2O World - Consensus Optimization and Machine Learning - Stephen Boyd
H2O World - Consensus Optimization and Machine Learning - Stephen BoydSri Ambati
 
1 seaborn introduction
1 seaborn introduction 1 seaborn introduction
1 seaborn introduction YuleiLi3
 
Effective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyEffective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyKimikazu Kato
 

Was ist angesagt? (20)

Introduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning ProgrammersIntroduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning Programmers
 
Numpy Talk at SIAM
Numpy Talk at SIAMNumpy Talk at SIAM
Numpy Talk at SIAM
 
20090622 Bp Study#22
20090622 Bp Study#2220090622 Bp Study#22
20090622 Bp Study#22
 
NumPy/SciPy Statistics
NumPy/SciPy StatisticsNumPy/SciPy Statistics
NumPy/SciPy Statistics
 
(2015 06-16) Three Approaches to Monads
(2015 06-16) Three Approaches to Monads(2015 06-16) Three Approaches to Monads
(2015 06-16) Three Approaches to Monads
 
The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)
 
Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303
 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator Pattern
 
Statistical inference for (Python) Data Analysis. An introduction.
Statistical inference for (Python) Data Analysis. An introduction.Statistical inference for (Python) Data Analysis. An introduction.
Statistical inference for (Python) Data Analysis. An introduction.
 
Scientific Computing with Python Webinar March 19: 3D Visualization with Mayavi
Scientific Computing with Python Webinar March 19: 3D Visualization with MayaviScientific Computing with Python Webinar March 19: 3D Visualization with Mayavi
Scientific Computing with Python Webinar March 19: 3D Visualization with Mayavi
 
Matlab plotting
Matlab plottingMatlab plotting
Matlab plotting
 
Funções 1
Funções 1Funções 1
Funções 1
 
R
RR
R
 
Q plot tutorial
Q plot tutorialQ plot tutorial
Q plot tutorial
 
CLIM Undergraduate Workshop: (Attachment) Performing Extreme Value Analysis (...
CLIM Undergraduate Workshop: (Attachment) Performing Extreme Value Analysis (...CLIM Undergraduate Workshop: (Attachment) Performing Extreme Value Analysis (...
CLIM Undergraduate Workshop: (Attachment) Performing Extreme Value Analysis (...
 
Surface3d in R and rgl package.
Surface3d in R and rgl package.Surface3d in R and rgl package.
Surface3d in R and rgl package.
 
Data Visualization with R.ggplot2 and its extensions examples.
Data Visualization with R.ggplot2 and its extensions examples.Data Visualization with R.ggplot2 and its extensions examples.
Data Visualization with R.ggplot2 and its extensions examples.
 
H2O World - Consensus Optimization and Machine Learning - Stephen Boyd
H2O World - Consensus Optimization and Machine Learning - Stephen BoydH2O World - Consensus Optimization and Machine Learning - Stephen Boyd
H2O World - Consensus Optimization and Machine Learning - Stephen Boyd
 
1 seaborn introduction
1 seaborn introduction 1 seaborn introduction
1 seaborn introduction
 
Effective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyEffective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPy
 

Ähnlich wie Financial markets modeling in R

Practical data science_public
Practical data science_publicPractical data science_public
Practical data science_publicLong Nguyen
 
R Cheat Sheet for Data Analysts and Statisticians.pdf
R Cheat Sheet for Data Analysts and Statisticians.pdfR Cheat Sheet for Data Analysts and Statisticians.pdf
R Cheat Sheet for Data Analysts and Statisticians.pdfTimothy McBush Hiele
 
Idea for ineractive programming language
Idea for ineractive programming languageIdea for ineractive programming language
Idea for ineractive programming languageLincoln Hannah
 
09 a1ec01 c programming and data structures
09 a1ec01 c programming and data structures09 a1ec01 c programming and data structures
09 a1ec01 c programming and data structuresjntuworld
 
KARNAUGH MAP(K-MAP)
KARNAUGH MAP(K-MAP)KARNAUGH MAP(K-MAP)
KARNAUGH MAP(K-MAP)mihir jain
 
DataEngConf: Feature Extraction: Modern Questions and Challenges at Google
DataEngConf: Feature Extraction: Modern Questions and Challenges at GoogleDataEngConf: Feature Extraction: Modern Questions and Challenges at Google
DataEngConf: Feature Extraction: Modern Questions and Challenges at GoogleHakka Labs
 
Applied machine learning for search engine relevance 3
Applied machine learning for search engine relevance 3Applied machine learning for search engine relevance 3
Applied machine learning for search engine relevance 3Charles Martin
 
Psychtoolbox (PTB) practical course by Volodymyr B. Bogdanov, Kyiv 2017, Day 1
Psychtoolbox (PTB) practical course  by Volodymyr B. Bogdanov, Kyiv 2017, Day 1Psychtoolbox (PTB) practical course  by Volodymyr B. Bogdanov, Kyiv 2017, Day 1
Psychtoolbox (PTB) practical course by Volodymyr B. Bogdanov, Kyiv 2017, Day 1Volodymyr Bogdanov
 
Introduction to datastructure and algorithm
Introduction to datastructure and algorithmIntroduction to datastructure and algorithm
Introduction to datastructure and algorithmPratik Mota
 
Pengolahan Data Panel Logit di Stata: Penilaian Goodness of Fit, Uji Model, d...
Pengolahan Data Panel Logit di Stata: Penilaian Goodness of Fit, Uji Model, d...Pengolahan Data Panel Logit di Stata: Penilaian Goodness of Fit, Uji Model, d...
Pengolahan Data Panel Logit di Stata: Penilaian Goodness of Fit, Uji Model, d...The1 Uploader
 
Jörg Stelzer
Jörg StelzerJörg Stelzer
Jörg Stelzerbutest
 

Ähnlich wie Financial markets modeling in R (20)

R Language Introduction
R Language IntroductionR Language Introduction
R Language Introduction
 
Practical data science_public
Practical data science_publicPractical data science_public
Practical data science_public
 
R Cheat Sheet for Data Analysts and Statisticians.pdf
R Cheat Sheet for Data Analysts and Statisticians.pdfR Cheat Sheet for Data Analysts and Statisticians.pdf
R Cheat Sheet for Data Analysts and Statisticians.pdf
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
 
Idea for ineractive programming language
Idea for ineractive programming languageIdea for ineractive programming language
Idea for ineractive programming language
 
Lecture12
Lecture12Lecture12
Lecture12
 
09 a1ec01 c programming and data structures
09 a1ec01 c programming and data structures09 a1ec01 c programming and data structures
09 a1ec01 c programming and data structures
 
KARNAUGH MAP(K-MAP)
KARNAUGH MAP(K-MAP)KARNAUGH MAP(K-MAP)
KARNAUGH MAP(K-MAP)
 
DataEngConf: Feature Extraction: Modern Questions and Challenges at Google
DataEngConf: Feature Extraction: Modern Questions and Challenges at GoogleDataEngConf: Feature Extraction: Modern Questions and Challenges at Google
DataEngConf: Feature Extraction: Modern Questions and Challenges at Google
 
Applied machine learning for search engine relevance 3
Applied machine learning for search engine relevance 3Applied machine learning for search engine relevance 3
Applied machine learning for search engine relevance 3
 
ML-CheatSheet (1).pdf
ML-CheatSheet (1).pdfML-CheatSheet (1).pdf
ML-CheatSheet (1).pdf
 
Survey Demo
Survey DemoSurvey Demo
Survey Demo
 
Psychtoolbox (PTB) practical course by Volodymyr B. Bogdanov, Kyiv 2017, Day 1
Psychtoolbox (PTB) practical course  by Volodymyr B. Bogdanov, Kyiv 2017, Day 1Psychtoolbox (PTB) practical course  by Volodymyr B. Bogdanov, Kyiv 2017, Day 1
Psychtoolbox (PTB) practical course by Volodymyr B. Bogdanov, Kyiv 2017, Day 1
 
Introduction to datastructure and algorithm
Introduction to datastructure and algorithmIntroduction to datastructure and algorithm
Introduction to datastructure and algorithm
 
Pengolahan Data Panel Logit di Stata: Penilaian Goodness of Fit, Uji Model, d...
Pengolahan Data Panel Logit di Stata: Penilaian Goodness of Fit, Uji Model, d...Pengolahan Data Panel Logit di Stata: Penilaian Goodness of Fit, Uji Model, d...
Pengolahan Data Panel Logit di Stata: Penilaian Goodness of Fit, Uji Model, d...
 
Rtutorial
RtutorialRtutorial
Rtutorial
 
Jörg Stelzer
Jörg StelzerJörg Stelzer
Jörg Stelzer
 
MUMS Opening Workshop - An Overview of Reduced-Order Models and Emulators (ED...
MUMS Opening Workshop - An Overview of Reduced-Order Models and Emulators (ED...MUMS Opening Workshop - An Overview of Reduced-Order Models and Emulators (ED...
MUMS Opening Workshop - An Overview of Reduced-Order Models and Emulators (ED...
 
Learn Matlab
Learn MatlabLearn Matlab
Learn Matlab
 
An Intoduction to R
An Intoduction to RAn Intoduction to R
An Intoduction to R
 

Kürzlich hochgeladen

AfRESFullPaper22018EmpiricalPerformanceofRealEstateInvestmentTrustsandShareho...
AfRESFullPaper22018EmpiricalPerformanceofRealEstateInvestmentTrustsandShareho...AfRESFullPaper22018EmpiricalPerformanceofRealEstateInvestmentTrustsandShareho...
AfRESFullPaper22018EmpiricalPerformanceofRealEstateInvestmentTrustsandShareho...yordanosyohannes2
 
Authentic No 1 Amil Baba In Pakistan Authentic No 1 Amil Baba In Karachi No 1...
Authentic No 1 Amil Baba In Pakistan Authentic No 1 Amil Baba In Karachi No 1...Authentic No 1 Amil Baba In Pakistan Authentic No 1 Amil Baba In Karachi No 1...
Authentic No 1 Amil Baba In Pakistan Authentic No 1 Amil Baba In Karachi No 1...First NO1 World Amil baba in Faisalabad
 
Tenets of Physiocracy History of Economic
Tenets of Physiocracy History of EconomicTenets of Physiocracy History of Economic
Tenets of Physiocracy History of Economiccinemoviesu
 
(中央兰开夏大学毕业证学位证成绩单-案例)
(中央兰开夏大学毕业证学位证成绩单-案例)(中央兰开夏大学毕业证学位证成绩单-案例)
(中央兰开夏大学毕业证学位证成绩单-案例)twfkn8xj
 
fca-bsps-decision-letter-redacted (1).pdf
fca-bsps-decision-letter-redacted (1).pdffca-bsps-decision-letter-redacted (1).pdf
fca-bsps-decision-letter-redacted (1).pdfHenry Tapper
 
212MTAMount Durham University Bachelor's Diploma in Technology
212MTAMount Durham University Bachelor's Diploma in Technology212MTAMount Durham University Bachelor's Diploma in Technology
212MTAMount Durham University Bachelor's Diploma in Technologyz xss
 
Bladex Earnings Call Presentation 1Q2024
Bladex Earnings Call Presentation 1Q2024Bladex Earnings Call Presentation 1Q2024
Bladex Earnings Call Presentation 1Q2024Bladex
 
原版1:1复刻堪萨斯大学毕业证KU毕业证留信学历认证
原版1:1复刻堪萨斯大学毕业证KU毕业证留信学历认证原版1:1复刻堪萨斯大学毕业证KU毕业证留信学历认证
原版1:1复刻堪萨斯大学毕业证KU毕业证留信学历认证jdkhjh
 
call girls in Nand Nagri (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in  Nand Nagri (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in  Nand Nagri (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Nand Nagri (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
chapter_2.ppt The labour market definitions and trends
chapter_2.ppt The labour market definitions and trendschapter_2.ppt The labour market definitions and trends
chapter_2.ppt The labour market definitions and trendslemlemtesfaye192
 
government_intervention_in_business_ownership[1].pdf
government_intervention_in_business_ownership[1].pdfgovernment_intervention_in_business_ownership[1].pdf
government_intervention_in_business_ownership[1].pdfshaunmashale756
 
Classical Theory of Macroeconomics by Adam Smith
Classical Theory of Macroeconomics by Adam SmithClassical Theory of Macroeconomics by Adam Smith
Classical Theory of Macroeconomics by Adam SmithAdamYassin2
 
Stock Market Brief Deck FOR 4/17 video.pdf
Stock Market Brief Deck FOR 4/17 video.pdfStock Market Brief Deck FOR 4/17 video.pdf
Stock Market Brief Deck FOR 4/17 video.pdfMichael Silva
 
PMFBY , Pradhan Mantri Fasal bima yojna
PMFBY , Pradhan Mantri  Fasal bima yojnaPMFBY , Pradhan Mantri  Fasal bima yojna
PMFBY , Pradhan Mantri Fasal bima yojnaDharmendra Kumar
 
The Core Functions of the Bangko Sentral ng Pilipinas
The Core Functions of the Bangko Sentral ng PilipinasThe Core Functions of the Bangko Sentral ng Pilipinas
The Core Functions of the Bangko Sentral ng PilipinasCherylouCamus
 
《加拿大本地办假证-寻找办理Dalhousie毕业证和达尔豪斯大学毕业证书的中介代理》
《加拿大本地办假证-寻找办理Dalhousie毕业证和达尔豪斯大学毕业证书的中介代理》《加拿大本地办假证-寻找办理Dalhousie毕业证和达尔豪斯大学毕业证书的中介代理》
《加拿大本地办假证-寻找办理Dalhousie毕业证和达尔豪斯大学毕业证书的中介代理》rnrncn29
 
Call Girls In Yusuf Sarai Women Seeking Men 9654467111
Call Girls In Yusuf Sarai Women Seeking Men 9654467111Call Girls In Yusuf Sarai Women Seeking Men 9654467111
Call Girls In Yusuf Sarai Women Seeking Men 9654467111Sapana Sha
 
magnetic-pensions-a-new-blueprint-for-the-dc-landscape.pdf
magnetic-pensions-a-new-blueprint-for-the-dc-landscape.pdfmagnetic-pensions-a-new-blueprint-for-the-dc-landscape.pdf
magnetic-pensions-a-new-blueprint-for-the-dc-landscape.pdfHenry Tapper
 

Kürzlich hochgeladen (20)

AfRESFullPaper22018EmpiricalPerformanceofRealEstateInvestmentTrustsandShareho...
AfRESFullPaper22018EmpiricalPerformanceofRealEstateInvestmentTrustsandShareho...AfRESFullPaper22018EmpiricalPerformanceofRealEstateInvestmentTrustsandShareho...
AfRESFullPaper22018EmpiricalPerformanceofRealEstateInvestmentTrustsandShareho...
 
Authentic No 1 Amil Baba In Pakistan Authentic No 1 Amil Baba In Karachi No 1...
Authentic No 1 Amil Baba In Pakistan Authentic No 1 Amil Baba In Karachi No 1...Authentic No 1 Amil Baba In Pakistan Authentic No 1 Amil Baba In Karachi No 1...
Authentic No 1 Amil Baba In Pakistan Authentic No 1 Amil Baba In Karachi No 1...
 
Tenets of Physiocracy History of Economic
Tenets of Physiocracy History of EconomicTenets of Physiocracy History of Economic
Tenets of Physiocracy History of Economic
 
(中央兰开夏大学毕业证学位证成绩单-案例)
(中央兰开夏大学毕业证学位证成绩单-案例)(中央兰开夏大学毕业证学位证成绩单-案例)
(中央兰开夏大学毕业证学位证成绩单-案例)
 
fca-bsps-decision-letter-redacted (1).pdf
fca-bsps-decision-letter-redacted (1).pdffca-bsps-decision-letter-redacted (1).pdf
fca-bsps-decision-letter-redacted (1).pdf
 
212MTAMount Durham University Bachelor's Diploma in Technology
212MTAMount Durham University Bachelor's Diploma in Technology212MTAMount Durham University Bachelor's Diploma in Technology
212MTAMount Durham University Bachelor's Diploma in Technology
 
Bladex Earnings Call Presentation 1Q2024
Bladex Earnings Call Presentation 1Q2024Bladex Earnings Call Presentation 1Q2024
Bladex Earnings Call Presentation 1Q2024
 
原版1:1复刻堪萨斯大学毕业证KU毕业证留信学历认证
原版1:1复刻堪萨斯大学毕业证KU毕业证留信学历认证原版1:1复刻堪萨斯大学毕业证KU毕业证留信学历认证
原版1:1复刻堪萨斯大学毕业证KU毕业证留信学历认证
 
Monthly Economic Monitoring of Ukraine No 231, April 2024
Monthly Economic Monitoring of Ukraine No 231, April 2024Monthly Economic Monitoring of Ukraine No 231, April 2024
Monthly Economic Monitoring of Ukraine No 231, April 2024
 
call girls in Nand Nagri (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in  Nand Nagri (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in  Nand Nagri (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Nand Nagri (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
chapter_2.ppt The labour market definitions and trends
chapter_2.ppt The labour market definitions and trendschapter_2.ppt The labour market definitions and trends
chapter_2.ppt The labour market definitions and trends
 
government_intervention_in_business_ownership[1].pdf
government_intervention_in_business_ownership[1].pdfgovernment_intervention_in_business_ownership[1].pdf
government_intervention_in_business_ownership[1].pdf
 
Classical Theory of Macroeconomics by Adam Smith
Classical Theory of Macroeconomics by Adam SmithClassical Theory of Macroeconomics by Adam Smith
Classical Theory of Macroeconomics by Adam Smith
 
Stock Market Brief Deck FOR 4/17 video.pdf
Stock Market Brief Deck FOR 4/17 video.pdfStock Market Brief Deck FOR 4/17 video.pdf
Stock Market Brief Deck FOR 4/17 video.pdf
 
PMFBY , Pradhan Mantri Fasal bima yojna
PMFBY , Pradhan Mantri  Fasal bima yojnaPMFBY , Pradhan Mantri  Fasal bima yojna
PMFBY , Pradhan Mantri Fasal bima yojna
 
🔝+919953056974 🔝young Delhi Escort service Pusa Road
🔝+919953056974 🔝young Delhi Escort service Pusa Road🔝+919953056974 🔝young Delhi Escort service Pusa Road
🔝+919953056974 🔝young Delhi Escort service Pusa Road
 
The Core Functions of the Bangko Sentral ng Pilipinas
The Core Functions of the Bangko Sentral ng PilipinasThe Core Functions of the Bangko Sentral ng Pilipinas
The Core Functions of the Bangko Sentral ng Pilipinas
 
《加拿大本地办假证-寻找办理Dalhousie毕业证和达尔豪斯大学毕业证书的中介代理》
《加拿大本地办假证-寻找办理Dalhousie毕业证和达尔豪斯大学毕业证书的中介代理》《加拿大本地办假证-寻找办理Dalhousie毕业证和达尔豪斯大学毕业证书的中介代理》
《加拿大本地办假证-寻找办理Dalhousie毕业证和达尔豪斯大学毕业证书的中介代理》
 
Call Girls In Yusuf Sarai Women Seeking Men 9654467111
Call Girls In Yusuf Sarai Women Seeking Men 9654467111Call Girls In Yusuf Sarai Women Seeking Men 9654467111
Call Girls In Yusuf Sarai Women Seeking Men 9654467111
 
magnetic-pensions-a-new-blueprint-for-the-dc-landscape.pdf
magnetic-pensions-a-new-blueprint-for-the-dc-landscape.pdfmagnetic-pensions-a-new-blueprint-for-the-dc-landscape.pdf
magnetic-pensions-a-new-blueprint-for-the-dc-landscape.pdf
 

Financial markets modeling in R

  • 1. Financial markets modeling in R Arbuzov V. Perm State National Research University arbuzov@prognoz.ru 20 November 2013 Perm R group r-group.mifit.ru ITE.LAB “MathEconomics” Open Course Russia, Perm, 20 November 2013 workshop
  • 6. Coding Useful commands to create a vector 1:10 seq(1,10) rep(1,10) working with vectors A<-1:10 B<-c(2,4,8) A*B A>B assignment operator <- or -> x<-10 10->X case sensitive X x R is a case sensitive language. FOO, Foo, and foo are three different objects!
  • 7. Coding Matrix y <- matrix(nrow=2,ncol=2) y[1,1] <- 1 y[2,1] <- 2 y[1,2] <- 3 y[2,2] <- 4 x <- matrix(1:4, 2, 2) A matrix is a vector with two additional attributes: the number of rows and the number of columns Matrix Operations x %*% y x* y 3*y x+y x+3 x[,2] x[1,] rbind(x,y)->z cbind(x,y) z[1:2,] z[z[,1]>1,] z[which(z[,1]>1),1]
  • 8. Coding Data Frame List kids <- c("Jack","Jill") ages <- c(12,10) d <- data.frame(kids,ages) d[1,] d[,1] d[[1]] j <- list(name="Joe", salary=55000, union=T) j$salary j[["salary"]] j[[2]] j$name [2]<-”Poll” j$salary[2]<-10000 j$union [2]<-”F” Arrays In contrast to a vector, in which all elements must be of the same mode, R’s list structure can combine objects of different types. my.array <- array(1:24, dim=c(3,4,2)) a data frame is like a matrix, with a two-dimensional rowsandcolumns structure. However, it differs from a matrix in that each column may have a different mode.
  • 9. Coding Loops for x <- c(5,12,13) for (n in x) print(n^2) for (i in 1:10) { x<-i*3 cos(x)->x print(x) } if-else i<-3 if (i == 4) x <- 1 else x <- 3 while i <- 1 while (i <= 10) i <- i+4 i <- 1 while (i <= 10) { x<-i*3 cos(x)->x print(c(x,i)) i <- i+1 }
  • 10. Import/Export data Import from text files or csv mydata <read.table("d:/my.data.txt", header=TRUE , sep=",") Import from Excel library(xlsx) mydata<-read.xlsx("d:/my.data.xlsx",1) Exporting Data write.table(mydata, "c:/mydata.txt", sep="t") write.xlsx(mydata, "c:/mydata.xls") Import/Export Data to clipboard read.table("clipboard",sep="t") write.table(arg1,"clipboard",sep="t") rb <- function(arg1){read.table("clipboard",sep="t")} P.S. cb <- function(arg1){write.table(arg1,"clipboard",sep="t")}
  • 11. Basic Graphs Creating a Graph attach(mtcars) plot(wt, mpg) abline(lm(mpg~wt)) title("Regression of MPG on Weight") Bar Plot counts <- table(mtcars$gear) barplot(counts, main="Car Distribution", xlab="Number of Gears") Pie Charts Boxplot slices <- c(10, 12,4, 16, 8) lbls <c("US", "UK", "Australia", "Germany", "France") pie(slices, labels = lbls, main="Pie Chart of Countries") boxplot(mpg~cyl,data=mtcars, mai n="Car Milage Data", xlab="Number of Cylinders", ylab="Miles Per Gallon")
  • 13. Select data from matrix x <- matrix(0,50,2) x[,1] x[1,] x[,1]<-rnorm(50) x x[1,]<-rnorm(2) x x <- matrix(rnorm(100),50,2) x[which(x[,1]>0),] Operators and & or |
  • 14. Distributions Basic distributions in R Beta ?beta Binomial ?binom Cauchy ?cauchy Chi-squared ?chisq Exponential ?exp F ?f Gamma ?gamma Geometric ?geom Hypergeometric ?hyper Log-normal ?lnorm Multinomial ?multinom Negative binomial ?nbinom Normal ?norm Poisson ?pois Student's t ?t Uniform ?unif Weibull ?weibull d – density q – quantile r – random
  • 15. Distributions Plot density of chosen distribution… x <- seq(-4, 4, length=100) dx <- d?????(x) plot(x, hx, type=“l”) Generate random variables of chosen distribution … x<-rnorm(1000)
  • 16. Distributions What is this distribution ? hist (?) density (?) ?
  • 17. Estimation of parameters Let’s estimate parameters of chosen distribution…. library(MASS) fitdistr(x,"normal") params<-fitdistr(x,"normal")$estimate Compare theoretical and empirical distributions… hist(x, freq = FALSE,ylim=c(0,0.4)) curve(dnorm(x, params[1], params[2]), col = 2, add = TRUE)
  • 19. Linear least-squares method x<-seq(0,10,length=1000) y<-1+2*x+sin(x)*rnorm(1000,0,2) plot(x,y) How to estimate this parameters? lm(y ~ x) summary(lm(y ~ x)) abline(lm(y ~ x),col="red",lwd=3)
  • 20. Nonlinear least-squares method x<-seq(0,10,length=1000) y<-2*sin(3*x)+rnorm(1000,0,0.8) How to estimate this parameters? help(nls) nls(y ~ A*sin(B*x)) nls(y ~ A*sin(B*x),start=list(A=1.8,B=3.1))
  • 21. Advanced graphics Add few diagrams to graph par(mfrow=c(2,2)) plot(rnorm(100),rbeta(100,12,1)) Add legend to graph legend("topright", inset=.05, title="legend", c("4","6","8"), horiz=TRUE)
  • 24. Download Data Package quantmod Package rusquant getSymbols("GOOG",src="yahoo", from = "2007-01-01“, to = Sys.Date()) getSymbols("SPFB.RTS", from="2011-0101", src="Finam“, period="hour" , auto.assign=FALSE) getSymbols("USD/EUR",src="oanda") 1min, 5min, 10min, 15min, 30min, hour, day, week, month
  • 25. Working with package quantmod Data visualization Add technical indicators barChart(AAPL) candleChart(AAPL,multi.col=TRUE,theme="white") addMACD() chartSeries(AAPL,up.col='white',dn.col='blue') addBBands() Select data AAPL['2007'] AAPL['2007-03/2007'] AAPL['/2007'] AAPL['2007-01-03'] Data management to.weekly(AAPL) to.monthly(AAPL) dailyReturn(AAPL) weeklyReturn(AAPL) monthlyReturn(AAPL)
  • 26. Load Data from Database Package RODBC library(RODBC) odbcDriverConnect(“”) channel <- odbcConnect("psu_schs",“student","Qwerty1") sqlQuery(channel, “select * from LPPL_MODELS”)
  • 28. Practice № 1. Working with data 1. AAPL 2. BAC 3. GOOG 4. GE 5. GM 6. PG 7. JNJ 8. JPM 9. LNKD 10. MSFT 11. NOK 12. IBM 13. AMZN 14. V TASK: a. Download Data of your instrument b. Plot price c. Add technical indicators d. Calculate price returns Commands to help : barChart(AAPL) chartSeries(AAPL,up.col='white',dn.col='blue') AAPL['2007-03/2007'] addMACD() dailyReturn(AAPL)
  • 29. Practice № 2. Distribution of price returns 1. AAPL 2. BAC 3. GOOG 4. GE 5. GM 6. PG 7. JNJ 8. JPM 9. LNKD 10. MSFT 11. NOK 12. IBM 13. AMZN 14. V TASK : a. Download Data of your instrument b. Calculate returns of close prices c. Plot density of distribution d. Estimate parameters of distribution e. Plot in one graph empirical and theoretical distributions Commands to help : getSymbols("AAPL", auto.assign=FALSE) library(MASS) fitdistr(x,"normal") hist(x) density(x) curve(dnorm(x, params[1], params[2]), col = 2, add = TRUE)
  • 30. Practice № 3. Estimation of correlation 1. AAPL 2. BAC 3. GOOG 4. GE 5. GM 6. PG 7. JNJ 8. JPM 9. LNKD 10. MSFT 11. NOK 12. IBM 13. AMZN 14. V TASK : a. Download Index Data (ticker: “MICEX”) b. Download Data of your instrument c. Calculate returns of close prices d. Calculate correlation of returns e. Calculate correlation of returns in 2012 year f. Calculate correlation of returns in 2008 year g. Calculate autocorrelation function of returns Commands to help : getSymbols(" MICEX ", src="Finam", period="day" , auto.assign=FALSE) AAPL['2007'] AAPL['2007-03/2007'] AAPL['/2007'] AAPL['2007-01-03']
  • 31. Practice № 4. Volatility estimation 1. AAPL 2. BAC 3. GOOG 4. GE 5. GM 6. PG 7. JNJ 8. JPM 9. LNKD 10. MSFT 11. NOK 12. IBM 13. AMZN 14. V TASK : a. Download Data of your instrument b. Calculate returns of close prices c. Plot clusterization of volatility d. Estimate model garch e. garchFit(data=x) @sigma.t Commands to help : AAPL['2007'] AAPL['2007-03/2007'] AAPL['/2007'] AAPL['2007-01-03']
  • 32. The practical task №5. Calculation of VaR 1. AAPL 2. BAC 3. GOOG 4. GE 5. GM 6. PG 7. JNJ 8. JPM 9. LNKD 10. MSFT 11. NOK 12. IBM 13. AMZN 14. V TASK : a. Download Data of your instrument b. Calculate returns of close prices c. Calculate historical VaR d. Calculate parametric VaR e. library(PerformanceAnalytics) f. help(VaR) Commands to help : quantile(x,0.95, na.rm=TRUE) AAPL['2007'] AAPL['2007-03/2007'] AAPL['/2007'] AAPL['2007-01-03']
  • 33. The practical task № 6. Estimate LPPL model TASK : a. Download Nikkei Index Data(ticker: “^N225”) from June 2012 to June 2013 b. Estimate parameters of model LPPL MODEL LPPL: Commands to help : help(nsl)