Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merge new teacher stuff #23

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
433 changes: 433 additions & 0 deletions CourseSessions/Sessions23/Session2inclass_BR.Rmd

Large diffs are not rendered by default.

Binary file added Exercises/Exerciseset1/DataSet1.Rdata
Binary file not shown.
55 changes: 28 additions & 27 deletions Exercises/Exerciseset1/ExerciseSet1.Rmd
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ We download daily prices (open, high, low, close, and adjusted close) and volume
```{r eval = TRUE, echo=TRUE, error = FALSE, warning=FALSE,message=FALSE,results='asis'}
source("helpersSet1.R")
source("dataSet1.R")
source("dataSet2.R")
```

For more information on downloading finance data from the internet as well as on finance related R tools see these starting points (there is a lot more of course available):
Expand All @@ -55,12 +56,12 @@ For more information on downloading finance data from the internet as well as on

#### Optional Question

1. Can you find some interesting finance related R package or github repository?
**Your Answers here:**
<br>
<br>

1. Can you find some interesting finance related R package or github repository?
<hr>
1. *Several R finance package are interesting including:*<br>
*- Rblpapi: a R Interface to Bloomberg*<br>
*- FinCal: a package to calculate the time Value of Money, the time Series Analysis and computational Finance*<br>
*- jrvFinance: a basic finance tool to calculate NPV/IRR/Annuities/Bond-Pricing or Black Scholes*<br>
<hr>

### Part I: Statistics of S&P Daily Returns
Expand All @@ -86,11 +87,16 @@ pnl_plot(SPY)

**Your Answers here:**
<br>
<br>
<br>
<br>

<hr>

*line 96: *ExerciseSet1.Rmd:write.csv(StockReturns[1:20,c("SPY","**AAPL**")], file = "twentydays.csv", row.names = TRUE, col.names = TRUE)<br>
*line 8: *dataSet1.R:mytickers = c("SPY", "**AAPL**") # Other tickers for example are "GOOG", "GS", "TSLA", "FB", "MSFT", <br>

<hr>
*Cumulative returns:* `r round(100*sum(StockReturns[,2]),1)`%<br>
*Average daily returns:* `r round(100*mean(StockReturns[,2]),3)`%<br>
*Standard deviation of the daily returns of Apple:* `r round(100*sd(StockReturns[,2]),3)`%<br>
<hr>

### Part II: Simple Matrix Manipulations
Expand Down Expand Up @@ -125,13 +131,15 @@ We can also transpose the matrix of returns to create a new "horizontal" matrix.
1. What R commands can you use to get the number of rows and number of columns of the new matrix called transposedData?
2. Based on the help for the R function *apply* (`help(apply)`), can you create again the portfolio of S&P and Apple and plot the returns in a new figure below?

**Your Answers here:**
<br>
<br>
<br>
<br>

<hr>
1. We can use `nrow(transposedData)` and `ncol(transposedData)`.
2. I assume that we are asked to re-draw the plot using the transposed matrix:
```{r eval=FALSE, echo=FALSE, comment=NA, warning=FALSE, message=FALSE,results='asis',fig.align='center', fig=TRUE}
portfolio2 = apply(transposedData,2,mean)
names(portfolio2) <- colnames(transposedData)
pnl_plot(portfolio2)
```

<hr>

### Part III: Reproducibility and Customization
Expand All @@ -142,14 +150,8 @@ This is an important step and will get you to think about the overall process on

1. We want to re-do all this analysis with data since 2001-01-01: what change do we need to make in the code (hint: all you need to change is one line - exactly 1 number! - in data.R file), and how can you get the new exercise set with the data since 2001-01-01?
2. *(Extra Exercise)* Can you get the returns of a few companies and plot the returns of an equal weighted portfolio with those companies during some period you select?

**Your Answers here:**
<br>
<br>
<br>
<br>

<hr>
All we need to change is the value allocated to the variable `startDate = "2001-01-01"` in Line 11.
<hr>

### Part IV: Read/Write .CSV files
Expand Down Expand Up @@ -177,13 +179,12 @@ Try it!
myData + StockReturns[1:40,])
```

**Your Answers here:**
<br>
<br>
<br>
<br>

<hr>

1. We get as output a number (20). Each row in myData is different from the corresponding row in StockReturns (hence the test is true and yields a result of 1). This makes senses because myData contains one row with a string whereas StockReturns containts three rows.
However, if we use as separator in the read.csv function a comma instead of a semicolon, we end up with matrices of the same dimensions, but there is an offset of one row for some reason. THen we get a result of 60 (20x3). If we were able to resolve the offset issue, we'd get a result of zero, i.e. all the cells would match.
2. We will get an error because we are summing matrices with different types of arguments.

<hr>

### Extra Question
Expand Down
254 changes: 254 additions & 0 deletions Exercises/Exerciseset1/ExerciseSet1.html

Large diffs are not rendered by default.

51 changes: 51 additions & 0 deletions Exercises/Exerciseset1/dataSet2.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@

# rm(list=ls()) # Clean up the memory, if we want to rerun from scratch
# source("helpersSet1.R")

getdata.fromscratch = 1

website_used = "yahoo" # can be "yahoo" or other ( see help(getSymbols) ). Depending on the website we may need to change the stock tickers' representation
mytickers = c("SPY", "AAPL") # Other tickers for example are "GOOG", "GS", "TSLA", "FB", "MSFT",
startDate = "2005-01-01"

if (getdata.fromscratch){
# Get SPY first, to get all trading days
tmp<-as.matrix(try(getSymbols(Symbols="AAPL",from = startDate,src = website_used, auto.assign=FALSE)))
ApplStockPrices=matrix(rep(0,nrow(tmp)*length(mytickers)), ncol=length(mytickers))
colnames(ApplStockPrices)<-mytickers;
rownames(ApplStockPrices)<-rownames(tmp)
ApplStockVolume=ApplStockPrices
ApplStockPrices[,1] <- tmp[,6]

for (ticker_index in 1:length(mytickers)){
ticker_to_get = mytickers[ticker_index]
print(paste("\nDownloading ticker ", ticker_to_get, " ..."))
tmpdata<-as.matrix(try(getSymbols(Symbols=ticker_to_get,from = startDate,auto.assign=FALSE)))
if (!inherits(tmpdata, "try-error"))
{
therownames=intersect(rownames(tmpdata),rownames(ApplStockPrices))
tmpdata[is.na(tmpdata)] <- 0
ApplStockPrices[therownames,ticker_index]<-tmpdata[therownames,6] # adjusted close price
ApplStockVolume[therownames,ticker_index]<-tmpdata[therownames,5] # shares volume for now - need to convert to dollars later
} else {
cat(ticker_to_get," NOT found")
}
}
# Get the daily returns now. Use the simple percentage difference approach
AaplStockReturns= ifelse(head(ApplStockPrices,-1)!=0, (tail(StockPrices,-1)-head(StockPrices,-1))/head(StockPrices,-1),0) # note that this removes the first day as we have no way to get the returns then!
rownames(AaplStockReturns)<-tail(rownames(ApplStockPrices),-1) # adjust the dates by 1 day now

# Now remove the first day from the other data, too
ApplStockPrices = StockPrices[rownames(AaplStockReturns),]
ApplStockVolume = ApplStockPrices[rownames(AaplStockReturns),]
colnames(ApplStockPrices)<-mytickers
colnames(ApplStockVolume)<-mytickers
colnames(AaplStockReturns)<-mytickers

save(AaplStockReturns,ApplStockPrices,ApplStockVolume, file = "DataSet1.Rdata")
} else {
load("DataSet1.Rdata")
}



21 changes: 21 additions & 0 deletions Exercises/Exerciseset1/twentydays.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"","SPY","AAPL"
"2005-01-04",-0.0122194637127275,0.0102701088517504
"2005-01-05",-0.00690061615719681,0.00875830945932705
"2005-01-06",0.00508430540389297,0.000775098385044691
"2005-01-07",-0.00143324918157237,0.0728119031851786
"2005-01-10",0.00472810453179597,-0.00418786145491284
"2005-01-11",-0.00689074776905752,-0.063805107443653
"2005-01-12",0.00330004252922032,0.0139406693608039
"2005-01-13",-0.00801211937901914,0.066299907249727
"2005-01-14",0.0052711748835299,0.00573060038933524
"2005-01-18",0.0104026005444693,0.00641032505910421
"2005-01-19",-0.0104628791052045,-0.0108989459656001
"2005-01-20",-0.0060903540542225,0.00829999885962422
"2005-01-21",-0.00612767375693113,0.0004257211545643
"2005-01-24",-0.00196947533623822,0.00383049984844807
"2005-01-25",0.00283135035218729,0.0182305207326887
"2005-01-26",0.00299458297525282,0.0027759262791443
"2005-01-27",0.00170602341346994,0.00539788429906169
"2005-01-28",0,0.0184471453404301
"2005-01-31",0.00621649614031668,0.0394701515667315
"2005-02-01",0.00634732427396169,0.00819242781131764
Loading