Predicción de acciones de Tesla, Inc. (TSLA)

Búsqueda y extracción de datos de Tesla, Inc. (TSLA)

TSLAdata <- pdfetch_YAHOO("TSLA",from = c("2019-01-01"),to = c("2023-01-03"), interval = '1d')
tesla <- TSLAdata[,4]
length(TSLAdata)
## [1] 6048

Serie de tiempo

tstesla <- ts(tesla, start = c(2019,1),frequency=365)
plot(tstesla)

Comola serie de tiempo no es estacionaria, se debe de hacer una diferenciación utilizando logarimos.

l_tesla<-diff(log(tstesla))
plot(l_tesla)

tseries::adf.test(l_tesla)
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
## Warning in tseries::adf.test(l_tesla): p-value smaller than printed p-value
## 
##  Augmented Dickey-Fuller Test
## 
## data:  l_tesla
## Dickey-Fuller = -8.7628, Lag order = 10, p-value = 0.01
## alternative hypothesis: stationary

Obtención de parámetros iniciales

Forma #1

Delta <- 1/365
alpha <- mean(l_tesla)/Delta
sigma <- sqrt(var(l_tesla)/Delta)
mu <- alpha +0.5*sigma^2
x0<-tstesla[1]

Forma #2

x <- tstesla
gBm <- setModel(drift="mu*x", diffusion="sigma*x", xinit=x0)
## Warning in yuima.warn("Solution variable (lhs) not specified. Trying to use state variables."): 
## YUIMA: Solution variable (lhs) not specified. Trying to use state variables.
mod <- setYuima(model=gBm, data=setData(tstesla, delta=Delta))
set.seed(123)
fit <- qmle(mod, start=list(mu=0, sigma=1),
            lower=list(mu=0.1, sigma=0.1),
            upper=list(mu=100, sigma=10))
summary(fit)
## Quasi-Maximum likelihood estimation
## 
## Call:
## qmle(yuima = mod, start = list(mu = 0, sigma = 1), lower = list(mu = 0.1, 
##     sigma = 0.1), upper = list(mu = 100, sigma = 10))
## 
## Coefficients:
##        Estimate Std. Error
## sigma 0.8087841 0.01807357
## mu    0.9733399 0.48692751
## 
## -2 log L: 5729.343

Comparación de resultados

coef(fit)
##     sigma        mu 
## 0.8087841 0.9733399
sigma
##            TSLA.close
## TSLA.close  0.8080848
mu
##            TSLA.close
## TSLA.close  0.9734014
gbm_vec <- function(nsim = 10000, t = 25, mu = 0, sigma = 0.1, S0 = 100, dt = 1./365) {
  # matrix of random draws - one for each day for each simulation
  epsilon <- matrix(rnorm(t*nsim), ncol = nsim, nrow = t)  
  # get GBM and convert to price paths
  gbm <- exp((mu - sigma * sigma / 2) * dt + sigma * epsilon * sqrt(dt))
  gbm <- apply(rbind(rep(S0, nsim), gbm), 2, cumprod)
  return(gbm)
}

Gráfica de valores simulados

gBm
## 
## Diffusion process
## Number of equations: 1
## Number of Wiener noises: 1
## Parametric model with 2 parameters
valores_simulados <- simulate(gBm, true.parameter = list(mu=mu, sigma=sigma))
## Warning in yuima.warn("'delta' (re)defined."): 
## YUIMA: 'delta' (re)defined.
plot(valores_simulados)

Evaluando ambas formas de parámetros

nsim <- 1000
t <- 366
mu <- 1.517177
sigma <- 0.531907
S0 <- 32.72
dt = 1/365
gbm <- gbm_vec(nsim, t, mu, sigma, S0, dt)

Gráfica del valor de las acciones de Tesla, Inc. (TSLA)

gbm_df <- as.data.frame(gbm) %>%
  mutate(ix = 1:nrow(gbm)) %>%
  pivot_longer(-ix, names_to = 'sim', values_to = 'price')
gbm_df %>%
  ggplot(aes(x=ix, y=price, color=sim)) +
  geom_line() +
  theme(legend.position = 'none')

Gráfica de la distribución de precios de Tesla, Inc. (TSLA)

data.frame(price = gbm[253, ]) %>%
  ggplot(aes(x = price)) +
  geom_histogram(aes(y = ..density..), binwidth = 0.1) +
  geom_density() + 
  ggtitle('terminal price distribution')
## Warning: The dot-dot notation (`..density..`) was deprecated in ggplot2 3.4.0.
## ℹ Please use `after_stat(density)` instead.

D <- gbm[253, ] %>%
  density()

Resultado del modelo

D$x[which.max(D$y)]
## [1] 71.38717
TSLAdata2 <- pdfetch_YAHOO("WMT",from = c("2019-01-01"),to = c("2023-03-03"), interval = '1d')
tesla2 <- TSLAdata2[,4]
View(tesla2)