SlideShare uma empresa Scribd logo
1 de 36
Using R in financial modeling




                               Арбузов Вячеслав
                                 arbuzov@prognoz.ru
Perm State National Research
University
Basic knowledgement
       about R
R console




            3
Coding

Simple        Mathematical functions in R
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)
Coding

  x<-1:10
Coding

Useful commands


   to create a vector                       assignment operator
   1:10                                     <- or ->
   seq(1,10)                                x<-10
   rep(1,10)                                10->X


   working with vectors                     case sensitive

    A<-1:10                                 X
    B<-c(2,4,8)                             x
    A*B
    A>B



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



    Matrix                       Matrix Operations

    y <- matrix(nrow=2,ncol=2)   x %*% y
    y[1,1] <- 1                  x* y
    y[2,1] <- 2                  3*y
    y[1,2] <- 3                  x+y
    y[2,2] <- 4                  x+3
    x <- matrix(1:4, 2, 2)       x[,2]
                                 x[1,]
                                 rbind(x,y)->z
                                 cbind(x,y)
                                 z[1:2,]
    A matrix is a vector         z[z[,1]>1,]
    with two additional          z[which(z[,1]>1),1]
    attributes: the
    number of rows and
    the
    number of columns
Coding

                                                   Data Frame
List
                                                        kids <- c("Jack","Jill")
j <- list(name="Joe", salary=55000, union=T)            ages <- c(12,10)
j$salary                                                d <- data.frame(kids,ages)
j[["salary"]]                                           d[1,]
j[[2]]                                                  d[,1]
j$name [2]<-”Poll”                                      d[[1]]
j$salary[2]<-10000
j$union [2]<-”F”
                                               Arrays

                                           my.array <- array(1:24, dim=c(3,4,2))
       In contrast to a
       vector, in which all
       elements
       must be of the same               a data frame is like a
       mode, R’s list                    matrix, with a two-dimensional rows-
       structure can                     andcolumns
       combine objects of                structure. However, it differs from
       different                         a matrix in that each column may have a
       types.                            different
                                         mode.
Coding

  Loops

                                   while
  for
  x <- c(5,12,13)
                                   i <- 1
  for (n in x) print(n^2)
                                   while (i <= 10) i <- i+4
  for (i in 1:10)
                                   i <- 1
  {
                                   while (i <= 10)
  x<-i*3
                                   {
  cos(x)->x
                                   x<-i*3
  print(x)
                                   cos(x)->x
  }
                                   print(c(x,i))
                                   i <- i+1
                                   }
  if-else


  i<-3
  if (i == 4) x <- 1 else x <- 3
Import 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")
Basic Graphs


 Creating a Graph                                Bar Plot
 attach(mtcars)                                  counts <- table(mtcars$gear)
 plot(wt, mpg)                                   barplot(counts, main="Car Distribution",
 abline(lm(mpg~wt))                               xlab="Number of Gears")
 title("Regression of MPG on Weight")




 Pie Charts                                        Boxplot

 slices <- c(10, 12,4, 16, 8)                      boxplot(mpg~cyl,data=mtcars, mai
 lbls <- c("US", "UK", "Australia",                n="Car Milage Data",
 "Germany", "France")                                xlab="Number of Cylinders",
 pie(slices, labels = lbls, main="Pie Chart of     ylab="Miles Per Gallon")
 Countries")
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                 d – density
Binomial                 ?binom                q – quantile
Cauchy                   ?cauchy               r – random
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
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))           cloud(y~x*y)




xyplot(rnorm(100)~rnorm(100)|rnorm(4))            densityplot(rnorm(4))
Package ggplot2

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




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

      Package quantmod                      Package rusquant


getSymbols("GOOG",src="yahoo",      getSymbols("SPFB.RTS", from="2011-01-
from = "2007-01-01“, to =           01", src="Finam“, period="hour" ,
Sys.Date())                         auto.assign=FALSE)

                                    1min, 5min, 10min, 15min,
getSymbols("USD/EUR",src="oanda")   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
                                                      Data management


AAPL['2007']
                                                          to.weekly(AAPL)
AAPL['2007-03/2007']
AAPL['/2007']                                           to.monthly(AAPL)
AAPL['2007-01-03']                                      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”)
Using package RMiFIT


library(RMiFIT )


 getFinData(Symbols = "AFLT",period = “mins")

 getFinData(Symbols = "TGKI",from = "2010-04-01",
 to = "2010-04-01",period = "deals")

 getFinData(Symbols = "AFLT",from = "2012-12-14",
 to = "2012-12-14",src=“Finam” ,period = "tick")


 getFinData(Symbols = "AFLT", from = "2012-12-04",period = "orders")




www.r-group.mifit.ru
Practice
Practice № 1. Working with data


                           TASK:
                           a. Download Data of your instrument
1. AFLT
                           b. Plot price
2. GAZP
                           c. Add technical indicators
3. RTKM
                           d. Calculate price returns
4. ROSN
5. SBER
6. SBERP
7. HYDR
8. LKOH                Commands to help :
9. VTBR                   barChart(AAPL)
10. GMKN                 chartSeries(AAPL,up.col='white',dn.col='blue')
11. SIBN                 AAPL['2007-03/2007']
12. PLZL
                         addMACD()
13. MTSS
                         dailyReturn(AAPL)
14. CHMF
15. SNGS
Practice № 2. Distribution of price returns


1. AFLT
2. GAZP                   TASK :
3. RTKM                   a. Download Data of your instrument
4. ROSN                   b. Calculate returns of close prices
5. SBER                   c. Plot density of distribution
6. SBERP                  d. Estimate parameters of distribution
7. HYDR                   e. Plot in one graph empirical and theoretical
8. LKOH                      distributions
9. VTBR
10. GMKN
11. SIBN            Commands to help :
12. PLZL
13. MTSS             getSymbols("AFLT",
14. CHMF             src="Finam", period="day" , auto.assign=FALSE)
15. SNGS
                    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. AFLT
2. GAZP                  TASK :
3. RTKM                  a. Download Index Data (ticker: “MICEX”)
4. ROSN                  b. Download Data of your instrument
5. SBER                  c. Calculate returns of close prices
6. SBERP                 d. Calculate correlation of returns
7. HYDR                  e. Calculate correlation of returns in 2012 year
8. LKOH                  f. Calculate correlation of returns in 2008 year
9. VTBR                  g. Calculate autocorrelation function of returns
10. GMKN
11. SIBN            Commands to help :
12. PLZL
13. MTSS            getSymbols(" MICEX ",
14. CHMF            src="Finam", period="day" , auto.assign=FALSE)
15. SNGS
                    AAPL['2007']
                    AAPL['2007-03/2007']
                    AAPL['/2007']
                    AAPL['2007-01-03']
Practice № 4. Volatility estimation


1. AFLT
2. GAZP                  TASK :
3. RTKM                  a. Download Data of your instrument
4. ROSN                  b. Calculate returns of close prices
5. SBER                  c. Plot clusterization of volatility
6. SBERP                 d. Estimate model garch
7. HYDR                  e. garchFit(data=x) @sigma.t
8. LKOH
9. VTBR
10. GMKN
11. SIBN            Commands to help :
12. PLZL
13. MTSS            AAPL['2007']
14. CHMF            AAPL['2007-03/2007']
15. SNGS            AAPL['/2007']
                    AAPL['2007-01-03']
Practice № 5.Estimation of long memory of order flow


1. AFLT
2. GAZP                 TASK :
3. RTKM                 a. Download order data of your instrument
4. ROSN                 b. Calculate long memory of limit orders, cancellations
5. SBER
6. SBERP
7. HYDR
8. LKOH
9. VTBR
10. GMKN
11. SIBN           Commands to help :
12. PLZL
13. MTSS           help (getFinData)
14. CHMF
15. SNGS
The practical task № 6. Calculation of VaR


1. AFLT
2. GAZP                  TASK :
3. RTKM                  a. Download Data of your instrument
4. ROSN                  b. Calculate returns of close prices
5. SBER                  c. Calculate historical VaR
6. SBERP                 d. Calculate parametric VaR
7. HYDR                  e. library(PerformanceAnalytics)
8. LKOH                  f. help(VaR)
9. VTBR
10. GMKN
11. SIBN            Commands to help :
12. PLZL
13. MTSS            quantile(x,0.95, na.rm=TRUE)
14. CHMF
15. SNGS            AAPL['2007']
                    AAPL['2007-03/2007']
                    AAPL['/2007']
                    AAPL['2007-01-03']
The practical task № 7. Estimate LPPL model


TASK :
a. Download Index Data(ticker: “MICEX”) from 2001 to 2009
b. Estimate parameters of model LPPL


MODEL LPPL:




Commands to help :

help(nsl)
Вопросы?




arbuzov@prognoz.ru

Mais conteúdo relacionado

Mais procurados

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
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
stasimus
 

Mais procurados (20)

NumPy Refresher
NumPy RefresherNumPy Refresher
NumPy Refresher
 
Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)
 
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)
 
Numpy Talk at SIAM
Numpy Talk at SIAMNumpy Talk at SIAM
Numpy Talk at SIAM
 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator Pattern
 
Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303
 
20090622 Bp Study#22
20090622 Bp Study#2220090622 Bp Study#22
20090622 Bp Study#22
 
Python3 cheatsheet
Python3 cheatsheetPython3 cheatsheet
Python3 cheatsheet
 
(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
 
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
 
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...
 
Advanced Data Visualization Examples with R-Part II
Advanced Data Visualization Examples with R-Part IIAdvanced Data Visualization Examples with R-Part II
Advanced Data Visualization Examples with R-Part II
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
 
Q plot tutorial
Q plot tutorialQ plot tutorial
Q plot tutorial
 
Matlab plotting
Matlab plottingMatlab plotting
Matlab plotting
 
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.
 
Rsplit apply combine
Rsplit apply combineRsplit apply combine
Rsplit apply combine
 
Pandas Cheat Sheet
Pandas Cheat SheetPandas Cheat Sheet
Pandas Cheat Sheet
 
Programs in array using SWIFT
Programs in array using SWIFTPrograms in array using SWIFT
Programs in array using SWIFT
 

Semelhante a Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav

Semelhante a Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav (20)

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
 
R
RR
R
 
R code for data manipulation
R code for data manipulationR code for data manipulation
R code for data manipulation
 
R code for data manipulation
R code for data manipulationR code for data manipulation
R code for data manipulation
 
R Language Introduction
R Language IntroductionR Language Introduction
R Language Introduction
 
Introduction to R
Introduction to RIntroduction to R
Introduction to R
 
CLUSTERGRAM
CLUSTERGRAMCLUSTERGRAM
CLUSTERGRAM
 
R Workshop for Beginners
R Workshop for BeginnersR Workshop for Beginners
R Workshop for Beginners
 
Practical data science_public
Practical data science_publicPractical data science_public
Practical data science_public
 
Introduction to R programming
Introduction to R programmingIntroduction to R programming
Introduction to R programming
 
Rcommands-for those who interested in R.
Rcommands-for those who interested in R.Rcommands-for those who interested in R.
Rcommands-for those who interested in R.
 
BUilt in Functions and Simple programs in R.pdf
BUilt in Functions and Simple programs in R.pdfBUilt in Functions and Simple programs in R.pdf
BUilt in Functions and Simple programs in R.pdf
 
R language introduction
R language introductionR language introduction
R language introduction
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
 
A quick introduction to R
A quick introduction to RA quick introduction to R
A quick introduction to R
 
Артём Акуляков - F# for Data Analysis
Артём Акуляков - F# for Data AnalysisАртём Акуляков - F# for Data Analysis
Артём Акуляков - F# for Data Analysis
 
Basic R Data Manipulation
Basic R Data ManipulationBasic R Data Manipulation
Basic R Data Manipulation
 
3 Data Structure in R
3 Data Structure in R3 Data Structure in R
3 Data Structure in R
 
Scala Collections
Scala CollectionsScala Collections
Scala Collections
 
Scala collections
Scala collectionsScala collections
Scala collections
 

Último

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Último (20)

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 

Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav

  • 1. Using R in financial modeling Арбузов Вячеслав arbuzov@prognoz.ru Perm State National Research University
  • 4. Coding Simple Mathematical functions in R 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)
  • 6. Coding Useful commands to create a vector assignment operator 1:10 <- or -> seq(1,10) x<-10 rep(1,10) 10->X working with vectors case sensitive A<-1:10 X B<-c(2,4,8) x A*B A>B R is a case sensitive language. FOO, Foo, and foo are three different objects!
  • 7. Coding Matrix Matrix Operations y <- matrix(nrow=2,ncol=2) x %*% y y[1,1] <- 1 x* y y[2,1] <- 2 3*y y[1,2] <- 3 x+y y[2,2] <- 4 x+3 x <- matrix(1:4, 2, 2) x[,2] x[1,] rbind(x,y)->z cbind(x,y) z[1:2,] A matrix is a vector z[z[,1]>1,] with two additional z[which(z[,1]>1),1] attributes: the number of rows and the number of columns
  • 8. Coding Data Frame List kids <- c("Jack","Jill") j <- list(name="Joe", salary=55000, union=T) ages <- c(12,10) j$salary d <- data.frame(kids,ages) j[["salary"]] d[1,] j[[2]] d[,1] j$name [2]<-”Poll” d[[1]] j$salary[2]<-10000 j$union [2]<-”F” Arrays my.array <- array(1:24, dim=c(3,4,2)) In contrast to a vector, in which all elements must be of the same a data frame is like a mode, R’s list matrix, with a two-dimensional rows- structure can andcolumns combine objects of structure. However, it differs from different a matrix in that each column may have a types. different mode.
  • 9. Coding Loops while for x <- c(5,12,13) i <- 1 for (n in x) print(n^2) while (i <= 10) i <- i+4 for (i in 1:10) i <- 1 { while (i <= 10) x<-i*3 { cos(x)->x x<-i*3 print(x) cos(x)->x } print(c(x,i)) i <- i+1 } if-else i<-3 if (i == 4) x <- 1 else x <- 3
  • 10. Import 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")
  • 11. Basic Graphs Creating a Graph Bar Plot attach(mtcars) counts <- table(mtcars$gear) plot(wt, mpg) barplot(counts, main="Car Distribution", abline(lm(mpg~wt)) xlab="Number of Gears") title("Regression of MPG on Weight") Pie Charts Boxplot slices <- c(10, 12,4, 16, 8) boxplot(mpg~cyl,data=mtcars, mai lbls <- c("US", "UK", "Australia", n="Car Milage Data", "Germany", "France") xlab="Number of Cylinders", pie(slices, labels = lbls, main="Pie Chart of ylab="Miles Per Gallon") Countries")
  • 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 d – density Binomial ?binom q – quantile Cauchy ?cauchy r – random 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
  • 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)
  • 18. Correlations y<-rnorm(1000) cor(x,y) cor(x,y, ,method = ?????) acf(y)
  • 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)
  • 22. Package lattice library(lattice) bwplot(sign(rnorm(30))~rnorm(30)|runif(3)) cloud(y~x*y) xyplot(rnorm(100)~rnorm(100)|rnorm(4)) densityplot(rnorm(4))
  • 23. Package ggplot2 library(ggplot2) qplot(rnorm(100)) qplot(rnorm(100),geom='density') qplot(rnorm(100),rnorm(100), qplot(rnorm(100),rnorm(100)) size=sign(rnorm(100))+1)
  • 24. Download Data Package quantmod Package rusquant getSymbols("GOOG",src="yahoo", getSymbols("SPFB.RTS", from="2011-01- from = "2007-01-01“, to = 01", src="Finam“, period="hour" , Sys.Date()) auto.assign=FALSE) 1min, 5min, 10min, 15min, getSymbols("USD/EUR",src="oanda") 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 Data management AAPL['2007'] to.weekly(AAPL) AAPL['2007-03/2007'] AAPL['/2007'] to.monthly(AAPL) AAPL['2007-01-03'] 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”)
  • 27. Using package RMiFIT library(RMiFIT ) getFinData(Symbols = "AFLT",period = “mins") getFinData(Symbols = "TGKI",from = "2010-04-01", to = "2010-04-01",period = "deals") getFinData(Symbols = "AFLT",from = "2012-12-14", to = "2012-12-14",src=“Finam” ,period = "tick") getFinData(Symbols = "AFLT", from = "2012-12-04",period = "orders") www.r-group.mifit.ru
  • 29. Practice № 1. Working with data TASK: a. Download Data of your instrument 1. AFLT b. Plot price 2. GAZP c. Add technical indicators 3. RTKM d. Calculate price returns 4. ROSN 5. SBER 6. SBERP 7. HYDR 8. LKOH Commands to help : 9. VTBR barChart(AAPL) 10. GMKN chartSeries(AAPL,up.col='white',dn.col='blue') 11. SIBN AAPL['2007-03/2007'] 12. PLZL addMACD() 13. MTSS dailyReturn(AAPL) 14. CHMF 15. SNGS
  • 30. Practice № 2. Distribution of price returns 1. AFLT 2. GAZP TASK : 3. RTKM a. Download Data of your instrument 4. ROSN b. Calculate returns of close prices 5. SBER c. Plot density of distribution 6. SBERP d. Estimate parameters of distribution 7. HYDR e. Plot in one graph empirical and theoretical 8. LKOH distributions 9. VTBR 10. GMKN 11. SIBN Commands to help : 12. PLZL 13. MTSS getSymbols("AFLT", 14. CHMF src="Finam", period="day" , auto.assign=FALSE) 15. SNGS 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 1. AFLT 2. GAZP TASK : 3. RTKM a. Download Index Data (ticker: “MICEX”) 4. ROSN b. Download Data of your instrument 5. SBER c. Calculate returns of close prices 6. SBERP d. Calculate correlation of returns 7. HYDR e. Calculate correlation of returns in 2012 year 8. LKOH f. Calculate correlation of returns in 2008 year 9. VTBR g. Calculate autocorrelation function of returns 10. GMKN 11. SIBN Commands to help : 12. PLZL 13. MTSS getSymbols(" MICEX ", 14. CHMF src="Finam", period="day" , auto.assign=FALSE) 15. SNGS AAPL['2007'] AAPL['2007-03/2007'] AAPL['/2007'] AAPL['2007-01-03']
  • 32. Practice № 4. Volatility estimation 1. AFLT 2. GAZP TASK : 3. RTKM a. Download Data of your instrument 4. ROSN b. Calculate returns of close prices 5. SBER c. Plot clusterization of volatility 6. SBERP d. Estimate model garch 7. HYDR e. garchFit(data=x) @sigma.t 8. LKOH 9. VTBR 10. GMKN 11. SIBN Commands to help : 12. PLZL 13. MTSS AAPL['2007'] 14. CHMF AAPL['2007-03/2007'] 15. SNGS AAPL['/2007'] AAPL['2007-01-03']
  • 33. Practice № 5.Estimation of long memory of order flow 1. AFLT 2. GAZP TASK : 3. RTKM a. Download order data of your instrument 4. ROSN b. Calculate long memory of limit orders, cancellations 5. SBER 6. SBERP 7. HYDR 8. LKOH 9. VTBR 10. GMKN 11. SIBN Commands to help : 12. PLZL 13. MTSS help (getFinData) 14. CHMF 15. SNGS
  • 34. The practical task № 6. Calculation of VaR 1. AFLT 2. GAZP TASK : 3. RTKM a. Download Data of your instrument 4. ROSN b. Calculate returns of close prices 5. SBER c. Calculate historical VaR 6. SBERP d. Calculate parametric VaR 7. HYDR e. library(PerformanceAnalytics) 8. LKOH f. help(VaR) 9. VTBR 10. GMKN 11. SIBN Commands to help : 12. PLZL 13. MTSS quantile(x,0.95, na.rm=TRUE) 14. CHMF 15. SNGS AAPL['2007'] AAPL['2007-03/2007'] AAPL['/2007'] AAPL['2007-01-03']
  • 35. The practical task № 7. Estimate LPPL model TASK : a. Download Index Data(ticker: “MICEX”) from 2001 to 2009 b. Estimate parameters of model LPPL MODEL LPPL: Commands to help : help(nsl)