Below are the solutions to these exercises on Analysis of stock prices part 2.

#################### # # # Exercise 1 # # # #################### # read data data <- read.csv("http://www.r-exercises.com/wp-content/uploads/2016/07/data.csv", sep=",", header=TRUE) # data frame from exercise 6, part 1 data.close <- reshape(data[c("Symbol", "Date", "Close")], timevar="Symbol", idvar="Date", direction="wide") colnames(data.close) <- c("Date", as.character(unique(data$Symbol))) data.close$Date <- as.Date(data.close$Date) data.close <- data.close[with(data.close, order(Date)), ] last.90 <- data.close[(NROW(data.close)-90):NROW(data.close), ] plot(type='l', x = last.90$Date, y = last.90$X, ylab="Closing price", xlab="", main="Closing price of 'X'")

#################### # # # Exercise 2 # # # #################### # data frame from exercise 7, part 1 data.return <- data.frame(Date = data.close$Date[-1], sapply(data.close[-1], function(x) { diff(x)/x[-length(x)]+1 })) data.return$Date <- as.Date(data.return$Date) plot(x=data.return$Date, y=rowMeans(data.return[-1], na.rm=TRUE), type=c("l"), xlab="", ylab="Daily return", main=paste("Average daily return of ", NCOL(data.return)-1, " stocks"))

#################### # # # Exercise 3 # # # #################### pairs(data.close[, -1])

#################### # # # Exercise 4 # # # #################### plot(type="l", x = data.close$Date, y = data.close$YHOO, ylab = "Closing price", xlab = "", main = "Closing prices of YHOO") lines(x = data.close$Date, y = lm(data.close$YHOO~data.close$Date)$fitted.values, col="red")

#################### # # # Exercise 5 # # # #################### summary(lm(data.close$GE~data.close$Date))$r.squared

## [1] 0.5957529

#################### # # # Exercise 6 # # # #################### y <- subset(data.close, data.close$Date >= "2016-01-01")$YHOO x <- subset(data.close, data.close$Date >= "2016-01-01")$Date summary(lm(y~x))

## ## Call: ## lm(formula = y ~ x) ## ## Residuals: ## Min 1Q Median 3Q Max ## -4.6767 -1.1440 0.0254 1.2768 2.8958 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) -8.247e+02 4.288e+01 -19.23 <2e-16 *** ## x 5.083e-02 2.537e-03 20.04 <2e-16 *** ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ## ## Residual standard error: 1.716 on 136 degrees of freedom ## Multiple R-squared: 0.747, Adjusted R-squared: 0.7451 ## F-statistic: 401.5 on 1 and 136 DF, p-value: < 2.2e-16

```
1
```

## [1] 1

#################### # # # Exercise 7 # # # #################### y <- subset(data.close, data.close$Date >= "2016-01-01")$GOOG x <- subset(data.close, data.close$Date >= "2016-01-01")$Date lm(y~x)

## ## Call: ## lm(formula = y ~ x) ## ## Coefficients: ## (Intercept) x ## 1204.70121 -0.02884

#################### # # # Exercise 8 # # # #################### conf.interval <- predict(lm(y~x), interval = "prediction")

## Warning in predict.lm(lm(y ~ x), interval = "prediction"): predictions on current data refer to _future_ responses

#################### # # # Exercise 9 # # # #################### # create data frame containing ten days after recorded period newdata <- data.frame(x = data.frame(x = seq(max(x)+1, by=1, length.out=10))) # fit the model model.fit <- lm(y~x)$fitted.values # make prediction pred.goog <- predict(lm(y ~ x), newdata, interval = "prediction") #################### # # # Exercise 10 # # # #################### # actual data plot(type="l", x = x, y = y, ylab = "Closing prices", xlab = "", main="Closing prices of GOOG", ylim = range(c(max(y, conf.interval[, 'upr'], pred.goog[, 'upr']), min(y, conf.interval[, 'lwr'], pred.goog[, 'lwr']))), xlim = (range(c(min(x), max(newdata$x))))) # model lines(x = x, y = model.fit, col="red") # 95% confidence interval lines(x = x, y = conf.interval[, 'lwr'], col="blue") lines(x = x, y = conf.interval[, 'upr'], col="blue") # prediction lines(x=newdata$x, y=pred.goog[, "fit"], col="brown") # 95% confindence interval for prediction lines(x=newdata$x, y=pred.goog[, "lwr"], col="brown") lines(x=newdata$x, y=pred.goog[, "upr"], col="brown")

**What's next:**

- Become a Top R Programmer Fast with our Individual Coaching Program
- Explore all our (>4000) R exercises
- Find an R course using our R Course Finder directory
- Subscribe to receive weekly updates and bonus sets by email
- Share with your friends and colleagues using the buttons below

Dr. Pankaj K Agarwal says

Thanks indeed. Thoroughly enjoyed and learnt. Keep posting.

Miodrag Sljukic says

Thank’s đź™‚

Si Hu says

I love your exercises — but I think something is wrong with the code in the answer to exercise 1. Instead of getting prices for the last 90 days, the code produces data (and a plot) for all the prices other than those of the last 90 days.

I know there is an obvious tweak, but not sure what it is. Can you help?