-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClass1.Rmd
More file actions
317 lines (241 loc) · 7.38 KB
/
Copy pathClass1.Rmd
File metadata and controls
317 lines (241 loc) · 7.38 KB
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
---
title: "Class 1"
author: "DABAJA"
date: "9/13/2017"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
Instal packages
```{r Packages}
#install.packages(c("timeDate","mvtnorm","quadprog","quantreg","rgl","robustbase","scatterplot3d","SparseM","tseries"))
#install.packages("/Users/dawidjarosz/Dropbox/Semester\ 11/Statistical\ Analysis\ of\ Financial\ Data/Class\ 1/Rsafd", repos = NULL, type="source")
library(timeDate)
library(mvtnorm)
library(quadprog)
library(rgl)
library(robustbase)
library(scatterplot3d)
library(SparseM)
library(tseries)
library(Rsafd)
```
Load the data set: Rdata rdb - file with databases he works with in the book.
```{r}
lazyLoad(filebase = "/Users/dawidjarosz/Dropbox/Semester\ 11/Statistical\ Analysis\ of\ Financial\ Data/Class\ 1/Rsafd/data/Rdata",
envir = parent.frame())
```
```{r}
wn <- rnorm(1024)
```
Samuelson
```{r}
DELTAT <- 1/252
SIG <- .2*sqrt(DELTAT)
MU <- .15*DELTAT
TIME <- (1:1024)/252
STOCK <- rep(0,1024) #repeats a zero for every entry
```
Model
```{r}
for (i in 1:1024) {
STOCK[i] <- exp(SIG*RW[i] + MU*TIME[i]) # this is exponential
}
```
without a loop
```{r}
STOCK <- exp(SIG*RW + MU*TIME)
```
Plot
```{r}
plot(TIME, STOCK, type="l")
```
```{r}
head(HOWAREYOU)
```
Building function, Black and Scholes -
```{r}
S <- 100 #stock price
K <- S
R <- .4 #per year
SIG <- .2 #annualized vol
TAU <-90/252 #time to maturity, trading days.
d1 <- log(S/K) + TAU * (R+SIG^2/2)
d2 <- d1/(SIG*sqrt(TAU))
d2 <- d1 - SIG*sqrt(TAU)
```
Making a BS funciton, pricing a call.
bs_call <- function() #locally
fix(bs_call) #for any other script, use it a lot, this is how you'll have access to it later
# the function doesn't work
```{r}
bs_call <- function(S=100,
K=100,
R=.1,
SIG=2,
TAU=90/252){
d1 <- log(S/K) + TAU * (R+SIG^2/2)
d1 <- d1/(SIG*sqrt(TAU))
d2 <- d1 - SIG*sqrt(TAU)
c <- s*pnorm(d1) - K*exp(-R*TAU)*pnorm(d2)
return(c) }
```
```{r}
#bs_call(S=109, K=109, R=0.2)
```
Precept
```{r Objects and matrices}
# Check/change working directory:
getwd()
#setwd("path...")
# can also be done using ctrl+shift+H
#### Creating R objects ####
# Creates a vector of length 16 containing the first 16 integers in increasing order:
x <- 1:16
# Same:
y <- seq(from=1, to=16, by=1)
# To know what the function seq does:
help(seq)
# If you type the name of the function or method without parentheses,
# the system will return the R code of the function in question:
objects() # lists objects in the workspace
objects # gives code for this function
dim(x) <- c(8,2) # Organizes the 1-dim vector in a 8x2 matrix
# the function c is used for concatenation
class(x) # all objects created by R have a class atribute, which can be retrieved
# by using the function class
z <- x*x # creates a new R object which is also a 8x2 matrix obtained by multiplying
# entry by entry
# Z <- x%*%x # usual matrix product ('Error: non-conformable arguments' means we
# can't multiply these two matrices due to dimension problems)
Z1 <- x%*%t(x) # 8x8 matrix
Z2 <- t(x)%*%x # 2x2 matrix
# t stands for transpose of the matrix
```
```{r}
rm(x) # removes objects; used to save memory
rm(y,z)
dump(c("Z1", "Z2"), "mymatrices") # dump produces text representations of objects
# dump needs 2 parameters: vectors of names of objects to be found in the workspace,
# and file name to dump the representations to. Outside of R!
```
## Random Generation and White Noise ##
```{r}
WN <- rnorm(1024) # create vector of length 1024
help(rnorm)
WN2 <- rnorm(1024,5.0,4.0) #mean and sd modified
plot(WN, type = "l") # produce sequential plot of the entries of this vector
graphics.off()
par("mar")
par(mar=c(1,1,1,1))
par(mfrow = c(2,1))
# mfrow=c(nrows, ncols) to create a matrix of nrows x ncols plots that are filled
# in by row. mfcol=c(nrows, ncols) fills in the matrix by columns.
plot(WN,type="l")
plot(WN[1:64],type="l") # notice the slicing
```
#### More functions and for loops ####
```{r}
RW <- cumsum(WN) # cumsum is the discrete analogue to integration, just as diff is
# the discrete analogue to differentiation
plot(RW,type="l") # Sample of size 1024 from a Random Walk
```
# Building Models #
```{r Samualson's model}
# Create an object from Samualson's model for stocks:
DELTAT <- 1/252
SIG <- .2*sqrt(DELTAT)
MU <- .15*DELTAT
TIME <- (1:1024)/252 # expressed in years, there are 252 trading days
STOCK <- rep(0,1024) # initial zero vector for the stock
for (I in 1:1024)
STOCK[I] <- exp(SIG*RW[I]+MU*TIME[I])
# To avoid the 'for' loop (and save time):
STOCK <- exp(SIG*RW+MU*TIME)
plot(RW, type="l")
title("Sample of size 1024 from a Random Walk")
plot(TIME, STOCK,type="l")
title("Corresponding Geometric Random Walk with Drift")
```
#### Importing Data ####
```{r}
# Installing packages (please download the Rsafd file first):
install.packages(c("timeDate","mvtnorm","quadprog","quantreg","rgl","robustbase","scatterplot3d","SparseM","tseries"))
# Fix libraries that are used very frequently:
#.First()
#fix(.First)
# library(Rsafd)
# cat("\n Welcome to my world\n\n")
```
```{r}
#attach(hills) # see item in INDEX file
#plot(climb,time)
#plot(dist,time)
```
#### Importing data from .rdb file ####
```{r}
setwd("/Users/dawidjarosz/Dropbox/Semester\ 11/Statistical\ Analysis\ of\ Financial\ Data/Rsafd/data")
readRDS("Rdata.rds") # see metadata
lazyLoad(filebase = "/Users/dawidjarosz/Dropbox/Semester\ 11/Statistical\ Analysis\ of\ Financial\ Data/Rsafd/data/Rdata",
envir = parent.frame())
#find(HOWAREYOU)
head(HOWAREYOU)
```
#### Getting data from the Web via Excel ####
Don't have the "toronto" file.
```{r}
#toronto <- read.csv("path...\\file.csv")
#class(toronto)
#dim(toronto)
#head(toronto) # notice the reversed order
#tail(toronto)
#toronto.close <- toronto[,4] # closing price is in the 4th column
#plot(toronto.close,type="l")
#tsx <-rev(toronto.close) # reverses the order of the data
#plot(tsx,type="l")
```
#### First Function ####
# e.g. Black-Scholes formula
```{r}
S <- 100 # price of the underlying asset
K <- S # at-the-money option
R <- .1 # interest rate
SIG <- .2 #annualized volatility
TAU <- 90/252 # time to maturity (90 days) in years
d1 <- log(S/K) + TAU*(R+SIG^2/2)
d1 <- d1/(SIG*sqrt(TAU))
d2 <- d1 - SIG*sqrt(TAU)
C <- S*pnorm(d1) - K*exp(-R*TAU)*pnorm(d2)
```
# Building a function:
# 1) Create a .txt file that contains the function and then call
# it using 'source'.
\textit{ How to save it into a file that I can later use and upload?}
```{r}
# source('bs_call_test.txt')
```
# 2) Local function:
```{r}
bs_call <- function (TAU=90/252,K=100,S=100,R=.1,SIG=.2)
{
# Parameters: TAU - time to maturity in years
# K - strike
# S - current value of the underlying
# R - yearly interest rate
# SIG - annualized volatility
# Return: Black-Scholes call price
d1 <- log(S/K) + TAU*(R+SIG^2/2)
d1 <- d1/(SIG*sqrt(TAU))
d2 <- d1 - SIG*sqrt(TAU)
C <- S*pnorm(d1) - K*exp(-R*TAU)*pnorm(d2)
return(C)
}
```
# 3) Global function:
```{r}
fix(bs_call) # define a function by copying the local function above on the pop-up window
# Using the function:
bs_call() # use the function with default values
bs_call(TAU=60/252) # change one or more of the default values
```