-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGold_R.R
More file actions
654 lines (489 loc) · 24.6 KB
/
Copy pathGold_R.R
File metadata and controls
654 lines (489 loc) · 24.6 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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
gold_data <- read.csv("C:\\Users\\VALLARI SHARMA\\Downloads\\Gold final PS.csv")
library(ggplot2)
# Inspection of the data
str(gold_data)
summary(gold_data)
# Histogram of Gold Close Prices
ggplot(gold_data, aes(x = close)) +
geom_histogram(binwidth = 10, fill = "blue", color = "black", alpha = 0.7) +
labs(title = "Histogram of Gold Close Prices", x = "Gold Close Price", y = "Frequency") +
theme_minimal()
# Density Plot
ggplot(gold_data, aes(x = close)) +
geom_density(fill = "blue", alpha = 0.5) +
labs(title = "Density Plot of Gold Close Prices", x = "Gold Close Price", y = "Density") +
theme_minimal()
rowst=nrow(gold_data)
rowst
# Load the libraries
library(MASS)
library(fitdistrplus)
library(dplyr)
gold_price_subset <- gold_data %>%
filter(close >= 1000 & close <= 1500)
subsetrows=nrow(gold_price_subset)
subsetrows
# Extract the 'close' column (Gold Close Price)
close_data <- gold_price_subset$close
# Step 1: Fit a normal distribution
normal_fit <- fitdistr(close_data, "normal")
# Step 2: Fit a log-normal distribution
lognormal_fit <- fitdistr(close_data, "lognormal")
# Step 3: Fit a t-distribution (with 5 degrees of freedom)
t_fit <- fitdistr(close_data, "t", df = 5)
# Step 4: Fit an exponential distribution
exponential_fit <- fitdistr(close_data, "exponential")
# Step 5: Fit a gamma distribution
gamma_fit <- fitdistr(close_data, "gamma")
#Step 6: Fit a Weibull distribution
weibull_fit <- fitdistr(close_data, "weibull")
#Step 7:Poisson distribution
# Convert the 'close' data to count data if necessary
close_counts <- round(data$close)
# Plot histogram of the counts to visualize the data
hist(close_counts, breaks=50, prob=TRUE, main="Histogram of Gold Close Counts", xlab="Gold Close (Counts)", col="skyblue")
# Fit a Poisson distribution
lambda <- mean(close_counts) # λ is the mean of the counts
# Print the estimated lambda (λ)
cat("Estimated lambda for Poisson Distribution:", lambda, "\n")
# Step 8: Print summary of the fits
print("Normal Distribution Fit:")
print(normal_fit)
print("Log-Normal Distribution Fit:")
print(lognormal_fit)
print("T-Distribution Fit:")
print(t_fit)
# Step 9: Print summary of the fits
print("Normal Distribution Fit:")
print(normal_fit)
print("Log-Normal Distribution Fit:")
print(lognormal_fit)
print("T-Distribution Fit:")
print(t_fit)
print("Exponential Distribution Fit:")
print(exponential_fit)
print("Gamma Distribution Fit:")
print(gamma_fit)
print("Weibull Distribution Fit:")
print(weibull_fit)
# These results provide information about the parameters of each fitted distribution
# and their estimated standard errors.
# This allows you to assess the uncertainty in the parameter estimates
# and compare the goodness of fit of different distributions
# Step 10: Plot the fitted distributions
hist(close_data, breaks=50, prob=TRUE, main="Gold Close Price", xlab="Price", col="skyblue")
# Overlay the normal distribution fit
curve(dnorm(x, mean=normal_fit$estimate[1], sd=normal_fit$estimate[2]),
col="red", lwd=2, add=TRUE, yaxt="n")
# Overlay the log-normal distribution fit
curve(dlnorm(x, meanlog=lognormal_fit$estimate[1], sdlog=lognormal_fit$estimate[2]),
col="green", lwd=2, add=TRUE, yaxt="n")
# Overlay the t-distribution fit
curve(dt((x - t_fit$estimate[1]) / t_fit$estimate[2], df=5) * (1/t_fit$estimate[2]),
col="blue", lwd=2, add=TRUE, yaxt="n")
# Overlay the exponential distribution fit
curve(dexp(x, rate=1/exponential_fit$estimate),
col="purple", lwd=2, add=TRUE, yaxt="n")
# Overlay the gamma distribution fit
curve(dgamma(x, shape=gamma_fit$estimate[1], rate=gamma_fit$estimate[2]),
col="orange", lwd=2, add=TRUE, yaxt="n")
# Overlay the Weibull distribution fit
curve(dweibull(x, shape=weibull_fit$estimate[1], scale=weibull_fit$estimate[2]),
col="brown", lwd=2, add=TRUE, yaxt="n")
# Overlay Poisson distribution on the histogram
x_vals <- 0:max(close_counts)
pois_prob <- dpois(x_vals, lambda)
# Plot the Poisson distribution curve
lines(x_vals, pois_prob, col="aquamarine4", lwd=2)
# Add legend to the plot
legend("topright", legend=c("Normal", "Log-normal", "T-distribution", "Exponential", "Gamma", "Weibull","Poisson"),
col=c("red", "green", "blue", "purple", "orange", "brown","aquamarine4"), lwd=2)
# The graph shows a histogram of gold close prices with superimposed density plots
# for seven different probability distributions
#poison continuation
# Create a table of observed counts of each unique value in the close_counts data
observed_counts <- table(close_counts)
# Expected counts based on the Poisson distribution
expected_counts <- dpois(as.numeric(names(observed_counts)), lambda) * length(close_counts)
# Perform chi-squared goodness-of-fit test
#Compares the observed and expected counts and calculates a chi-squared statistic.
gof_test <- chisq.test(observed_counts, p=expected_counts / sum(expected_counts))
gof_test
# Print the result
if (gof_test$p.value < 0.05) {
cat("The data does not fit a Poisson distribution as there is significant differnce in counts.\n")
} else {
cat("The data fits a Poisson distribution as there is significant differnce in counts.\n")
}
#Step 9: Compute AIC values for the fitted distributions
# AIC (Akaike Information Criterion) is a statistical measure used to compare the
# relative quality of different statistical models for a given dataset.
# It balances the model's fit to the data with its complexity.
print("AIC for Normal Distribution:")
print(AIC(normal_fit))
print("AIC for Log-Normal Distribution:")
print(AIC(lognormal_fit))
print("AIC for T-Distribution:")
print(AIC(t_fit))
cat("AIC for Exponential Distribution:\n")
print(AIC(exponential_fit))
cat("AIC for Gamma Distribution:\n")
print(AIC(gamma_fit))
cat("AIC for Weibull Distribution:\n")
print(AIC(weibull_fit))
# Calculate AIC for Poisson
# Calculate log-likelihood for the Poisson model
log_likelihood_poisson <- sum(dpois(close_counts, lambda, log=TRUE))
aic_poisson <- -2 * log_likelihood_poisson + 2 * 1 # 1 parameter for Poisson (lambda)
cat("AIC for Poisson Distribution:", aic_poisson, "\n")
# Log-likelihood is a measure of how well a statistical model fits a given dataset.
# It is the natural logarithm of the likelihood function, which represents
# the probability of observing the data given the model's parameters.
#Note:
# Poisson distribution is designed for: count data
# Gold price data is typically continuous, representing a numerical value.
# When we try to fit a Poisson distribution to continuous data,
# the fitdistr function might encounter difficulties in finding suitable parameter
# estimates that maximize the likelihood.
# This can lead to errors or unexpected results.Hence cant do AIC(poisson_fit)
#HYPOTHESIS TESTING USING Z-TEST
# Loading necessary libraries
library(ggplot2)
library(BSDA)
data=gold_price_subset
# Converting 'time' column to Date type
data$time <- as.Date(data$time, format="%d-%m-%Y")
# Why are we dividing?
# 1.Comparison: Dividing the data into groups allows you to compare the
# average gold prices in each group. This can help you determine if there is a
# relationship between DXY and gold prices.
# 2.Hypothesis Testing: The Z-test is used to compare the means of two groups.
# By dividing the data, you have two groups that can be compared using the Z-test.
# 3.Clarity: Dividing the data into groups can make it easier to interpret the
# results and understand the relationship between the variables.
# Hypothesis 1: There is a negative correlation between gold prices and DXY
cor_gold_dxy <- cor(data$close, data$dxy_close, method="pearson")
# Plot the relationship between Gold price and DXY
ggplot(data, aes(x = dxy_close, y = close)) +
geom_point() +
geom_smooth(method = "lm", col = "blue") +
labs(title = paste("Correlation between Gold Price and DXY:", round(cor_gold_dxy, 2)),
x = "DXY Close", y = "Gold Close")
# Divide the data into two groups: high and low DXY
threshold_dxy <- median(data$dxy_close)
high_dxy <- subset(data, dxy_close > threshold_dxy)
low_dxy <- subset(data, dxy_close <= threshold_dxy)
# Perform the Z-test for DXY
z_test_dxy <- z.test(high_dxy$close,
y = low_dxy$close,
sigma.x = sd(high_dxy$close),
sigma.y = sd(low_dxy$close))
# Print the result
if(z_test_dxy$p.value < 0.05) {
cat("Null hypothesis rejected for Gold vs DXY. Conclusion: There is a significant difference in Gold prices based on DXY.\n")
} else {
cat("Null hypothesis accepted for Gold vs DXY. Conclusion: No significant difference in Gold prices based on DXY.\n")
}
# Hypothesis 2: Positive correlation between gold and crude oil prices
cor_gold_oil <- cor(data$close, data$light_crude_oil_close, method="pearson")
# Divide the data into two groups: high and low Crude Oil prices
threshold_oil <- median(data$light_crude_oil_close)
high_oil <- subset(data, light_crude_oil_close > threshold_oil)
low_oil <- subset(data, light_crude_oil_close <= threshold_oil)
# Perform the z-test
z_test_oil <- z.test(high_oil$close,
y = low_oil$close,
sigma.x = sd(high_oil$close),
sigma.y = sd(low_oil$close))
# Print the result
if(t_test_oil$p.value < 0.05) {
print("Null hypothesis rejected for Gold vs Crude Oil.")
print("Conclusion: There is a significant difference in Gold prices based on Crude Oil prices.\n")
} else {
print("Null hypothesis accepted for Gold vs Crude Oil.")
print(" Conclusion: No significant difference in Gold prices based on Crude Oil prices.\n")
}
# Plotting the relationship between Gold price and Crude Oil price
ggplot(data, aes(x = light_crude_oil_close, y = close)) +
geom_point() +
geom_smooth(method = "lm", col = "green") +
labs(title = paste("Correlation between Gold Price and Crude Oil:", round(cor_gold_oil, 2)),
x = "Crude Oil Close", y = "Gold Close")
# Hypothesis 3: Gold moves inversely with the S&P 500 during uncertainty
cor_gold_sp500 <- cor(data$close, data$sp500_close, method="pearson")
# Divide the data into two groups: high and low S&P 500
threshold_sp500 <- median(data$sp500_close)
high_sp500 <- subset(data, sp500_close > threshold_sp500)
low_sp500 <- subset(data, sp500_close <= threshold_sp500)
# Perform the t-test
z_test_sp500 <- z.test(high_sp500$close,
y = low_sp500$close,
sigma.x = sd(high_sp500$close),
sigma.y = sd(low_sp500$close))
# Print the result
if(t_test_sp500$p.value < 0.05) {
print("Null hypothesis rejected for Gold vs S&P 500.")
print("Conclusion: There is a significant difference in Gold prices based on the S&P 500 index.\n")
} else {
print("Null hypothesis accepted for Gold vs S&P 500.")
print("Conclusion: No significant difference in Gold prices based on the S&P 500 index.\n")
}
# Plot the relationship between Gold price and S&P 500 index
ggplot(data, aes(x = sp500_close, y = close)) +
geom_point() +
geom_smooth(method = "lm", col = "red") +
labs(title = paste("Correlation between Gold Price and S&P 500:", round(cor_gold_sp500, 2)),
x = "S&P 500 Close", y = "Gold Close")
#Hypothesis 4: Gold is affected significantly by RSI
cor_gold_rsi <- cor(data$close, data$gold_RSI, method="pearson")
# Divide the data into two groups: high and low RSI
threshold_rsi <- median(data$gold_RSI)
high_rsi <- subset(data, gold_RSI > threshold_rsi)
low_rsi <- subset(data, gold_RSI <= threshold_rsi)
# Perform the t-test
z_test_rsi <- z.test(high_rsi$close,
y = low_rsi$close,
sigma.x = sd(high_rsi$close),
sigma.y = sd(low_rsi$close))
# Print the result
if(z_test_rsi$p.value < 0.05) {
cat("Null hypothesis accepted for Gold vs RSI. Conclusion: There is a significant difference in Gold prices based on RSI.\n")
} else {
cat("Null hypothesis rejected for Gold vs RSI. Conclusion: No significant difference in Gold prices based on RSI.\n")
}
# Plotting Gold price vs RSI
ggplot(data, aes(x = gold_RSI, y = close)) +
geom_point() +
geom_smooth(method = "lm", col = "purple") +
labs(title = paste("Correlation between Gold Price and RSI:", round(cor_gold_rsi, 2)),
x = "Gold RSI", y = "Gold Close")
#Hypothesis 5: Gold is affected significantly by SMAs
# Create a condition for when the gold price is above all SMAs
above_all_smas <- subset(data, close > gold_SMA_10 & close > gold_SMA_50 & close > gold_SMA_200)
# Create a condition for when the gold price is below all SMAs
below_all_smas <- subset(data, close <= gold_SMA_10 & close <= gold_SMA_50 & close <= gold_SMA_200)
# Perform a t-test to compare gold prices above and below the SMAs
z_test_sma_combined <- z.test(above_all_smas$close,
y = below_all_smas$close,
sigma.x = sd(above_all_smas$close),
sigma.y = sd(below_all_smas$close))
# Print the t-test result with hypothesis testing conclusion
if(t_test_sma_combined$p.value < 0.05) {
print(" Null hypothesis accepted for Gold vs combined SMAs (10, 50, 200).")
print("Conclusion:There is a significant difference in Gold prices when above vs below the combined SMAs.")
} else {
print("Null hypothesis rejected for Gold vs combined SMAs (10, 50, 200). ")
print("Conclusion: No significant difference in Gold prices when above vs below the combined SMAs.\n")
}
# Plotting Gold price with 10-day, 50-day, and 200-day SMAs
ggplot(data, aes(x = time)) +
geom_line(aes(y = close, col = "Gold Price")) +
geom_line(aes(y = gold_SMA_10, col = "SMA 10-Day")) +
geom_line(aes(y = gold_SMA_50, col = "SMA 50-Day")) +
geom_line(aes(y = gold_SMA_200, col = "SMA 200-Day")) +
labs(title = "Gold Price vs Moving Averages",
x = "Time", y = "Gold Price") +
scale_color_manual(values = c("Gold Price" = "red", "SMA 10-Day" = "blue",
"SMA 50-Day" = "green", "SMA 200-Day" = "black"))
data <- read.csv("C:\\Users\\VALLARI SHARMA\\Downloads\\Gold final PS.csv")
# Perform Pearson correlation test between gold prices and U.S. Dollar Index
cor_test_result <- cor.test(data$close, data$dxy_close, method = "pearson")
# Print the result
print(cor_test_result)
data <- read.csv("C:\\Users\\VALLARI SHARMA\\Downloads\\Gold final PS.csv")
# Calculate daily returns as percentage change in the gold closing price
data$returns <- c(NA, diff(data$close) / data$close[-nrow(data)] * 100)
# Create a condition for overbought (RSI > 70) and oversold (RSI < 30)
overbought <- data$gold_RSI > 70
oversold <- data$gold_RSI < 30
# Subset data for overbought and oversold conditions
overbought_returns <- data$returns[overbought]
oversold_returns <- data$returns[oversold]
# Average returns on all other days (when RSI is neither overbought nor oversold)
other_returns <- data$returns[!(overbought | oversold)]
# Perform t-tests to compare overbought/oversold days vs other days
t_test_overbought <- t.test(overbought_returns, other_returns, na.rm = TRUE)
t_test_oversold <- t.test(oversold_returns, other_returns, na.rm = TRUE)
# Print the results
print("T-test for Overbought Days (RSI > 70):")
print(t_test_overbought)
print("T-test for Oversold Days (RSI < 30):")
print(t_test_oversold)
# Calculate daily returns as percentage change in the gold closing price
data$returns <- c(NA, diff(data$close) / data$close[-nrow(data)] * 100)
# Define moving average crossover signal (10-day MA crosses above 50-day MA)
crossover_signal <- data$gold_SMA_10 > data$gold_SMA_50
# Subset returns based on crossover signals (buying/selling points)
crossover_returns <- data$returns[crossover_signal]
random_returns <- sample(data$returns, length(crossover_returns), replace = TRUE) # Random trading strategy
# Perform paired t-test to compare returns of crossover vs random strategy
paired_t_test <- t.test(crossover_returns, random_returns, paired = FALSE, na.rm = TRUE)
# Print the result
print("Paired t-test for Moving Average Strategy vs Random Strategy:")
print(paired_t_test)
# Install necessary packages (if not already installed)
install.packages("zoo")
install.packages("ggplot2")
data <- read.csv("C:\\Users\\VALLARI SHARMA\\Downloads\\Gold final PS.csv")
# Check the first few rows to see if columns were added correctly
head(data)
data$rolling_mean <- rollapply(data$close, width = 30, FUN = mean, fill = NA, align = "right")
data$rolling_mean
# Filter out rows where rolling_mean is NA
valid_data <- data[!is.na(data$rolling_mean), ]
# View the first few rows of the valid data
head(valid_data)
# View the rolling mean after the first 30 rows
head(data$rolling_mean, 40)
# Convert the 'time' column to Date format (assuming it's in 'dd/mm/yyyy' format)
data$time <- as.Date(data$time, format = "%d/%m/%Y")
# Sort data by time (if not already sorted)
data <- data[order(data$time),]
# Calculate daily returns as percentage change in the gold closing price
data$returns <- c(NA, diff(data$close) / data$close[-nrow(data)] * 100)
# Calculate 30-day rolling mean of gold closing prices
data$rolling_mean <- rollapply(data$close, width = 30, FUN = mean, fill = NA, align = "right")
# Calculate 30-day rolling volatility (standard deviation of returns)
data$rolling_volatility <- rollapply(data$returns, width = 30, FUN = sd, fill = NA, align = "right")
# Plot the rolling mean of gold prices over time
ggplot(data, aes(x = time)) +
geom_line(aes(y = rolling_mean), color = "blue", linewidth = 1) + # Changed size to linewidth
labs(title = "30-Day Rolling Mean of Gold Prices",
x = "Date", y = "Rolling Mean (Gold Price)") +
theme_minimal()
S
# Plot the rolling volatility of gold returns over time, handling missing values with na.rm = TRUE
ggplot(data, aes(x = time)) +
geom_line(aes(y = rolling_volatility), color = "red", linewidth = 1, na.rm = TRUE) + # Changed size to linewidth
labs(title = "30-Day Rolling Volatility of Gold Prices",
x = "Date", y = "Rolling Volatility (Standard Deviation of Returns)") +
theme_minimal()
# Adding vertical lines to mark significant historical events (e.g., financial crisis of 2008)
ggplot(data, aes(x = time)) +
geom_line(aes(y = rolling_volatility), color = "red", linewidth = 1, na.rm = TRUE) + # Changed size to linewidth
geom_vline(xintercept = as.Date("2008-09-15"), linetype = "dashed", color = "blue") + # Lehman Brothers collapse
labs(title = "30-Day Rolling Volatility of Gold Prices",
x = "Date", y = "Rolling Volatility (Standard Deviation of Returns)") +
annotate("text", x = as.Date("2008-09-15"), y = max(data$rolling_volatility, na.rm = TRUE),
label = "2008 Financial Crisis", vjust = -1) +
theme_minimal()
# Convert the 'time' column to Date format (assuming it's in 'dd/mm/yyyy' format)
data$time <- as.Date(data$time, format = "%d/%m/%Y")
# Sort data by time (if not already sorted)
data <- data[order(data$time),]
# Check the structure of the dataset
str(data)
# Plot the gold price time series using ggplot2
ggplot(data, aes(x = time, y = close)) +
geom_line(color = "blue", linewidth = 1) + # Line plot for closing prices
labs(title = "Gold Price Time Series",
x = "Date", y = "Gold Price (Closing)") +
theme_minimal() + # Clean theme for the plot
theme(axis.text.x = element_text(angle = 45, hjust = 1)) # Rotate x-axis labels for better readability
# Convert the 'time' column to Date format
data$time <- as.Date(data$time, format = "%d/%m/%Y")
# Extract 'Month' from the date to create a categorical variable for ANOVA
data$month <- format(data$time, "%m")
# Check the structure of the dataset
str(data)
# Remove any missing values if necessary
data <- na.omit(data)
# Perform one-way ANOVA to check if gold prices differ by month
anova_result <- aov(close ~ month, data = data)
# View the ANOVA table
summary(anova_result)
# If the ANOVA result is significant, perform Tukey's Honest Significant Difference (HSD) test
# This helps to understand which specific groups differ
tukey_result <- TukeyHSD(anova_result)
print(tukey_result)
# Visualize the gold prices by month to check the variation
ggplot(data, aes(x = month, y = close)) +
geom_boxplot(fill = "skyblue") +
labs(title = "Gold Prices by Month",
x = "Month", y = "Gold Price (Closing)") +
theme_minimal()
# Load necessary libraries
data <- read.csv("C:\\Users\\VALLARI SHARMA\\Downloads\\Gold final PS.csv")
# Convert 'time' column to Date format
data$time <- as.Date(data$time, format = "%d/%m/%Y")
# Extract month and year from the time variable for grouping
data$month <- month(data$time, label = TRUE) # Label months as Jan, Feb, etc.
data$year <- year(data$time)
# Calculate monthly average of gold prices
monthly_data <- data %>%
group_by(year, month) %>%
summarise(monthly_mean = mean(close, na.rm = TRUE))
# Plot the monthly average gold prices across years to detect seasonality
ggplot(monthly_data, aes(x = month, y = monthly_mean, group = year, color = factor(year))) +
geom_line() +
labs(title = "Monthly Average of Gold Prices Across Years",
x = "Month", y = "Average Gold Price") +
theme_minimal()
# Calculate monthly returns from closing prices
data <- data %>%
group_by(month) %>%
mutate(monthly_return = (close - lag(close)) / lag(close))
# Summarize monthly returns to detect seasonality
monthly_returns <- data %>%
group_by(month) %>%
summarise(mean_return = mean(monthly_return, na.rm = TRUE))
# Plot monthly average returns to detect seasonality
ggplot(monthly_returns, aes(x = month, y = mean_return)) +
geom_bar(stat = "identity", fill = "skyblue") +
labs(title = "Average Monthly Returns of Gold Prices",
x = "Month", y = "Average Monthly Return") +
theme_minimal()
# Perform ANOVA test to check if there is a significant difference in returns between months
anova_test <- aov(monthly_return ~ month, data = data)
summary(anova_test)
# Calculate Historical Returns
gold_data <- gold_data %>%
mutate(daily_return = c(NA, diff(log(close)))) # Log returns
# Estimate Parameters for Simulation
mu <- mean(gold_data$daily_return, na.rm = TRUE) # Expected return
sigma <- sd(gold_data$daily_return, na.rm = TRUE) # Volatility
S0 <- last(gold_data$close) # Last known gold price
# Run Monte Carlo Simulations
set.seed(123) # For reproducibility
n_simulations <- 1000 # Number of simulations
n_days <- 365 # Number of trading days in a year
simulated_prices <- matrix(NA, nrow = n_days, ncol = n_simulations)
for (i in 1:n_simulations) {
simulated_prices[1, i] <- S0 # Starting price
for (t in 2:n_days) {
simulated_prices[t, i] <- simulated_prices[t - 1, i] * exp(rnorm(1, mu, sigma))
}
}
# Convert matrix to data frame for ggplot
simulated_prices_df <- as.data.frame(simulated_prices)
simulated_prices_df <- mutate(simulated_prices_df, Day = 1:n_days)
simulated_prices_long <- pivot_longer(simulated_prices_df, -Day, names_to = "Simulation", values_to = "Price")
# Calculate mean and quantiles for confidence intervals
summary_stats <- simulated_prices_long %>%
group_by(Day) %>%
summarize(mean_price = mean(Price),
lower_bound = quantile(Price, 0.05),
upper_bound = quantile(Price, 0.95))
# Create a ggplot object
p <- ggplot() +
geom_ribbon(data = summary_stats, aes(x = Day, ymin = lower_bound, ymax = upper_bound),
fill = "black", alpha = 0.4) + # Confidence interval
geom_line(data = simulated_prices_long, aes(x = Day, y = Price, group = Simulation),
color = alpha("blue", 0.1), linewidth = 0.5) + # Simulation paths
theme_minimal(base_size = 16) +
labs(title = "Monte Carlo Simulations of Gold Prices",
subtitle = "Visualizing the potential future paths of gold prices with 90% confidence intervals",
x = "Days",
y = "Gold Price (in USD)",
caption = "Source: Your Gold Dataset") +
theme(panel.grid.major = element_line(color = "grey80"),
panel.grid.minor = element_blank(),
plot.title = element_text(hjust = 0.5, face = "bold"),
plot.subtitle = element_text(hjust = 0.5, face = "italic"),
plot.caption = element_text(hjust = 0, face = "italic"),
axis.title.x = element_text(),
axis.title.y = element_text())
# Convert ggplot to plotly for interactivity
interactive_plot <- ggplotly(p)
# Show the interactive plot
interactive_plot