SlideShare a Scribd company logo
1 of 34
Регрессионный анализ
Финансовая эконометрика
Содержание
• параметрическая регрессия
• непараметрическая регрессия
Параметрическая регрессия
Линейная параметрическая регрессия
•
Параметрическая регрессия в R
# исходные данные
library(datasets)
ozone <- airquality$Ozone
rad <- airquality$Solar.R

rem <- is.na(ozone) | is.na(rad)
ozone <- ozone[!rem]; rad <- rad[!rem]

# разделим выборку на обучающую и экзаменующую
N <- length(ozone); E <- 20; T <- N-E
eval.obs <- sample(1:N,size=E,replace=FALSE)
train.obs <- (1:N)[-eval.obs]

t.rad <- rad[train.obs]; t.ozone <- ozone[train.obs]
e.rad <- rad[eval.obs]; e.ozone <- ozone[eval.obs]
Параметрическая регрессия в R
# регрессионная модель
fit.par <- lm(ozone ~ radiation,
data=data.frame(radiation=t.rad,ozone=t.ozone),
weights=NULL)


# другой вариант
fit.par <- lm(t.ozone ~ t.rad)
Анализ качества модели
summary(fit.par)
            Estimate Std. Error t value Pr(>|t|)
(Intercept) 17.85005    7.37407   2.421 0.017524 *
radiation    0.13726    0.03613   3.799 0.000265 ***
Multiple R-squared: 0.1395,     Adjusted R-squared: 0.1299
F-statistic: 14.43 on 1 and 89 DF, p-value: 0.0002655

fit.par$coefficients
fit.par$residuals
fit.par$fitted.values




                                               150
plot(t.rad,t.ozone,
xlab="radiation",ylab="ozone")
                                               100
points(t.rad,
                                       ozone




fit.par$fitted.values,
col="blue",pch=20)
                                               50
                                               0




                                                     0   50   100   150          200   250   300

                                                                     radiation
Histogram of res




   Анализ остатков модели




                                         0.015
    res <- fit.par$residuals




                                         0.010
                               Density
    hist(res)
    plot(res,type="l")




                                         0.005
    # тесты на нормальность
    library(fBasics)




                                         0.000
    shapiro.test(res)                                -50        0                   50        100

                                                                            res
    jarqueberaTest(res)




                                         100
                                         50
                               res

                                         0




      Тест        p.value
Shapiro – Wilks   0.000
                                         -50




Jarque – Bera     0.000                          0         20          40                60   80

                                                                            Index
Переформулировка модели
fit.par <- lm(log(ozone) ~ rad + rad2,
data=data.frame(rad=t.rad,rad2=t.rad^2,ozone=t.ozone))
              Estimate Std. Error   t value Pr(>|t|)
(Intercept) 2.024e+00 2.235e-01    9.058 3.12e-14 ***
rad          1.673e-02 3.117e-03   5.367 6.43e-07 ***
rad2        -3.903e-05 9.362e-06 -4.169 7.14e-05 ***
Multiple R-squared: 0.3456,    Adjusted R-squared: 0.3307




                                                   150
                                                   100
                                           ozone

                                                   50
                                                   0




                                                         0   50   100   150          200   250   300

                                                                         radiation
Histogram of res




   Анализ остатков модели




                                                   0.6
                                                   0.5
                                                   0.4
    res <- fit.par$residuals




                               Density

                                                   0.3
    hist(res)
    plot(res,type="l")




                                                   0.2
                                                   0.1
    # тесты на нормальность
    library(fBasics)




                                                   0.0
    shapiro.test(res)                                     -1.5   -1.0        -0.5        0.0     0.5   1.0        1.5

                                                                                         res
    jarqueberaTest(res)




                                                   1.0
                                                   0.5
                               fit.par$residuals

                                                   0.0
                                                   -0.5




      Тест        p.value
                                                   -1.0




Shapiro – Wilks   0.055
Jarque – Bera     0.154                                   0             20          40           60          80

                                                                                         Index
Тесты на гетероскедастичность
•
Тесты на гетероскедастичность
•
Тесты на гетероскедастичность в R
library(lmtest)

# тест Бреуша–Пагана
bptest(fit.par,varformula=NULL,data=NULL,studentize=FALSE)
Breusch-Pagan test
data: fit.par
BP = 0.4585, df = 2, p-value = 0.7951




# тест Голдфелда–Куандта
gqtest(fit.par,fraction=25,alternative="two.sided")
 Goldfeld-Quandt test
data: fit.par
GQ = 0.9161, df1 = 30, df2 = 30, p-value = 0.5941
Тест на причинность
•
Тест на автокорреляцию
•
Переформулировка модели
    ar1 <- log(t.ozone[1:(T-1)])
    fit.par <- lm(log(ozone) ~ rad + rad2 + ar1,
    data=data.frame(ozone=t.ozone[2:T],rad=t.rad[2:T],
    rad2=t.rad[2:T]^2))
                 Estimate Std. Error t value Pr(>|t|)
    (Intercept) 9.149e-01 3.057e-01    2.993 0.003606 **
    rad          1.523e-02 3.414e-03   4.461 2.45e-05 ***
    rad2        -3.236e-05 1.024e-05 -3.160 0.002178 **
    ar1          3.087e-01 8.281e-02   3.727 0.000346 ***
    Multiple R-squared: 0.4867,
    Adjusted R-squared: 0.4688




                                                          150
      Тест        p.value

                                                          100
Shapiro – Wilks    0.800                          ozone



Jarque – Bera      0.854
                                                          50




Breusch–Pagan      0.438
Goldfeld–Quandt    0.643
                                                          0




Durbin–Watson      0.448                                        0   50   100   150          200   250   300

                                                                                radiation
Построение прогноза
•
Построение прогноза в R
frc.par <- predict(fit.par,
  newdata=data.frame(rad=e.rad,rad2=e.rad^2,
  ar1=log(ozone[eval.obs-1])), se.fit=TRUE,
  interval="prediction",level=0.90)

frc.par$fit      # прогнозные значения и интервалы
frc.par$se.fit   # стандартные ошибки




                                          200
                                          150
                                  ozone

                                          100
                                          50
                                          0




                                                50   100   150          200   250   300

                                                            radiation
Непараметрическая регрессия
Непараметрическая регрессия
•
Непараметрическая регрессия в R
# расчёт величины h
library(np)
bw <- npregbw(ozone ~ rad, ckertype="gaussian",
bwtype="fixed", data=data.frame(ozone=t.ozone,rad=t.rad))
h <- bw$bw

# ядро и функция Надарая – Уотсона
kern <- function(x) exp(-(x^2/2))/sqrt(2*pi)

NW <- function(x, x.dat, y.dat, h) {
  K1 <- K2 <- 0
  N <- length(y.dat)
  for (i in 1:N) {
    K1 <- K1 + kern((x-x.dat[i])/h)*y.dat[i]
    K2 <- K2 + kern((x-x.dat[i])/h)
  }
  K1 / K2
}
График оценки
plot(t.rad,t.ozone)
points(t.rad, NW(t.rad,t.rad,t.ozone,h), pch=20, col="blue")




                                140
                                120
                                100
                                80
                      t.ozone

                                60
                                40
                                20
                                0




                                      0   50   100   150        200   250   300

                                                      t.radiation
График оценки (другой вариант)
plot(t.rad,t.ozone)
fit.npar <- npreg(bw)
ozone.hat <- predict(fit.npar)
points(t.rad,ozone.hat,pch=20,col="blue")




                                     140
                                     120
                                     100
                                     80
                           t.ozone

                                     60
                                     40
                                     20
                                     0




                                           0   50   100   150        200   250   300

                                                           t.radiation
•
Построение прогноза в R
e <- t.ozone - ozone.hat
s2 <- var(e)
g <- (4/(3*T))^(1/5)*sqrt(s2)

# симулированные значения ошибок
b <- 10^4
e.star <- e[sample(1:T,size=b,replace=TRUE)]+g*rnorm(b)
e.star <- sort(e.star)

# прогноз и доверительные границы
alpha <- 0.1
y <- predict(fit.npar,newdata=data.frame(rad=e.rad))
bottom <- y + e.star[alpha/2*b]
top <- y + e.star[(1-alpha/2)*b]
Построение прогноза в R
z <- order(e.rad)
plot(e.rad,e.ozone,ylim=range(c(top,bottom)))
lines(e.rad[z],y[z],col="blue",lwd=2)
lines(e.rad[z],top[z],col="red",lty="dashed")
lines(e.rad[z],bottom[z],col="red",lty="dashed")




                                       100
                                       80
                                       60
                             e.ozone

                                       40
                                       20
                                       0
                                       -20




                                             0   50   100   150       200   250   300

                                                              e.rad
•
Построение прогноза в R
# моделирование условной дисперсии
s2.hat <- (e-mean(e))^2
h.res <- npregbw(s2.hat ~ rad, ckertype="gaussian",
bwtype="fixed", data=data.frame(rad=t.rad))
res.npar <- npreg(h.res)

# метод бутстрапа
b <- 10^4; alpha <- 0.1
top <- bottom <- numeric(E)
y <- predict(fit.npar,newdata=data.frame(rad=e.rad))
for (i in 1:E) {

    s2 <- predict(res.npar,newdata=data.frame(rad=e.rad[i]))
    g <- (4/(3*T))^(1/5)*sqrt(s2)

    e.star <- e[sample(1:T,size=b,replace=TRUE)]+g*rnorm(b)
    e.star <- sort(e.star)

    bottom[i] <- y[i] + e.star[alpha/2*b]
    top[i] <- y[i] + e.star[(1-alpha/2)*b]
}
Построение прогноза в R
z <- order(e.rad)
plot(e.rad,e.ozone,ylim=range(c(top,bottom)))
lines(e.rad[z],y[z],col="blue",lwd=2)
lines(e.rad[z],top[z],col="red",lty="dashed")
lines(e.rad[z],bottom[z],col="red",lty="dashed")




                                       120
                                       100
                                       80
                                       60
                             e.ozone

                                       40
                                       20
                                       0
                                       -20




                                             0   50   100   150       200   250   300

                                                              e.rad
Непараметрическая регрессия,
двумерный случай
•
Множественная регрессия в R
# добавочная объясняющая переменная
temp <- airquality$Temp
temp <- temp[!rem]
t.temp <- temp[train.obs]; e.temp <- temp[eval.obs]

# регрессионная модель
bw2 <- npregbw(ozone ~ rad + temp,
  ckertype="gaussian", bwtype="fixed",
  data=data.frame(ozone=t.ozone,rad=t.rad,temp=t.temp))
rad.temp <- cbind(t.rad,t.temp)
ozone.hat <- NW2(rad.temp,rad.temp,t.ozone,bw2$bw,2)

# альтернативный вариант
ozone.reg <- npreg(bw2)
ozone.hat <- predict(ozone.reg)
Множественная регрессия в R
zt <- order(t.rad)
plot(t.ozone[zt])
lines(ozone.hat[zt],col="blue",lwd=2)




                                       150
                                       100
                         t.ozone[zt]

                                       50
                                       0




                                             0   20   40           60   80

                                                           Index
Построение прогноза

                          Homoskedastic variance                                Heteroskedastic variance
             120




                                                                      120
             100




                                                                      100
             80




                                                                      80
e.ozone[z]




                                                         e.ozone[z]
             60




                                                                      60
             40




                                                                      40
             20




                                                                      20
             0




                                                                      0
             -20




                      5           10           15   20                      5            10            15   20

                                   Index                                                  Index
Домашнее задание
• рассмотреть данные о величине спроса на деньги в пакете
  lmtest: moneydemand
• разделить выборку на обучающую и экзаменующую части
• на пространстве обучающей выборки построить
  параметрическую и непараметрическую регрессионные
  модели с эндогенной переменной logM
• проверить качество параметрической модели с помощью
  тестов на нормальность, гетероскедастичность и
  автокорреляцию
• построить прогноз и доверительные интервалы для
  эндогенной переменной на экзаменующей выборке
• написать комментарии

More Related Content

Viewers also liked

4. непараметрическое моделирование
4. непараметрическое моделирование4. непараметрическое моделирование
4. непараметрическое моделирование
msuteam
 
Venture investments structuring
Venture investments structuringVenture investments structuring
Venture investments structuring
msuteam
 
Communal Violence Bill - Summary - Hindi
Communal Violence Bill - Summary - HindiCommunal Violence Bill - Summary - Hindi
Communal Violence Bill - Summary - Hindi
communal
 
Cataluña islámica
Cataluña islámicaCataluña islámica
Cataluña islámica
Acorrecto
 

Viewers also liked (13)

4. непараметрическое моделирование
4. непараметрическое моделирование4. непараметрическое моделирование
4. непараметрическое моделирование
 
Sound waves
Sound wavesSound waves
Sound waves
 
Venture investments structuring
Venture investments structuringVenture investments structuring
Venture investments structuring
 
Cmf enrolled students_2016_new
Cmf enrolled students_2016_newCmf enrolled students_2016_new
Cmf enrolled students_2016_new
 
Cmf 2016-2017
Cmf 2016-2017Cmf 2016-2017
Cmf 2016-2017
 
A study on construction of optimal portfolio using sharpe’s single index model
A study on construction of optimal portfolio using sharpe’s single index modelA study on construction of optimal portfolio using sharpe’s single index model
A study on construction of optimal portfolio using sharpe’s single index model
 
Apresentação atmo setembro_2016
Apresentação atmo setembro_2016Apresentação atmo setembro_2016
Apresentação atmo setembro_2016
 
Presentación Road Show Island Tours Marzo 2017
Presentación Road Show Island Tours Marzo 2017Presentación Road Show Island Tours Marzo 2017
Presentación Road Show Island Tours Marzo 2017
 
31 1-earthsoft-effective teachers
31 1-earthsoft-effective teachers31 1-earthsoft-effective teachers
31 1-earthsoft-effective teachers
 
Communal Violence Bill - Summary - Hindi
Communal Violence Bill - Summary - HindiCommunal Violence Bill - Summary - Hindi
Communal Violence Bill - Summary - Hindi
 
Gestão na prática & Gestão Estratégica
Gestão na prática & Gestão EstratégicaGestão na prática & Gestão Estratégica
Gestão na prática & Gestão Estratégica
 
Cataluña islámica
Cataluña islámicaCataluña islámica
Cataluña islámica
 
What If Solar String Monitoring Was An Affordable, Temporary Solution?
What If Solar String Monitoring Was An Affordable, Temporary Solution?What If Solar String Monitoring Was An Affordable, Temporary Solution?
What If Solar String Monitoring Was An Affordable, Temporary Solution?
 

5. регрессионный анализ

  • 2. Содержание • параметрическая регрессия • непараметрическая регрессия
  • 5. Параметрическая регрессия в R # исходные данные library(datasets) ozone <- airquality$Ozone rad <- airquality$Solar.R rem <- is.na(ozone) | is.na(rad) ozone <- ozone[!rem]; rad <- rad[!rem] # разделим выборку на обучающую и экзаменующую N <- length(ozone); E <- 20; T <- N-E eval.obs <- sample(1:N,size=E,replace=FALSE) train.obs <- (1:N)[-eval.obs] t.rad <- rad[train.obs]; t.ozone <- ozone[train.obs] e.rad <- rad[eval.obs]; e.ozone <- ozone[eval.obs]
  • 6. Параметрическая регрессия в R # регрессионная модель fit.par <- lm(ozone ~ radiation, data=data.frame(radiation=t.rad,ozone=t.ozone), weights=NULL) # другой вариант fit.par <- lm(t.ozone ~ t.rad)
  • 7. Анализ качества модели summary(fit.par) Estimate Std. Error t value Pr(>|t|) (Intercept) 17.85005 7.37407 2.421 0.017524 * radiation 0.13726 0.03613 3.799 0.000265 *** Multiple R-squared: 0.1395, Adjusted R-squared: 0.1299 F-statistic: 14.43 on 1 and 89 DF, p-value: 0.0002655 fit.par$coefficients fit.par$residuals fit.par$fitted.values 150 plot(t.rad,t.ozone, xlab="radiation",ylab="ozone") 100 points(t.rad, ozone fit.par$fitted.values, col="blue",pch=20) 50 0 0 50 100 150 200 250 300 radiation
  • 8. Histogram of res Анализ остатков модели 0.015 res <- fit.par$residuals 0.010 Density hist(res) plot(res,type="l") 0.005 # тесты на нормальность library(fBasics) 0.000 shapiro.test(res) -50 0 50 100 res jarqueberaTest(res) 100 50 res 0 Тест p.value Shapiro – Wilks 0.000 -50 Jarque – Bera 0.000 0 20 40 60 80 Index
  • 9. Переформулировка модели fit.par <- lm(log(ozone) ~ rad + rad2, data=data.frame(rad=t.rad,rad2=t.rad^2,ozone=t.ozone)) Estimate Std. Error t value Pr(>|t|) (Intercept) 2.024e+00 2.235e-01 9.058 3.12e-14 *** rad 1.673e-02 3.117e-03 5.367 6.43e-07 *** rad2 -3.903e-05 9.362e-06 -4.169 7.14e-05 *** Multiple R-squared: 0.3456, Adjusted R-squared: 0.3307 150 100 ozone 50 0 0 50 100 150 200 250 300 radiation
  • 10. Histogram of res Анализ остатков модели 0.6 0.5 0.4 res <- fit.par$residuals Density 0.3 hist(res) plot(res,type="l") 0.2 0.1 # тесты на нормальность library(fBasics) 0.0 shapiro.test(res) -1.5 -1.0 -0.5 0.0 0.5 1.0 1.5 res jarqueberaTest(res) 1.0 0.5 fit.par$residuals 0.0 -0.5 Тест p.value -1.0 Shapiro – Wilks 0.055 Jarque – Bera 0.154 0 20 40 60 80 Index
  • 13. Тесты на гетероскедастичность в R library(lmtest) # тест Бреуша–Пагана bptest(fit.par,varformula=NULL,data=NULL,studentize=FALSE) Breusch-Pagan test data: fit.par BP = 0.4585, df = 2, p-value = 0.7951 # тест Голдфелда–Куандта gqtest(fit.par,fraction=25,alternative="two.sided") Goldfeld-Quandt test data: fit.par GQ = 0.9161, df1 = 30, df2 = 30, p-value = 0.5941
  • 16. Переформулировка модели ar1 <- log(t.ozone[1:(T-1)]) fit.par <- lm(log(ozone) ~ rad + rad2 + ar1, data=data.frame(ozone=t.ozone[2:T],rad=t.rad[2:T], rad2=t.rad[2:T]^2)) Estimate Std. Error t value Pr(>|t|) (Intercept) 9.149e-01 3.057e-01 2.993 0.003606 ** rad 1.523e-02 3.414e-03 4.461 2.45e-05 *** rad2 -3.236e-05 1.024e-05 -3.160 0.002178 ** ar1 3.087e-01 8.281e-02 3.727 0.000346 *** Multiple R-squared: 0.4867, Adjusted R-squared: 0.4688 150 Тест p.value 100 Shapiro – Wilks 0.800 ozone Jarque – Bera 0.854 50 Breusch–Pagan 0.438 Goldfeld–Quandt 0.643 0 Durbin–Watson 0.448 0 50 100 150 200 250 300 radiation
  • 18. Построение прогноза в R frc.par <- predict(fit.par, newdata=data.frame(rad=e.rad,rad2=e.rad^2, ar1=log(ozone[eval.obs-1])), se.fit=TRUE, interval="prediction",level=0.90) frc.par$fit # прогнозные значения и интервалы frc.par$se.fit # стандартные ошибки 200 150 ozone 100 50 0 50 100 150 200 250 300 radiation
  • 21. Непараметрическая регрессия в R # расчёт величины h library(np) bw <- npregbw(ozone ~ rad, ckertype="gaussian", bwtype="fixed", data=data.frame(ozone=t.ozone,rad=t.rad)) h <- bw$bw # ядро и функция Надарая – Уотсона kern <- function(x) exp(-(x^2/2))/sqrt(2*pi) NW <- function(x, x.dat, y.dat, h) { K1 <- K2 <- 0 N <- length(y.dat) for (i in 1:N) { K1 <- K1 + kern((x-x.dat[i])/h)*y.dat[i] K2 <- K2 + kern((x-x.dat[i])/h) } K1 / K2 }
  • 22. График оценки plot(t.rad,t.ozone) points(t.rad, NW(t.rad,t.rad,t.ozone,h), pch=20, col="blue") 140 120 100 80 t.ozone 60 40 20 0 0 50 100 150 200 250 300 t.radiation
  • 23. График оценки (другой вариант) plot(t.rad,t.ozone) fit.npar <- npreg(bw) ozone.hat <- predict(fit.npar) points(t.rad,ozone.hat,pch=20,col="blue") 140 120 100 80 t.ozone 60 40 20 0 0 50 100 150 200 250 300 t.radiation
  • 24.
  • 25. Построение прогноза в R e <- t.ozone - ozone.hat s2 <- var(e) g <- (4/(3*T))^(1/5)*sqrt(s2) # симулированные значения ошибок b <- 10^4 e.star <- e[sample(1:T,size=b,replace=TRUE)]+g*rnorm(b) e.star <- sort(e.star) # прогноз и доверительные границы alpha <- 0.1 y <- predict(fit.npar,newdata=data.frame(rad=e.rad)) bottom <- y + e.star[alpha/2*b] top <- y + e.star[(1-alpha/2)*b]
  • 26. Построение прогноза в R z <- order(e.rad) plot(e.rad,e.ozone,ylim=range(c(top,bottom))) lines(e.rad[z],y[z],col="blue",lwd=2) lines(e.rad[z],top[z],col="red",lty="dashed") lines(e.rad[z],bottom[z],col="red",lty="dashed") 100 80 60 e.ozone 40 20 0 -20 0 50 100 150 200 250 300 e.rad
  • 27.
  • 28. Построение прогноза в R # моделирование условной дисперсии s2.hat <- (e-mean(e))^2 h.res <- npregbw(s2.hat ~ rad, ckertype="gaussian", bwtype="fixed", data=data.frame(rad=t.rad)) res.npar <- npreg(h.res) # метод бутстрапа b <- 10^4; alpha <- 0.1 top <- bottom <- numeric(E) y <- predict(fit.npar,newdata=data.frame(rad=e.rad)) for (i in 1:E) { s2 <- predict(res.npar,newdata=data.frame(rad=e.rad[i])) g <- (4/(3*T))^(1/5)*sqrt(s2) e.star <- e[sample(1:T,size=b,replace=TRUE)]+g*rnorm(b) e.star <- sort(e.star) bottom[i] <- y[i] + e.star[alpha/2*b] top[i] <- y[i] + e.star[(1-alpha/2)*b] }
  • 29. Построение прогноза в R z <- order(e.rad) plot(e.rad,e.ozone,ylim=range(c(top,bottom))) lines(e.rad[z],y[z],col="blue",lwd=2) lines(e.rad[z],top[z],col="red",lty="dashed") lines(e.rad[z],bottom[z],col="red",lty="dashed") 120 100 80 60 e.ozone 40 20 0 -20 0 50 100 150 200 250 300 e.rad
  • 31. Множественная регрессия в R # добавочная объясняющая переменная temp <- airquality$Temp temp <- temp[!rem] t.temp <- temp[train.obs]; e.temp <- temp[eval.obs] # регрессионная модель bw2 <- npregbw(ozone ~ rad + temp, ckertype="gaussian", bwtype="fixed", data=data.frame(ozone=t.ozone,rad=t.rad,temp=t.temp)) rad.temp <- cbind(t.rad,t.temp) ozone.hat <- NW2(rad.temp,rad.temp,t.ozone,bw2$bw,2) # альтернативный вариант ozone.reg <- npreg(bw2) ozone.hat <- predict(ozone.reg)
  • 32. Множественная регрессия в R zt <- order(t.rad) plot(t.ozone[zt]) lines(ozone.hat[zt],col="blue",lwd=2) 150 100 t.ozone[zt] 50 0 0 20 40 60 80 Index
  • 33. Построение прогноза Homoskedastic variance Heteroskedastic variance 120 120 100 100 80 80 e.ozone[z] e.ozone[z] 60 60 40 40 20 20 0 0 -20 5 10 15 20 5 10 15 20 Index Index
  • 34. Домашнее задание • рассмотреть данные о величине спроса на деньги в пакете lmtest: moneydemand • разделить выборку на обучающую и экзаменующую части • на пространстве обучающей выборки построить параметрическую и непараметрическую регрессионные модели с эндогенной переменной logM • проверить качество параметрической модели с помощью тестов на нормальность, гетероскедастичность и автокорреляцию • построить прогноз и доверительные интервалы для эндогенной переменной на экзаменующей выборке • написать комментарии