Номын сан болон өгөгдөл татах

library(tidyquant)
library(dplyr)
library(ggplot2)
library(zoo)
library(timeDate)
library(scales)
nke <- tq_get("NKE", from = "2025-03-07", to = "2026-03-06")

dates <- nke$date
price <- nke$close
n     <- length(price)

cat("Нийт өгөгдөл:", n, "өдөр\n")
## Нийт өгөгдөл: 250 өдөр
cat("Хугацаа:", as.character(min(dates)), "~", as.character(max(dates)), "\n")
## Хугацаа: 2025-03-07 ~ 2026-03-05

Арифметик өгөөж

ret   <- diff(price) / head(price, -1)
T_len <- length(ret)

μ ба σ үнэлэх

mu    <- mean(ret)
sigma <- sd(ret)

cat("mu    =", round(mu, 6), "\n")
## mu    = -0.000872
cat("sigma =", round(sigma, 6), "\n")
## sigma = 0.026371

200 удаагийн Брауны симуляци

set.seed(123)

sim_list <- list()
ret_list <- list()
SSE      <- numeric(200)

for (sim in 1:200) {
  z     <- rnorm(T_len, mean = 0, sd = 1)
  r_sim <- mu + sigma * z

  p_sim    <- numeric(n)
  p_sim[1] <- price[1]
  for (t in 2:n) {
    p_sim[t] <- p_sim[t-1] * (1 + r_sim[t-1])
  }

  sim_list[[sim]] <- p_sim
  ret_list[[sim]] <- r_sim
  SSE[sim]        <- sum((price - p_sim)^2)
}

best_index     <- which.min(SSE)
best_price     <- sim_list[[best_index]]
best_ret       <- ret_list[[best_index]]
best_price_SSE <- SSE[best_index]

cat("Minimum SSE =", formatC(best_price_SSE, format = "f", digits = 2, big.mark = ","), "\n")
## Minimum SSE = 9,939.44
cat("Шилдэг симуляц #", best_index, "\n")
## Шилдэг симуляц # 15

Дизайн theme


График 1 — Шилдэг симуляц vs ажиглагдсан

df_plot <- data.frame(
  date      = dates,
  Observed  = price,
  Simulated = best_price
)

sse_label <- paste0(
  "Шилдэг симуляц #", best_index,
  "\nSSE = ", formatC(best_price_SSE, format = "f", digits = 0, big.mark = ",")
)

p1_ymin <- min(c(price, best_price)) * 0.97
p1_ymax <- max(c(price, best_price)) * 1.03

ggplot(df_plot, aes(x = date)) +
  geom_line(aes(y = Simulated, color = "Шилдэг симуляц"), linewidth = 0.9, alpha = 0.75) +
  geom_line(aes(y = Observed,  color = "Ажиглагдсан"),    linewidth = 1.1) +
  geom_point(data = df_plot[c(1, nrow(df_plot)), ],
             aes(y = Observed), color = clr_up, size = 3, shape = 21,
             fill = "white", stroke = 1.5) +
  annotate("label",
           x = min(dates) + 30, y = p1_ymax * 0.97,
           label = sse_label,
           color = clr_sim, fill = "#F5F3FF",
           label.size = 0.3, size = 3.2, fontface = "italic", hjust = 0) +
  scale_color_manual(values = c("Ажиглагдсан" = clr_up, "Шилдэг симуляц" = clr_sim)) +
  scale_x_date(date_labels = "%b %Y", date_breaks = "2 months") +
  scale_y_continuous(labels = dollar_format(), n.breaks = 8) +
  coord_cartesian(ylim = c(p1_ymin, p1_ymax)) +
  labs(
    title    = "NKE — Брауны хөдөлгөөн: Шилдэг симуляц",
    subtitle = paste0("200 симуляц  |  μ = ", round(mu, 6),
                      "  |  σ = ", round(sigma, 6),
                      "  |  SSE = ", formatC(min(SSE), format = "e", digits = 3)),
    y = "Хаалтын ханш (USD)", x = NULL,
    caption = "Эх сурвалж: Yahoo Finance  |  Брауны хөдөлгөөний загвар  |  set.seed(123)"
  ) +
  theme_pro + theme(legend.position = "top")
Шилдэг GBM симуляц нь ажиглагдсан ханштай харьцуулалт

Шилдэг GBM симуляц нь ажиглагдсан ханштай харьцуулалт


График 2 — 200 симуляцийн SSE харьцуулалт

df_sse      <- data.frame(sim = 1:200, SSE = SSE)
df_sse$rank <- rank(df_sse$SSE)

ggplot(df_sse, aes(x = sim, y = SSE)) +
  geom_segment(aes(xend = sim, yend = min(SSE) * 0.98), color = clr_grid, linewidth = 0.5) +
  geom_point(aes(color = rank), size = 2, alpha = 0.85) +
  geom_point(data = df_sse[best_index, ], aes(x = sim, y = SSE),
             color = clr_dn, size = 5, shape = 18) +
  geom_hline(yintercept = best_price_SSE,
             color = clr_dn, linetype = "dashed", linewidth = 0.6, alpha = 0.7) +
  annotate("label",
           x = best_index + 10, y = best_price_SSE,
           label = paste0("Min SSE\nСимуляц #", best_index),
           color = clr_dn, fill = "#FEF2F2",
           label.size = 0.3, size = 3.2, fontface = "bold") +
  scale_color_gradient(low = "#DDD6FE", high = clr_up, guide = "none") +
  scale_y_continuous(labels = comma) +
  labs(
    title    = "NKE — 200 Брауны симуляцийн SSE харьцуулалт",
    subtitle = paste0("Шилдэг симуляц #", best_index,
                      "  |  Min SSE = ", formatC(best_price_SSE, format = "f", digits = 0, big.mark = ","),
                      "  |  Дундаж SSE = ", formatC(mean(SSE), format = "f", digits = 0, big.mark = ",")),
    x = "Симуляцийн дугаар", y = "SSE (үнэ²)",
    caption = "Нил ягаан → Ногоон: муу → сайн  |  Улаан ромб: хамгийн сайн"
  ) +
  theme_pro
200 Брауны симуляц тус бүрийн SSE утгын харьцуулалт

200 Брауны симуляц тус бүрийн SSE утгын харьцуулалт


30 өдрийн таамаглал

future_days <- 30
z_future    <- rnorm(future_days, 0, 1)
r_future    <- mu + sigma * z_future

future_price    <- numeric(future_days)
future_price[1] <- best_price[n] * (1 + r_future[1])
for (t in 2:future_days) {
  future_price[t] <- future_price[t-1] * (1 + r_future[t])
}

cat("30 өдрийн дараах таамаглаж буй үнэ = $", round(tail(future_price, 1), 2), "\n")
## 30 өдрийн дараах таамаглаж буй үнэ = $ 53.42
future_dates <- timeSequence(from = as.Date("2026-03-09"), by = "day", length.out = 60)
future_dates <- as.Date(future_dates[isBizday(future_dates)][1:30])

График 3 — Симуляц & 30 хоногийн таамаглал

last_obs   <- price[n]
last_fore  <- tail(future_price, 1)
fore_dir   <- ifelse(last_fore >= last_obs, "↑ Өсөх", "↓ Буурах")
fore_color <- ifelse(last_fore >= last_obs, clr_up, clr_dn)
fore_bg    <- ifelse(last_fore >= last_obs, "#F0FDF4", "#FEF2F2")

all_vals <- c(price, best_price, future_price)
y_min    <- min(all_vals, na.rm = TRUE) * 0.97
y_max    <- max(all_vals, na.rm = TRUE) * 1.03
label_y  <- pmin(pmax(last_fore, y_min + (y_max - y_min) * 0.05), y_max - (y_max - y_min) * 0.10)
split_x  <- max(dates)

df_hist   <- data.frame(date = dates,       Observed = price,      Simulated = best_price,  Forecast = NA_real_)
df_future <- data.frame(date = future_dates, Observed = NA_real_,  Simulated = NA_real_,    Forecast = future_price)
df_total  <- rbind(df_hist, df_future)

forecast_region <- data.frame(xmin = min(future_dates), xmax = max(future_dates), ymin = -Inf, ymax = Inf)

ggplot(df_total, aes(x = date)) +
  geom_rect(data = forecast_region,
            aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax),
            fill = "#FEF9C3", alpha = 0.4, inherit.aes = FALSE) +
  geom_vline(xintercept = as.numeric(split_x), color = "#CBD5E1", linewidth = 0.8, linetype = "dashed") +
  annotate("text", x = split_x - 8, y = y_max * 0.993,
           label = "Өнгөрсөн ◀", color = clr_sub, size = 2.8, hjust = 1, fontface = "italic") +
  annotate("text", x = split_x + 8, y = y_max * 0.993,
           label = "▶ Таамаглал", color = clr_sub, size = 2.8, hjust = 0, fontface = "italic") +
  geom_line(aes(y = Simulated, color = "Шилдэг симуляц"),        linewidth = 0.85, alpha = 0.6, na.rm = TRUE) +
  geom_line(aes(y = Observed,  color = "Ажиглагдсан"),           linewidth = 1.15, na.rm = TRUE) +
  geom_line(aes(y = Forecast,  color = "30 хоногийн таамаглал"), linewidth = 1.4,  na.rm = TRUE) +
  geom_point(data = tail(df_future[!is.na(df_future$Forecast), ], 1),
             aes(y = Forecast), color = fore_color, size = 4, shape = 21,
             fill = fore_color, stroke = 1.2, na.rm = TRUE) +
  annotate("label",
           x = max(future_dates) - 3, y = label_y,
           label = paste0(fore_dir, "  $", round(last_fore, 2)),
           color = fore_color, fill = fore_bg,
           label.size = 0.4, size = 3.8, fontface = "bold", hjust = 1) +
  scale_color_manual(
    values = c("Ажиглагдсан" = clr_up, "Шилдэг симуляц" = clr_sim, "30 хоногийн таамаглал" = clr_fore),
    breaks = c("Ажиглагдсан", "Шилдэг симуляц", "30 хоногийн таамаглал")
  ) +
  scale_x_date(date_labels = "%b %Y", date_breaks = "2 months") +
  scale_y_continuous(labels = dollar_format(), n.breaks = 8) +
  coord_cartesian(ylim = c(y_min, y_max)) +
  labs(
    title    = "NKE — Брауны хөдөлгөөн: Симуляц & 30 хоногийн таамаглал",
    subtitle = paste0("200 симуляц  |  μ = ", round(mu, 6),
                      "  |  σ = ", round(sigma, 6),
                      "  |  Шилдэг симуляц #", best_index,
                      "  |  Таамаглал: $", round(last_fore, 2)),
    y = "Хаалтын ханш (USD)", x = NULL,
    caption = "Эх сурвалж: Yahoo Finance  |  Брауны хөдөлгөөний загвар  |  set.seed(123)"
  ) +
  theme_pro + theme(legend.position = "top")
Ажиглагдсан өгөгдөл, шилдэг симуляц болон 30 хоногийн таамаглал

Ажиглагдсан өгөгдөл, шилдэг симуляц болон 30 хоногийн таамаглал


Үр дүнгийн хураангуй

Брауны хөдөлгөөний загварын үр дүнгийн хураангуй
Үзүүлэлт Утга
Өгөгдлийн хугацаа 2025-03-07 ~ 2026-03-05
Нийт ажиглалтын тоо 250
Дундаж өгөөж (μ) -0.000872
Өгөөжийн стандарт хазайлт (σ) 0.026371
Нийт симуляцийн тоо 200
Шилдэг симуляцийн дугаар 15
Хамгийн бага SSE 9,939.44
Дундаж SSE 102,730.52
30 өдрийн таамаглал $53.42 (↓ Буурах)

Эх сурвалж: Yahoo Finance | Брауны хөдөлгөөний загвар | set.seed(123)