SlideShare a Scribd company logo
1 of 35
Download to read offline
Introduction to financial
modeling in R platform

Arbuzov V.

Perm State National Research
University

Perm R group
r-group.mifit.ru

arbuzov@prognoz.ru

Perm Winter School 2014
Russia, Perm, 31 January 2014
workshop
Basic knowledgement
about R
3

R console
R as calculator
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?
๐‘ฆ = ๐›ผsin(๐›ฝ๐‘ฅ)
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)
Tree maps

library(portfolio)
data(dow.jan.2005)
map.market(id = dow.jan.2005$symbol,
area = dow.jan.2005$cap.bil,
group = dow.jan.2005$sector,
color = 100 * dow.jan.2005$month.ret)
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

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

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

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

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

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

More Related Content

What's hot

Monad presentation scala as a category
Monad presentation   scala as a categoryMonad presentation   scala as a category
Monad presentation scala as a category
samthemonad
ย 
Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)
stasimus
ย 
20090622 Bp Study#22
20090622 Bp Study#2220090622 Bp Study#22
20090622 Bp Study#22
Tomohito Ozaki
ย 
Rsplit apply combine
Rsplit apply combineRsplit apply combine
Rsplit apply combine
Michelle Darling
ย 

What's hot (20)

NumPy Refresher
NumPy RefresherNumPy Refresher
NumPy Refresher
ย 
Monad presentation scala as a category
Monad presentation   scala as a categoryMonad presentation   scala as a category
Monad presentation scala as a category
ย 
Numpy Talk at SIAM
Numpy Talk at SIAMNumpy Talk at SIAM
Numpy Talk at SIAM
ย 
R-ggplot2 package Examples
R-ggplot2 package ExamplesR-ggplot2 package Examples
R-ggplot2 package Examples
ย 
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)
ย 
Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)
ย 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator Pattern
ย 
20090622 Bp Study#22
20090622 Bp Study#2220090622 Bp Study#22
20090622 Bp Study#22
ย 
Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303
ย 
NumPy/SciPy Statistics
NumPy/SciPy StatisticsNumPy/SciPy Statistics
NumPy/SciPy Statistics
ย 
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.
ย 
(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
ย 
Matlab plotting
Matlab plottingMatlab plotting
Matlab plotting
ย 
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
ย 
Q plot tutorial
Q plot tutorialQ plot tutorial
Q plot tutorial
ย 
Python3 cheatsheet
Python3 cheatsheetPython3 cheatsheet
Python3 cheatsheet
ย 
Programs in array using SWIFT
Programs in array using SWIFTPrograms in array using SWIFT
Programs in array using SWIFT
ย 
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 (...
ย 
Rsplit apply combine
Rsplit apply combineRsplit apply combine
Rsplit apply combine
ย 
Pandas Cheat Sheet
Pandas Cheat SheetPandas Cheat Sheet
Pandas Cheat Sheet
ย 

Viewers also liked (7)

Financial market simulation based on zero intelligence models
Financial market simulation based on zero intelligence modelsFinancial market simulation based on zero intelligence models
Financial market simulation based on zero intelligence models
ย 
Lppl models MiFIT 2013: Vyacheslav Arbuzov
Lppl models MiFIT 2013: Vyacheslav ArbuzovLppl models MiFIT 2013: Vyacheslav Arbuzov
Lppl models MiFIT 2013: Vyacheslav Arbuzov
ย 
Extent3 prognoz practical_approach_lppl_model_2012
Extent3 prognoz practical_approach_lppl_model_2012Extent3 prognoz practical_approach_lppl_model_2012
Extent3 prognoz practical_approach_lppl_model_2012
ย 
Seminar psu 21.10.2013 financial bubble diagnostics based on log-periodic p...
Seminar psu 21.10.2013   financial bubble diagnostics based on log-periodic p...Seminar psu 21.10.2013   financial bubble diagnostics based on log-periodic p...
Seminar psu 21.10.2013 financial bubble diagnostics based on log-periodic p...
ย 
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over WebsocketIntroduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
Introduction to WAMP, a protocol enabling PUB/SUB and RPC over Websocket
ย 
Hidden Markov Models
Hidden Markov ModelsHidden Markov Models
Hidden Markov Models
ย 
Hidden Markov Model & Stock Prediction
Hidden Markov Model & Stock PredictionHidden Markov Model & Stock Prediction
Hidden Markov Model & Stock Prediction
ย 

Similar to Perm winter school 2014.01.31

R Language Introduction
R Language IntroductionR Language Introduction
R Language Introduction
Khaled Al-Shamaa
ย 
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
jntuworld
ย 
R
RR
R
exsuns
ย 

Similar to Perm winter school 2014.01.31 (20)

R Language Introduction
R Language IntroductionR Language Introduction
R Language Introduction
ย 
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
ย 
R Programming Intro
R Programming IntroR Programming Intro
R Programming Intro
ย 
Regression and Classification with R
Regression and Classification with RRegression and Classification with R
Regression and Classification with R
ย 
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
ย 
Big Data Mining in Indian Economic Survey 2017
Big Data Mining in Indian Economic Survey 2017Big Data Mining in Indian Economic Survey 2017
Big Data Mining in Indian Economic Survey 2017
ย 
KARNAUGH MAP(K-MAP)
KARNAUGH MAP(K-MAP)KARNAUGH MAP(K-MAP)
KARNAUGH MAP(K-MAP)
ย 
Practical data science_public
Practical data science_publicPractical data science_public
Practical data science_public
ย 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
ย 
Data analysis with R
Data analysis with RData analysis with R
Data analysis with R
ย 
NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...
NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...
NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...
ย 
Programming in R
Programming in RProgramming in R
Programming in R
ย 
Idea for ineractive programming language
Idea for ineractive programming languageIdea for ineractive programming language
Idea for ineractive programming language
ย 
Digital electronics k map comparators and their function
Digital electronics k map comparators and their functionDigital electronics k map comparators and their function
Digital electronics k map comparators and their function
ย 
R tutorial for a windows environment
R tutorial for a windows environmentR tutorial for a windows environment
R tutorial for a windows environment
ย 
R programming language
R programming languageR programming language
R programming language
ย 
R
RR
R
ย 
Introduction to Data Science With R Lab Record
Introduction to Data Science With R Lab RecordIntroduction to Data Science With R Lab Record
Introduction to Data Science With R Lab Record
ย 
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
ย 
R Programming Homework Help
R Programming Homework HelpR Programming Homework Help
R Programming Homework Help
ย 

Recently uploaded

Recently uploaded (20)

Call US ๐Ÿ“ž 9892124323 โœ… Kurla Call Girls In Kurla ( Mumbai ) secure service
Call US ๐Ÿ“ž 9892124323 โœ… Kurla Call Girls In Kurla ( Mumbai ) secure serviceCall US ๐Ÿ“ž 9892124323 โœ… Kurla Call Girls In Kurla ( Mumbai ) secure service
Call US ๐Ÿ“ž 9892124323 โœ… Kurla Call Girls In Kurla ( Mumbai ) secure service
ย 
03_Emmanuel Ndiaye_Degroof Petercam.pptx
03_Emmanuel Ndiaye_Degroof Petercam.pptx03_Emmanuel Ndiaye_Degroof Petercam.pptx
03_Emmanuel Ndiaye_Degroof Petercam.pptx
ย 
Vip Call US ๐Ÿ“ž 7738631006 โœ…Call Girls In Sakinaka ( Mumbai )
Vip Call US ๐Ÿ“ž 7738631006 โœ…Call Girls In Sakinaka ( Mumbai )Vip Call US ๐Ÿ“ž 7738631006 โœ…Call Girls In Sakinaka ( Mumbai )
Vip Call US ๐Ÿ“ž 7738631006 โœ…Call Girls In Sakinaka ( Mumbai )
ย 
Stock Market Brief Deck (Under Pressure).pdf
Stock Market Brief Deck (Under Pressure).pdfStock Market Brief Deck (Under Pressure).pdf
Stock Market Brief Deck (Under Pressure).pdf
ย 
The Economic History of the U.S. Lecture 17.pdf
The Economic History of the U.S. Lecture 17.pdfThe Economic History of the U.S. Lecture 17.pdf
The Economic History of the U.S. Lecture 17.pdf
ย 
The Economic History of the U.S. Lecture 23.pdf
The Economic History of the U.S. Lecture 23.pdfThe Economic History of the U.S. Lecture 23.pdf
The Economic History of the U.S. Lecture 23.pdf
ย 
Call Girls Service Nagpur Maya Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Maya Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Maya Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Maya Call 7001035870 Meet With Nagpur Escorts
ย 
The Economic History of the U.S. Lecture 19.pdf
The Economic History of the U.S. Lecture 19.pdfThe Economic History of the U.S. Lecture 19.pdf
The Economic History of the U.S. Lecture 19.pdf
ย 
Pooja 9892124323 : Call Girl in Juhu Escorts Service Free Home Delivery
Pooja 9892124323 : Call Girl in Juhu Escorts Service Free Home DeliveryPooja 9892124323 : Call Girl in Juhu Escorts Service Free Home Delivery
Pooja 9892124323 : Call Girl in Juhu Escorts Service Free Home Delivery
ย 
00_Main ppt_MeetupDORA&CyberSecurity.pptx
00_Main ppt_MeetupDORA&CyberSecurity.pptx00_Main ppt_MeetupDORA&CyberSecurity.pptx
00_Main ppt_MeetupDORA&CyberSecurity.pptx
ย 
Top Rated Pune Call Girls Viman Nagar โŸŸ 6297143586 โŸŸ Call Me For Genuine Sex...
Top Rated  Pune Call Girls Viman Nagar โŸŸ 6297143586 โŸŸ Call Me For Genuine Sex...Top Rated  Pune Call Girls Viman Nagar โŸŸ 6297143586 โŸŸ Call Me For Genuine Sex...
Top Rated Pune Call Girls Viman Nagar โŸŸ 6297143586 โŸŸ Call Me For Genuine Sex...
ย 
02_Fabio Colombo_Accenture_MeetupDora&Cybersecurity.pptx
02_Fabio Colombo_Accenture_MeetupDora&Cybersecurity.pptx02_Fabio Colombo_Accenture_MeetupDora&Cybersecurity.pptx
02_Fabio Colombo_Accenture_MeetupDora&Cybersecurity.pptx
ย 
The Economic History of the U.S. Lecture 18.pdf
The Economic History of the U.S. Lecture 18.pdfThe Economic History of the U.S. Lecture 18.pdf
The Economic History of the U.S. Lecture 18.pdf
ย 
The Economic History of the U.S. Lecture 21.pdf
The Economic History of the U.S. Lecture 21.pdfThe Economic History of the U.S. Lecture 21.pdf
The Economic History of the U.S. Lecture 21.pdf
ย 
Call Girls Koregaon Park Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Koregaon Park Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Koregaon Park Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Koregaon Park Call Me 7737669865 Budget Friendly No Advance Booking
ย 
Booking open Available Pune Call Girls Talegaon Dabhade 6297143586 Call Hot ...
Booking open Available Pune Call Girls Talegaon Dabhade  6297143586 Call Hot ...Booking open Available Pune Call Girls Talegaon Dabhade  6297143586 Call Hot ...
Booking open Available Pune Call Girls Talegaon Dabhade 6297143586 Call Hot ...
ย 
05_Annelore Lenoir_Docbyte_MeetupDora&Cybersecurity.pptx
05_Annelore Lenoir_Docbyte_MeetupDora&Cybersecurity.pptx05_Annelore Lenoir_Docbyte_MeetupDora&Cybersecurity.pptx
05_Annelore Lenoir_Docbyte_MeetupDora&Cybersecurity.pptx
ย 
The Economic History of the U.S. Lecture 26.pdf
The Economic History of the U.S. Lecture 26.pdfThe Economic History of the U.S. Lecture 26.pdf
The Economic History of the U.S. Lecture 26.pdf
ย 
VVIP Pune Call Girls Katraj (7001035870) Pune Escorts Nearby with Complete Sa...
VVIP Pune Call Girls Katraj (7001035870) Pune Escorts Nearby with Complete Sa...VVIP Pune Call Girls Katraj (7001035870) Pune Escorts Nearby with Complete Sa...
VVIP Pune Call Girls Katraj (7001035870) Pune Escorts Nearby with Complete Sa...
ย 
Solution Manual for Principles of Corporate Finance 14th Edition by Richard B...
Solution Manual for Principles of Corporate Finance 14th Edition by Richard B...Solution Manual for Principles of Corporate Finance 14th Edition by Richard B...
Solution Manual for Principles of Corporate Finance 14th Edition by Richard B...
ย 

Perm winter school 2014.01.31

  • 1. Introduction to financial modeling in R platform Arbuzov V. Perm State National Research University Perm R group r-group.mifit.ru arbuzov@prognoz.ru Perm Winter School 2014 Russia, Perm, 31 January 2014 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? ๐‘ฆ = ๐›ผsin(๐›ฝ๐‘ฅ) 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. Tree maps library(portfolio) data(dow.jan.2005) map.market(id = dow.jan.2005$symbol, area = dow.jan.2005$cap.bil, group = dow.jan.2005$sector, color = 100 * dow.jan.2005$month.ret)
  • 25. 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
  • 26. 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)
  • 27. Load Data from Database Package RODBC library(RODBC) odbcDriverConnect(โ€œโ€) channel <- odbcConnect("psu_schs",โ€œstudent","Qwerty1") sqlQuery(channel, โ€œselect * from LPPL_MODELSโ€)
  • 29. Practice โ„– 1. Working with data 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)
  • 30. Practice โ„– 2. Distribution of price returns 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)
  • 31. Practice โ„– 3. Estimation of correlation 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']
  • 32. Practice โ„– 4. Volatility estimation 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']
  • 33. The practical task โ„–5. Calculation of VaR 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']
  • 34. 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) ๐‘š ๐‘๐‘œ๐‘ [๐œ” ๐‘™๐‘œ๐‘” ๐‘ก ๐‘ โˆ’ ๐‘ก โˆ’ ๐œ‘]