forked from burakbayramli/books
-
Notifications
You must be signed in to change notification settings - Fork 0
/
returnCalculations.r
217 lines (188 loc) · 5.94 KB
/
returnCalculations.r
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# returnCalculations.r
#
# author: E. Zivot
# created: September 29, 2009
# revision history:
# June 24, 2011
# Updated code to work with R 2.12.2
# October 10, 2009
# Added examples from Performance Analytics and quantmod
# October 5, 2009
# Added code for return calculations
#
# Data used (available at http://faculty.washington.edu/ezivot/econ424/R_hints.htm)
# sbuxPrices.csv
# msftPrices.csv
#
# Core R functions used
#
# abline
# class
# colnames
# exp
# legend
# lines
# log
# max
# min
# plot
# read.csv
# rownames
# seq
# str
# tail
# R packages/functions used
#
# PerformanceAnalytics
# chart.TimeSeries
# chart.Cumulative
# ReturnCalculate
#
# quantmod
# getSymbols
#
# zoo
# zoo
# as.yearmon
# diff
# lag
#
# set options
#
options(digits = 4)
options(width = 75)
options(chmhelp=TRUE)
loadPath = "C:\\Users\\ezivot\\Documents\\FinBook\\Data\\"
#
# load data
#
# read the sbux prices into a data.frame object. First look at the online help file
# for read.csv
?read.csv
# now read in the data
sbux.df = read.csv(file=paste(loadPath, "sbuxPrices.csv", sep=""),
header=TRUE, stringsAsFactors=FALSE)
msft.df = read.csv(file=paste(loadPath, "msftPrices.csv", sep=""),
header=TRUE, stringsAsFactors=FALSE)
# sbux.df and msft are a data.frame objects. Data.frames are rectangular data
# objects with observations in rows and variables in columns
class(sbux.df)
str(sbux.df)
head(sbux.df)
tail(sbux.df)
colnames(sbux.df)
class(sbux.df$Date)
class(sbux.df$Adj.Close)
# plot prices
plot(msft.df$Adj.Close, type = "l", lty = "solid", lwd = 2,
col = "blue", ylab = "return")
lines(sbux.df$Adj.Close, lty = "dotted", lwd = 2, col = "black")
legend(x = "topleft", legend=c("MSFT", "SBUX"), lwd = 2,
lty = c("solid", "dotted"), col = c("blue", "black"))
#
# compute monthly simple returns
#
n = nrow(sbux.df)
sbux.ret = sbux.df$Adj.Close[2:n]/sbux.df$Adj.Close[1:n-1] - 1
msft.ret = msft.df$Adj.Close[2:n]/msft.df$Adj.Close[1:n-1] - 1
head(cbind(sbux.ret, msft.ret))
# compute 2-period returns
sbux.ret.2 = sbux.df$Adj.Close[3:n]/sbux.df$Adj.Close[1:n-2] - 1
#
# compute monthly cc returns
#
sbux.ccret = log(1 + sbux.ret)
msft.ccret = log(1 + msft.ret)
# equivalently can compute
sbux.ccret = log(sbux.df$Adj.Close[2:n]/sbux.df$Adj.Close[1:n-1])
msft.ccret = log(msft.df$Adj.Close[2:n]/msft.df$Adj.Close[1:n-1])
head(cbind(sbux.ccret, msft.ccret))
# rearrange data frame so that the rownames are the character dates and the
# data.frame only contains the price data. Note, using drop=FALSE preserves
# the data.frame object structure
rownames(sbux.df) = sbux.df$Date
rownames(msft.df) = msft.df$Date
sbux.df = sbux.df[, "Adj.Close", drop=FALSE]
msft.df = msft.df[, "Adj.Close", drop=FALSE]
#
# Return calculations using zoo objects and PerformanceAnalytics functions
# note: PerformanceAnalytics automatically loads zoo
#
library(PerformanceAnalytics)
# create zoo objects from data.frame objects
dates.sbux = as.yearmon(sbux.df$Date, format="%m/%d/%Y")
dates.msft = as.yearmon(msft.df$Date, format="%m/%d/%Y")
sbux.z = zoo(x=sbux.df$Adj.Close, order.by=dates.sbux)
msft.z = zoo(x=msft.df$Adj.Close, order.by=dates.msft)
class(sbux.z)
head(sbux.z)
# subset using dates
# subsetting can be done with a date index and the window function
sbux.z[as.yearmon(c("Mar 1993", "Mar 1994"))]
window(sbux.z, start=as.yearmon("Mar 1993"), end=as.yearmon("Mar 1994"))
# create merged time series
sbuxMsft.z = merge(sbux.z, msft.z)
head(sbuxMsft.z)
# two series on same graph
plot(msft.z, lwd=2, col="blue", ylab="Prices", xlab="Months")
lines(sbux.z, col="black", lwd=2, lty="dotted")
legend(x="topleft", legend=c("MSFT", "SBUX"), col=c("blue", "black"),
lwd=2, lty=c("solid", "dotted"))
# two series in two separate panels
plot(sbuxMsft.z, lwd=c(2,2), plot.type="multiple",
col=c("black", "blue"), lty=c("solid", "dotted"),
ylab=c("SBUX", "MSFT"), main="")
# create merged time series
sbuxMsft.z = merge(sbux.z, msft.z)
# compute returns using diff() and lag()
sbuxRet.z = diff(sbux.z)/lag(sbux.z, k=-1)
sbuxRetcc.z = diff(log(sbux.z))
head(merge(sbuxRet.z, sbuxRetcc.z))
sbuxMsftRet.z = CalculateReturns(sbuxMsft.z, method="simple")
head(sbuxMsftRet.z)
# continuously compounded returns
sbuxMsftRetcc.z = CalculateReturns(sbuxMsft.z, method="compound")
head(sbuxMsftRetcc.z)
# show prices with dot-com boom shading and labels
# dates are formated the same way they appear on the x-axis
#shading.dates = list(c("01/98", "10/00"))
#label.dates = c("01/98", "10/00")
shading.dates = list(c("Jan 98", "Oct 00"))
label.dates = c("Jan 98", "Oct 00")
label.values = c("Start of Boom", "End of Boom")
chart.TimeSeries(msft.z, lwd=2, col="blue", ylab="Price",
main="The rise and fall of Microsoft stock",
period.areas=shading.dates, period.color="yellow",
event.lines=label.dates, event.labels=label.values,
event.color="black")
# plot growth of $1 invested
chart.CumReturns(sbuxMsftRet.z, lwd=2, main="Growth of $1", legend.loc="topleft")
#
# Return calculations and charting using quantmod and xts
#
library(quantmod)
getSymbols("YHOO")
class(YHOO)
colnames(YHOO)
start(YHOO)
end(YHOO)
head(YHOO)
chartSeries(YHOO,theme=chartTheme('white'))
#
# Return calculations and plotting using Rmetrics package fPortfolio
#
# to be completed
#
# properties of exponentials and logarithms
#
x = seq(-1, 2, length.out = 100)
e.x = exp(x)
ln.x = log(x[x > 0])
lb = min(e.x, ln.x)
ub = max(e.x, ln.x)
plot(x, e.x, ylim = c(lb, ub), type = "l", lty = 2, lwd = 2, col = "blue",
xlab = "x", ylab = "y")
lines(x[x > 0], ln.x, lwd = 2, col = "red")
abline(h=0, v=0)
legend(x = "topleft", legend = c("exp(x)", "ln(x)"), lty=c(2, 1), lwd = 2,
col = c("blue", "red"))