library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.5.1     ✔ tibble    3.2.1
## ✔ lubridate 1.9.4     ✔ tidyr     1.3.1
## ✔ purrr     1.0.4     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(rvest)
## 
## Attaching package: 'rvest'
## 
## The following object is masked from 'package:readr':
## 
##     guess_encoding
library(ggplot2)
library(quantmod)
## Loading required package: xts
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## 
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## 
## 
## ######################### Warning from 'xts' package ##########################
## #                                                                             #
## # The dplyr lag() function breaks how base R's lag() function is supposed to  #
## # work, which breaks lag(my_xts). Calls to lag(my_xts) that you type or       #
## # source() into this session won't work correctly.                            #
## #                                                                             #
## # Use stats::lag() to make sure you're not using dplyr::lag(), or you can add #
## # conflictRules('dplyr', exclude = 'lag') to your .Rprofile to stop           #
## # dplyr from breaking base R's lag() function.                                #
## #                                                                             #
## # Code in packages is not affected. It's protected by R's namespace mechanism #
## # Set `options(xts.warn_dplyr_breaks_lag = FALSE)` to suppress this warning.  #
## #                                                                             #
## ###############################################################################
## 
## Attaching package: 'xts'
## 
## The following objects are masked from 'package:dplyr':
## 
##     first, last
## 
## Loading required package: TTR
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(kableExtra)
## 
## Attaching package: 'kableExtra'
## 
## The following object is masked from 'package:dplyr':
## 
##     group_rows
library(TTR)  # For moving averages

# Ticker symbol
ticker <- "COST"  # Costco Wholesale Corp.

# Scrape financial data from Finviz
finviz_url <- paste0("https://finviz.com/quote.ashx?t=", ticker)
webpage <- tryCatch(read_html(finviz_url), error = function(e) NULL)

if (!is.null(webpage)) {
  data <- webpage %>%
    html_nodes("table.snapshot-table2") %>%
    html_table(fill = TRUE)
  if (length(data) > 0) {
    financials <- data[[1]]
    colnames(financials) <- c("Metric", "Value")
  } else {
    financials <- data.frame(Metric = "No data", Value = "No data")
  }
} else {
  financials <- data.frame(Metric = "Error", Value = "Failed to fetch data")
}

# Display financials table
kable(financials, caption = paste("Key Financials for", ticker))
Key Financials for COST
Metric Value NA NA NA NA NA NA NA NA NA NA
Index NDX, S&P 500 P/E 54.77 EPS (ttm) 17.13 Insider Own 0.23% Shs Outstand 443.73M Perf Week -10.38%
Market Cap 416.45B Forward P/E 47.02 EPS next Y 19.95 Insider Trans -1.54% Shs Float 442.87M Perf Month -10.73%
Income 7.62B PEG 5.51 EPS next Q 4.22 Inst Own 69.59% Short Float 1.57% Perf Quarter -5.32%
Sales 264.09B P/S 1.58 EPS this Y 9.32% Inst Trans 1.29% Short Ratio 3.32 Perf Half Y 5.89%
Book/sh 57.64 P/B 16.28 EPS next Y 10.22% ROA 10.92% Short Interest 6.94M Perf Year 21.33%
Cash/sh 29.64 P/C 31.65 EPS next 5Y 9.94% ROE 32.89% 52W Range 697.27 - 1078.23 Perf YTD 2.39%
Dividend Est. 4.65 (0.50%) P/FCF 60.14 EPS past 5Y 14.93% ROI 22.67% 52W High -12.99% Beta 0.94
Dividend TTM 4.64 (0.49%) Quick Ratio 0.49 Sales past 5Y 10.86% Gross Margin 12.67% 52W Low 34.55% ATR (14) 25.94
Dividend Ex-Date Feb 07, 2025 Current Ratio 1.00 EPS Y/Y TTM 16.91% Oper. Margin 3.69% RSI (14) 31.86 Volatility 3.08% 2.07%
Employees 333000 Debt/Eq 0.31 Sales Y/Y TTM 6.13% Profit Margin 2.89% Recom 2.05 Target Price 1080.14
Option/Short Yes / Yes LT Debt/Eq 0.31 EPS Q/Q 2.58% Payout 26.32% Rel Volume 1.71 Prev Close 964.31
Sales Surprise 0.97% EPS Surprise -1.77% Sales Q/Q 9.04% Earnings Mar 06 AMC Avg Volume 2.09M Price 938.17
SMA20 -9.69% SMA50 -5.08% SMA200 2.96% Trades Volume 2,108,840 Change -2.71%
# Retrieve stock data from Yahoo Finance
stock_data <- tryCatch({
  getSymbols(ticker, src = "yahoo", from = Sys.Date() - 180, to = Sys.Date(), auto.assign = FALSE)
}, error = function(e) NULL)

if (!is.null(stock_data)) {
  # Calculate daily returns
  stock_data$Daily_Return <- dailyReturn(Cl(stock_data))

  # Summary of daily returns
  print(summary(stock_data$Daily_Return))

  # Calculate 20-day simple moving average (SMA)
  stock_data$Moving_Avg <- SMA(Cl(stock_data), n = 20)

  # Enhanced plot with customized style
  chartSeries(stock_data, 
              theme = chartTheme("white", up.col = "darkgreen", dn.col = "darkred", border = "blue"), 
              name = paste("Stock Price of", ticker),
              TA = "addSMA(n=20, col='purple'); addBBands()")
} else {
  print(paste("Failed to retrieve stock data for", ticker))
}
##      Index             Daily_Return       
##  Min.   :2024-09-11   Min.   :-0.0606943  
##  1st Qu.:2024-10-23   1st Qu.:-0.0068279  
##  Median :2024-12-05   Median : 0.0003720  
##  Mean   :2024-12-07   Mean   : 0.0006449  
##  3rd Qu.:2025-01-22   3rd Qu.: 0.0083164  
##  Max.   :2025-03-07   Max.   : 0.0326830