About

This worksheet is your warm-up exercises to getting started with some R for finance, based on examples from the book. It is also your getting started with problems solving (no R required) and expressing your methods/answers using proper mathematical symbols and representations.

Setup

Remember to always set your working directory to the source file location. Go to ‘Session’, scroll down to ‘Set Working Directory’, and click ‘To Source File Location’. Read carefully the below and follow the instructions to complete the tasks and answer any questions. Submit your work to RPubs as detailed in previous notes.

Note

For clarity, tasks/questions to be completed/answered are highlighted in red color (color visible only in preview mode) and numbered according to their particular placement in the task section. Type your answers outside the red color tags!

Quite often you will need to add your own code chunk. Execute sequentially all code chunks, preview, publish, and submit link on Sakai following the naming convention. Make sure to add comments to your code where appropriate. Use own language!

Any sign of plagiarism, will result in dissmissal of work!


Task 1: Charting Stock Time Series

This task follows the book’s R Example 1.1/p. 8 also exhibited in the R-Labs section R Labs1 from the book’s website (*). In order to work with R in finance we need to first install the package quantmod that allows us to retrieve financial data and conduct various statistical analysis.

# Require will load the package only if not installed 
# Dependencies = TRUE makes sure that dependencies are install
if(!require("quantmod",quietly = TRUE))
  install.packages("quantmod",dependencies = TRUE, repos = "https://cloud.r-project.org")
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## Version 0.4-0 included new data defaults. See ?getSymbols.

##### 1A) Insert in the code chunk below the rest of the code to calculate and chart the time series for stock GE. Follow the example in the book. Add comments, where appropriate, explaining what the particular line(s) of code is/are executing/solving for.

##retrieve historical price data for General Electric Co. from Yahoo Finance
getSymbols('GE',src='yahoo', from="2000-01-01", to="2009-12-30")
## 'getSymbols' currently uses auto.assign=TRUE by default, but will
## use auto.assign=FALSE in 0.5-0. You will still be able to use
## 'loadSymbols' to automatically load data. getOption("getSymbols.env")
## and getOption("getSymbols.auto.assign") will still be checked for
## alternate defaults.
## 
## This message is shown once per session and may be disabled by setting 
## options("getSymbols.warning4.0"=FALSE). See ?getSymbols for details.
## 
## WARNING: There have been significant changes to Yahoo Finance data.
## Please see the Warning section of '?getSymbols.yahoo' for details.
## 
## This message is shown once per session and may be disabled by setting
## options("getSymbols.yahoo.warning"=FALSE).
## [1] "GE"
##to see headers of file (OHLCV type)
names(GE)
## [1] "GE.Open"     "GE.High"     "GE.Low"      "GE.Close"    "GE.Volume"  
## [6] "GE.Adjusted"
##to see the data from 1st January 2000 to 20th of January 2000
GE["2000-01-01/2000-01-20"]
##             GE.Open  GE.High   GE.Low GE.Close GE.Volume GE.Adjusted
## 2000-01-03 51.00000 51.22917 49.72917 50.00000  22069800    27.37866
## 2000-01-04 49.08333 49.33333 48.00000 48.00000  22121400    26.28352
## 2000-01-05 47.91667 49.00000 47.52083 47.91667  27292800    26.23787
## 2000-01-06 47.70833 48.97917 47.54167 48.55727  19873200    26.58866
## 2000-01-07 49.33333 50.62500 49.00000 50.43750  20141400    27.61822
## 2000-01-10 50.89583 51.35417 50.37500 50.41667  15226500    27.60681
## 2000-01-11 50.33333 50.89583 50.20833 50.50000  15123000    27.65244
## 2000-01-12 50.35417 51.08333 50.18750 50.66667  18342300    27.74371
## 2000-01-13 51.04167 51.64583 51.00000 51.25000  14953500    28.06313
## 2000-01-14 51.12500 51.54167 49.85417 50.33333  18480300    27.56119
## 2000-01-18 49.87500 49.87500 48.91667 49.33333  18296700    27.01362
## 2000-01-19 48.83333 50.31250 48.75000 49.57290  14849700    27.14478
## 2000-01-20 49.68750 49.91667 47.54167 48.64583  30759000    26.63714
##to see only the adjusted close price for that period
geAdj = GE$GE.Adjusted["2000-01-01/2000-01-20"] ;geAdj
##            GE.Adjusted
## 2000-01-03    27.37866
## 2000-01-04    26.28352
## 2000-01-05    26.23787
## 2000-01-06    26.58866
## 2000-01-07    27.61822
## 2000-01-10    27.60681
## 2000-01-11    27.65244
## 2000-01-12    27.74371
## 2000-01-13    28.06313
## 2000-01-14    27.56119
## 2000-01-18    27.01362
## 2000-01-19    27.14478
## 2000-01-20    26.63714
##compute the maximum, minimum and mean value
max(geAdj); min(geAdj); mean(geAdj)
## [1] 28.06313
## [1] 26.23787
## [1] 27.1946
##make a chart of the financial data
chartSeries(GE)

##make a chart from January to Febuary 2001
chartSeries(GE,TA=NULL,subset='2001-01::2001-02')

Task 2: Comparing Performance of Stocks Time Series

This follows the book’s example 1.3.4 R Lab/p. 34 also R Labs 1 from the book’s website (*).

##### 2A) Insert the code chunk to chart instead the performance of Value Line Index VLIC (sort of benchmark), and four other stocks of your choice over a time period dating back one year from present date.

library("quantmod")
symbols=c('^VLIC','GE','KO','AAPL','MCD')
getSymbols(symbols,src='yahoo',from="2017-11-11",to="2018-11-11")
## [1] "VLIC" "GE"   "KO"   "AAPL" "MCD"
 #obtain adjusted closed
 VLICad = VLIC$VLIC.Adjusted; GEad= GE$GE.Adjusted;
KOad=KO$KO.Adjusted; AAPLad=AAPL$AAPL.Adjusted;
MCDad = MCD$MCD.Adjusted
#compute cumulative sum (cumsum) of daily returns (Delt)
 #Remove first term of the series, with [-1,],
 #since cumsum is not defined for it.
vl = cumsum((Delt(VLICad)*100)[-1,])
ge = cumsum((Delt(GEad)*100)[-1,])
ko = cumsum((Delt(KOad)*100)[-1,])
ap = cumsum((Delt(AAPLad)*100)[-1,])
md = cumsum((Delt(MCDad)*100)[-1,])
 ###range of values for the plot
 lim = c(min(vl,ge,ko,ap,md),max(vl,ge,ko,ap,md))
 ###the plot
plot(vl,main="",ylim=lim,xlab="dates",ylab="% benefits")

lines(ge,col="green"); lines(ko,col="red")

lines(ap,col="violet"); lines(md,col="yellow")

legend(x="topleft",cex=0.4,c("VLIC","GE","KO","AAPL","MCD"),
lty=1, col=c("black","green","red","violet","yellow"))

##### 2B) Write the mathematical form/representation, using proper math symbols, to describe the formula being calculated and plotted in the code

The mathematical form/representation of formula being calculated and plotted in the code is \[\sum_{i=2}^{t} ri\] to compute the cumulative sum of daily returns and remove the first term of the series.

##### 2C) Write a paragraph, in your own words, comparing the stock performances based on your assessment of the companies general business and their valuation vis-a-vis the market overall performance, and pertinent econonomical factors.

By using the above formula, it is resonable that higher cumulative sum of daily returns means better stoke performance. From the chart we can see that the performance of GE company goes in the opposite direction as the market overall performance does and become worse and worse. We also know that the present trend of stock price of GE company is going down continuously because it has high proportion of bebt and even has negative profit in the quarter statements. Besides, it need to pay a large amount of annuity to retired workers, which also increases the cost and weakens their profit. The performances of both Coca-Cola company and McDonald corporation go in the same direction as the market overall performance does.These two comanies are both in the food industry. By analizing the chart we can see that the performance of the whold food industry is in the average level of the whole US economy, thus similar to the market overall performance. However, the performance of Apple company outshines the the market overall’s, especially this year. As we all know, Apple’s general business is high-tech products, and high-technology industry is a promising industry now. So it is not surprised to find that the performance of Apple outshine that of overall market.

To add math symbols in R Markdown check the link MathinRmd.html. Many other examples are on Google. Following is an example: \(\sum_{n=1}^{10} n^2\). Other, less preferred options, is to neatly handwrite your equations on a paper or use own preferred tools like Microsoft Word, take a clear image capture of your work and include here. Hard to read work will be dismissed.

Below is an example on how to include an image. It is assumed that the image resides in the same folder as the worksheet. Otherwise the path to the folder where the image resides needs to be included in the name referencing below.

This is a caption

This is a caption

Task 3: Problem(s) Solving

This task does not require use of R code. You will however need to type your work here, using proper mathematical symbols and representations, or include a clear image capture of your work.

##### 3A) Solve for 1.3.8 Problem/p. 36.

We will build two portfolios. The portfolio A consists of one call option on the stock, whose current price is what we want to calculate. The payoff of the option depends on the two possible prices Su and Sd of stock at maturity, and given by max(S-K,0). The payoff can be either, Cu=Su-K=40-20=20 or Cd=0 since Sd<K. The portfolio B consists of \(\Delta\) shares of stock and a loan from the bank for the amount of B.According to replicating portfolios method, the payoff of portfolio B should be the same as A. Therefore, we can know that, \(\Delta\)Su-B\(e^{rt}\)=Cu or \(\Delta\)Sd-B\(e^{rt}\)=Cd From these two equations above, we can calculate the equations for \(\Delta\) and B, which is: \(\Delta\)=\(\frac{Cu-Cd}{Su-Sd}\)=\(\frac{20-0}{40-15}\)=0.8, B=$\(=\)$=7.13

Since both portfolios must have the same values at all times including time 0, therefore, the price of call option is equal to the price of portfolio B, which is: C=\(\Delta\)S-B=0.825-7.13=12.87. Besides, according to the put-call parity, the price of put option P=C+K\(e^{-rt}\)-S=12.87+20\(e^{-0.05*1}\)-25=6.89.

##### 3B) Solve for 1.3.9 Problem/p. 36

According to the put-call parity, the price of put option P=C+K\(e^{-rt}\)-S. So we can form two portfolios which have the same values at all times. Portfolio A is a put option, portfolio B is a call option plus cash flow and a short position on the stock. From the result above, C=\(\Delta\)S-B. Therefore, P=C+K\(e^{-rt}\)-S=(\(\Delta\)-1)S+(K\(e^{-rt}\)-B). In this equation, \(\Delta\) is reffered as \(\Delta\)c, which is the number of shares needed to replicate a call option. Also, (\(\Delta\)-1) is reffered as \(\Delta\)p, which is the number of shares needed to replicate the put on the same stock and with the same strike price. Thus, for a call and a put European options on the same stock with same strike price, \(\Delta\)p=\(\Delta\)c-1. *http://computationalfinance.lsi.upc.edu