-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAssignment1.Rmd
More file actions
360 lines (291 loc) · 13.1 KB
/
Assignment1.Rmd
File metadata and controls
360 lines (291 loc) · 13.1 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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
---
title: '**Visualisation**: Assignment 1'
author: 'Name: Adarsha Mondal | Roll Number: MDS202205'
date: 'Dead Line : 03 Oct 2022'
output:
pdf_document: default
html_document:
df_print: paged
word_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(ggplot2)
library(gridExtra)
library(reshape2)
library(ggpubr)
library(formatR)
theme_set(theme_bw())
```
## Instruction:
1) Work on the \`Assignment1.Rmd' file. Compile the file as pdf. Submit only the pdf file in moodle.
2) Make sure you write your name and roll number at the top of the \`Assignment1.Rmd' file.
## Total Marks: 10 points
## Problem 1 (3 points)
**Problem Statement:** Write an $\texttt{R}$ function which will test Central Limit Theorem.
- Assume the underlying population distribution follow Poisson distribution with rate parameter $\lambda$
- We want to estimate the unknown $\lambda$ with the sample mean $$\hat{\lambda}=\frac{1}{n}\sum_{i=1}^{n}X_i$$
- The exact sampling distribution of $\hat{\lambda}$ is unknown
- But CLT tells us that as sample size $n$ increases the sampling distribution of $\hat{\lambda}$ can be approximated by Gaussian distribution.
### **Input in the function:**
- $n$: sample size
- $\lambda$ : rate parameter
- $N$: simulation size
## **Output from the function:**
- Histogram of the sampling distribution using `ggplot`
- QQ-plot using `ggplot`
## **Test cases:**
- case 1 a: $\lambda =0.7$, n=10, N=5000
- case 1 b: $\lambda=0.7$, n=30, N=5000
- case 1 c: $\lambda=0.7$, n=100, N=5000
- case 1 c: $\lambda=0.7$, n=300, N=5000
- case 2 a: $\lambda=1.7$, n=10, N=5000
- case 2 b: $\lambda=1.7$, n=30, N=5000
- case 2 c: $\lambda=1.7$, n=100, N=5000
- case 2 c: $\lambda=1.7$, n=300, N=5000
```{r tidy = TRUE, tidy.opts = list(width.cutoff = 50)}
cumulative_df = data.frame(means = numeric(0),
samp_size = character(0), lambda = character(0))
problem_1 = function(lambda, sample_size, sim_size){
samplings_mean_vec = replicate(sim_size,mean(rpois(sample_size,lambda)))
samplings_mean_df = data.frame(samplings_mean_vec,
rep(paste("Sample size :", sample_size,sep = " "),sim_size),
rep(paste("Lambda :",lambda,sep = " "),sim_size))
return(samplings_mean_df)
}
lambdas = c(0.7, 1.7)
test_cases = c(010,030,100,300)
simulation_size = 5000
for (lambda in lambdas){
for (test in test_cases){
cumulative_df = rbind(cumulative_df, problem_1(lambda,test,simulation_size))
}
}
colnames(cumulative_df) = c('means', 'samp_size', 'lambda')
# Histigrams
print(ggplot(cumulative_df)+aes(x=means)+
geom_histogram(color="white", fill="black",bins=22)+
geom_vline(xintercept = 0.7, linetype="dashed", color="orange",size=1)+
geom_vline(xintercept = 1.7, linetype="dashed", color="blue",size=1)+
#facet_wrap(~samp_size, ncol=4)+
facet_grid(lambda ~ samp_size, scales = "free")+
theme(axis.line = element_line(colour = "darkblue", size = 1,
linetype = "solid"),
axis.title.x = element_text(face="bold",size=15),
axis.title.y = element_text(face="bold",size=15))+
geom_text(aes(0.6,2000,label = 0.7, hjust=-1))+
geom_text(aes(1.6,2000,label = 1.7, hjust=-1))+
labs(title = "Histograms corresponding to all test-cases",x = "Sample Means",
y="Count"))
#head(cumulative_df[cumulative_df$lambda=='Lambda : 0.7',])
# Q-Q Plots
for (lambda in lambdas){
df = cumulative_df[cumulative_df$lambda==paste('Lambda :',lambda,sep = ' '),]
print(ggplot(data=df, aes(sample = means))+geom_qq(size=1)+
geom_qq_line(color = "blue")+
facet_wrap(vars(samp_size), scales = "free_y",nrow = 1)+
theme(axis.line = element_line(colour = "darkblue", size = 1,
linetype = "solid"),
axis.title.x = element_text(face="bold",size=15),
axis.title.y = element_text(face="bold",size=15))+
labs(title = paste('Q-Q Plots corresponding to Lambda =',lambda,sep = ' '),
x = "Theoretical Quantiles", y = "Sample Quantiles"))
}
```
### **Problem 2:** (2 points)
Consider the `JohnsonJohnson` dataset. The datset contains the Quarterly earnings (dollars) per Johnson & Johnson share 1960--80.
a) Draw the time series plot of Quarterly earnings in regular scale and log-scale using the `ggplot` (1 point)
```{r}
head(JohnsonJohnson)
```
```{r tidy = TRUE, tidy.opts = list(width.cutoff = 50)}
problem_2 = function(){
jj_earnings_df = data.frame(time = time(JohnsonJohnson),
earnings = JohnsonJohnson)
line = ggplot(data = jj_earnings_df, aes(x = time, y = earnings)) +
geom_line(color = "#00AFBB", size = 1)+
geom_smooth()+
theme(axis.line = element_line(colour = "black", size = 1,
linetype = "solid"),
axis.title.x = element_text(face="bold",size=12),
axis.title.y = element_text(face="bold",size=12))+
labs(title = "Time Series plot",
subtitle = "Quarterly earnings from 1960 - 1980",
x = "Time",
y = "Earnings($)")
log = ggplot(data = jj_earnings_df, aes(x = time, y = earnings)) +
geom_line(color = "red", size = 1) + scale_y_continuous(trans = "log")+
geom_smooth(method = "lm")+
theme(axis.line = element_line(colour = "black", size = 1,
linetype = "solid"),
axis.title.x = element_text(face="bold",size=12),
axis.title.y = element_text(face="bold",size=12))+
labs(title = "Log-scaled Time Series plot",
subtitle = "Quarterly earnings from 1960 - 1980",
x = "Time",
y = "log(Earnings)")
figure = ggarrange(line, log, ncol = 2)
return(figure)
}
print(problem_2())
```
### **Problem 3:** (2 points)
- An experiment was conducted to measure and compare the effectiveness of various feed supplements on the growth rate of chickens.
- Following R-code is a standard side-by-side boxplot showing effect of feed supplements on the growth rate of chickens.
```{r,fig=T}
boxplot(weight~feed,data=chickwts,pch=20
,main = "chickwt data"
,ylab = "Weight at six weeks (gm)"
,xlab = "Feed Type")
```
a) Reproduce the same plot using the `ggplot`; while fill each boxes with different colour.
b) In addition draw probability density plot for weights of chicken's growth by each feed seperately using the `ggplot`. Draw this plot seperately.
```{r tidy = TRUE, tidy.opts = list(width.cutoff = 50)}
problem_3 = function(){
chickwts_df = data.frame(chickwts)
#
print(ggplot(chickwts_df, aes(x = feed, y = weight, fill=feed))+
aes(color = feed)+
geom_boxplot(alpha=0.3)+
theme(axis.line = element_line(colour = "black", size = 1,
linetype = "solid"),
axis.title.x = element_text(face="bold",size=15),
axis.title.y = element_text(face="bold",size=15),
axis.text.x = element_text(face = "bold",size = 12),
axis.text.y = element_text(face = "bold",size = 12)))
# Probability densities
print(ggplot(chickwts_df)+
geom_density(aes(y=weight, fill="f8766d"))+
facet_grid(~feed)+
theme(axis.line = element_line(colour = "black", size = 1,
linetype = "solid"),
axis.title.x = element_text(face="bold",size=15),
axis.title.y = element_text(face="bold",size=15),
axis.text.x = element_text(angle = -90,face = "bold",size = 10),
axis.text.y = element_text(face = "bold",size = 10),
legend.position="none") +
labs(title = "Probability of weight of chicks depending on feed",
x = "Probability Density",
y = "Weight(g)"))
}
problem_3()
```
### **Problem 4:** (3 points)
Consider the `EuStockMarkets` data available in `R`. Contains the daily closing prices of major European stock indices: Germany DAX (Ibis), Switzerland SMI, France CAC, and UK FTSE. The data are sampled in business time, i.e., weekends and holidays are omitted.
```{r}
head(EuStockMarkets)
```
- Suppose $P_t$ is the closing price of a stock indices on day $t$.
- The daily return $r_t$ is defined as $$
r_t = \log(P_t)-\log(P_{t-1}).
$$
a) Draw time-series plot of $P_t$ for all four markets
b) Draw time-series plot of $r_t$ for all four markets
c) Draw histogram of $P_t$ for all four markets
d) Draw histogram of $r_t$ for all four markets
e) Suppose you invested \$ 1000 in each market indices on day 1. Plot how your investment grows on the same plot for all four markets. Make your plot using `ggplot`.
f) Check which market outperform others during the same time?
Make all your plots using `ggplot`.
```{r tidy = TRUE, tidy.opts = list(width.cutoff = 50)}
time = data.frame(time = time(EuStockMarkets))
data = data.frame(EuStockMarkets)
n = nrow(data)
for(i in 1:4){
temp_dr = c(0)
temp_inv = c(1000)
for(j in 2:n){
k = log(data[j,i]/data[j-1,i])
temp_dr = c(temp_dr,k)
temp_inv = c(temp_inv,temp_inv[j-1]*exp(k))
}
if(i==1){
dr_df = data.frame(IDX_dr = temp_dr)
investment_df = data.frame(IDX_inv = temp_inv)
}
else{
dr_df[paste(names(data)[i], 'dr', sep = '_')] = data.frame(temp_dr)
investment_df[paste(names(data)[i], 'inv', sep = '_')] = data.frame(temp_inv)
}
}
inv_melt=melt(cbind(time,investment_df),id=c('time'),value.name = "value")
pt_melt = melt(cbind(time, data), id = c("time"), value.name = "value")
dr_melt = melt(cbind(time, dr_df), id = c("time"), value.name = "value")
```
a)
```{r tidy = TRUE, tidy.opts = list(width.cutoff = 50)}
print(ggplot(pt_melt)+aes(x=time, y=value)+
geom_line(aes(color=variable),size=1)+
facet_grid(vars(variable))+
labs(title = "Performance on closing value of various Indices(P_t)",
y = "Closing value")+
theme(axis.line = element_line(colour = "black", size = 0.6,
linetype = "solid"),
axis.title.x = element_text(face="bold",size=15),
axis.title.y = element_text(face="bold",size=15),
axis.text.x = element_text(face = "bold",size = 12),
axis.text.y = element_text(face = "bold",size = 12),
legend.position = "none"))
```
b)
```{r tidy = TRUE, tidy.opts = list(width.cutoff = 50)}
print(ggplot(dr_melt)+aes(x=time, y=value)+
geom_line()+
geom_point(alpha=0.3,aes(colour=value>0))+
facet_grid(vars(variable))+
labs(title = "Performance on daily return of various Indices(r_t)",
y = "log(ratio of consecutive day values)")+
theme(axis.line = element_line(colour = "black", size = 0.6,
linetype = "solid"),
axis.title.x = element_text(face="bold",size=15),
axis.title.y = element_text(face="bold",size=15),
axis.text.x = element_text(face = "bold",size = 12),
axis.text.y = element_text(face = "bold",size = 12)))
```
c)
```{r tidy = TRUE, tidy.opts = list(width.cutoff = 50)}
print(ggplot(pt_melt)+aes(x=value)+
geom_histogram(aes(color=variable),bins=50)+
facet_grid(vars(variable))+
labs(title =
"Deviation of closing value of various indices from its centrality",
y = "Count",x="Closing Value")+
theme(axis.line = element_line(colour = "black", size = 0.6,
linetype = "solid"),
axis.title.x = element_text(face="bold",size=15),
axis.title.y = element_text(face="bold",size=15),
axis.text.x = element_text(face = "bold",size = 12),
axis.text.y = element_text(face = "bold",size = 12),
legend.position = "none"))
```
d)
```{r tidy = TRUE, tidy.opts = list(width.cutoff = 50)}
print(ggplot(dr_melt)+aes(x=value)+
geom_histogram(aes(color=variable),bins=40)+
facet_grid(vars(variable))+
geom_vline(xintercept = 0, linetype="dashed", color="orange",size=1)+
labs(title =
"Count of daily return of various indices",
y = "Count",x="Daily return")+
theme(axis.line = element_line(colour = "black", size = 0.6,
linetype = "solid"),
axis.title.x = element_text(face="bold",size=15),
axis.title.y = element_text(face="bold",size=15),
axis.text.x = element_text(face = "bold",size = 12),
axis.text.y = element_text(face = "bold",size = 12),
legend.position = "none"))
```
e)
```{r tidy = TRUE, tidy.opts = list(width.cutoff = 50)}
print(ggplot(inv_melt, aes(x = time, y = value)) +
geom_line(aes(color = variable, linetype = "solid"),size=1)+
labs(title =
"Performance comparision of various Indices b/w 1991-'99",
y = "Absolute Monetery value($)",x="Time")+
theme(axis.line = element_line(colour = "black", size = 0.6,
linetype = "solid"),
axis.title.x = element_text(face="bold",size=13),
axis.title.y = element_text(face="bold",size=13),
axis.text.x = element_text(face = "bold",size = 12),
axis.text.y = element_text(face = "bold",size = 12)))
```
f) By analyzing the last graph(e), we get to know that, the SMI(Swiss Market Index) outperforms all the the other indices (DAX, CAC and FTSE) for almost the entire time-span given(1991-1999).