knitr::opts_chunk$set(echo = TRUE)
##https://rpubs.com/kcin999/yahoo-finance
# Yahoo Finance is a powerful suite of information supported by Yahoo,
# which provides information such as:
#. Financial News
#. Stock and Market Data (Stock Quotes, Financial Reports, etc.)
# In R, there is quantmod, which also retrieves the information needed.
# It also provides a couple of charts and details that we can use 
# in order to further help our analysis.
# install.packages("quantmod")
library(xts)
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
library(zoo)
library(quantmod)
## Loading required package: TTR
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
#These three indices are representative of the capitalization of companies 
# listed on North American stock exchanges, but each group has shares and
# weightings with a specific method.

# The Dow Jones is a stock index made up of 30 companies with the largest 
# market capitalization on the New York Stock Exchange (NYSE), with the 
# exception of transportation and public services.

# The Nasdaq is a stock of securities prepared by electronic companies and 
# based on various indices that it represents.

# Finally, the S&P 500 is an index with the 500 most representative 
# companies on the New York Stock Exchange.

# https://cran.r-project.org/web/packages/quantmod/quantmod.pdf
# To collect information about Dow Jones Industrial Average (DJI). 
# We only need to know their ticker, which is ‘^DJI’ on the Yahoo.Finance.
DJ=getSymbols('^DJI', 
               src='yahoo', 
               auto.assign=FALSE)
na.omit(DJ)
##            DJI.Open DJI.High  DJI.Low DJI.Close DJI.Volume DJI.Adjusted
## 2007-01-03 12459.54 12580.35 12404.82  12474.52  327200000     12474.52
## 2007-01-04 12473.16 12510.41 12403.86  12480.69  259060000     12480.69
## 2007-01-05 12480.05 12480.13 12365.41  12398.01  235220000     12398.01
## 2007-01-08 12392.01 12445.92 12337.37  12423.49  223500000     12423.49
## 2007-01-09 12424.77 12466.43 12369.17  12416.60  225190000     12416.60
## 2007-01-10 12417.00 12451.61 12355.63  12442.16  226570000     12442.16
## 2007-01-11 12442.96 12544.46 12442.96  12514.98  261720000     12514.98
## 2007-01-12 12514.66 12561.04 12489.66  12556.08  256530000     12556.08
## 2007-01-16 12555.84 12585.08 12538.93  12582.59  242720000     12582.59
## 2007-01-17 12571.46 12614.00 12550.55  12577.15  272720000     12577.15
##        ...                                                             
## 2023-11-27 35376.44 35410.37 35280.57  35333.47  258340000     35333.47
## 2023-11-28 35332.13 35518.67 35307.73  35416.98  256210000     35416.98
## 2023-11-29 35436.80 35579.13 35405.89  35430.42  299330000     35430.42
## 2023-11-30 35596.57 35970.70 35592.22  35950.89  435540000     35950.89
## 2023-12-01 35914.45 36264.85 35914.45  36245.50  321840000     36245.50
## 2023-12-04 36089.38 36238.18 36029.69  36204.44  329450000     36204.44
## 2023-12-05 36135.65 36164.68 36010.85  36124.56  309250000     36124.56
## 2023-12-06 36183.73 36292.58 36024.25  36054.43  283240000     36054.43
## 2023-12-07 36124.17 36164.17 36021.95  36117.38  287280000     36117.38
## 2023-12-08 36084.82 36296.20 36061.64  36247.87  295180000     36247.87
## chartSeries in order to generate some visualizations.
# This code generates the trend of Dow Jones Industrial Average (DJI)
# price and volume over the last 6 months.
chartSeries(DJ, 
            name="Dow Jones Industrial Average (DJI)", 
            subset="last 6 months", 
            type = "auto",    # same as "candlesticks"
            theme=chartTheme("white"))

## To collect information about NASDAQ Composite (^IXIC). 
# We only need to know their ticker, which is ‘^IXIC’  Yahoo.Finance.
ND=getSymbols("^IXIC", 
               src='yahoo', 
               auto.assign=FALSE)
na.omit(ND)
##            IXIC.Open IXIC.High IXIC.Low IXIC.Close IXIC.Volume IXIC.Adjusted
## 2007-01-03   2429.72   2454.62  2394.66    2423.16  2435280000       2423.16
## 2007-01-04   2423.82   2460.51  2413.75    2453.43  2104210000       2453.43
## 2007-01-05   2445.07   2445.07  2420.59    2434.25  2060360000       2434.25
## 2007-01-08   2435.25   2445.63  2421.13    2438.20  1905620000       2438.20
## 2007-01-09   2443.26   2449.87  2423.56    2443.83  2144160000       2443.83
## 2007-01-10   2434.04   2461.34  2427.90    2459.33  2274210000       2459.33
## 2007-01-11   2464.89   2489.46  2463.39    2484.85  2436270000       2484.85
## 2007-01-12   2481.72   2502.82  2481.54    2502.82  2175810000       2502.82
## 2007-01-16   2504.56   2508.93  2493.92    2497.78  2139550000       2497.78
## 2007-01-17   2487.89   2496.93  2475.83    2479.42  2273880000       2479.42
##        ...                                                                  
## 2023-11-27  14239.31  14305.71 14205.24   14241.02  4205880000      14241.02
## 2023-11-28  14224.63  14303.66 14195.72   14281.76  4474400000      14281.76
## 2023-11-29  14367.11  14423.22 14247.89   14258.49  4890220000      14258.49
## 2023-11-30  14265.05  14289.20 14127.05   14226.22  5678070000      14226.22
## 2023-12-01  14181.35  14311.95 14135.00   14305.03  5607000000      14305.03
## 2023-12-04  14168.66  14197.52 14058.52   14185.49  6270020000      14185.49
## 2023-12-05  14126.40  14285.66 14121.76   14229.91  6179120000      14229.91
## 2023-12-06  14325.62  14327.63 14138.51   14146.71  5167030000      14146.71
## 2023-12-07  14230.43  14353.11 14220.87   14339.99  5694310000      14339.99
## 2023-12-08  14279.46  14416.92 14264.96   14403.97  5430840000      14403.97
chartSeries(ND, 
            name="NASDAQ Composite (^IXIC)", 
            subset="last 6 months",
            type = "matchsticks",
            theme=chartTheme("white"))

## To collect information about S&P 500 (^GSPC). 
# We only need to know their ticker, which is ‘^GSPC’  Yahoo.Finance.
SP=getSymbols("^GSPC", 
               src='yahoo', 
               auto.assign=FALSE)
na.omit(SP)
##            GSPC.Open GSPC.High GSPC.Low GSPC.Close GSPC.Volume GSPC.Adjusted
## 2007-01-03   1418.03   1429.42  1407.86    1416.60  3429160000       1416.60
## 2007-01-04   1416.60   1421.84  1408.43    1418.34  3004460000       1418.34
## 2007-01-05   1418.34   1418.34  1405.75    1409.71  2919400000       1409.71
## 2007-01-08   1409.26   1414.98  1403.97    1412.84  2763340000       1412.84
## 2007-01-09   1412.84   1415.61  1405.42    1412.11  3038380000       1412.11
## 2007-01-10   1408.70   1415.99  1405.32    1414.85  2764660000       1414.85
## 2007-01-11   1414.84   1427.12  1414.84    1423.82  2857870000       1423.82
## 2007-01-12   1423.82   1431.23  1422.58    1430.73  2686480000       1430.73
## 2007-01-16   1430.73   1433.93  1428.62    1431.90  2599530000       1431.90
## 2007-01-17   1431.77   1435.27  1428.57    1430.62  2690270000       1430.62
##        ...                                                                  
## 2023-11-27   4554.86   4560.52  4546.32    4550.43  3403990000       4550.43
## 2023-11-28   4545.55   4568.14  4540.51    4554.89  3586240000       4554.89
## 2023-11-29   4571.84   4587.64  4547.15    4550.58  4418760000       4550.58
## 2023-11-30   4554.87   4569.89  4537.24    4567.80  5399300000       4567.80
## 2023-12-01   4559.43   4599.39  4554.71    4594.63  4397120000       4594.63
## 2023-12-04   4564.37   4572.37  4546.72    4569.78  4369910000       4569.78
## 2023-12-05   4557.25   4578.56  4551.68    4567.18  3909950000       4567.18
## 2023-12-06   4586.23   4590.74  4546.50    4549.34  4245680000       4549.34
## 2023-12-07   4568.84   4590.92  4565.22    4585.59  3818880000       4585.59
## 2023-12-08   4576.20   4609.23  4574.06    4604.37  3707010000       4604.37
chartSeries(SP, 
            name="S&P 500 (^GSPC)", 
            subset="last 6 months",
            type = "candlesticks",
            theme=chartTheme("white"))

# In order to visualize the 3 indices together we are going to build a
# Matrix of visualizacion
M=matrix(c(1,1,2,2,3,3),nrow=6,ncol=1)
layout(M)
layout.show(n=3)

par(bty="n")
# Then we plot each of the Indices' column of the Closed Price Adjusted
plot(x=DJ,                              # Draw first time series
     y=DJ$DJI.Adjusted,
     type = "l",                       # Lines
     main="Dow Jones Industrial Average (DJI)", 
     col.main="red",                   # Color of the main title
     xlab = "Year",
     ylab = "Values",
     las=2)                     # Axis labels Perpendicular to axis
plot(ND,                             # Draw second time series
      y=ND$IXIC.Adjusted,
     main="NASDAQ Composite (^IXIC)",
     type = "l",                       # Lines
     col = 3, 
     las=2)                     # Axis labels Perpendicular to axis
## Warning in merge.xts(temp_xts, xts_object, fill = na.locf, join = "right", :
## NAs introduced by coercion to integer range
plot(SP,                             # Draw third time series
      y=SP$GSPC.Adjusted ,
     main="S&P 500 (^GSPC)",
     type = "l",                       # Lines
     col = 4, 
     las=2)                     # Axis labels Perpendicular to axis
## Warning in merge.xts(temp_xts, xts_object, fill = na.locf, join = "right", :
## NAs introduced by coercion to integer range

# We take only the column of the Closed Price Adjusted of each index and
# Binded in one Data Frame
df=cbind(DJ$DJI.Adjusted,ND$IXIC.Adjusted,SP$GSPC.Adjusted)
nombre=c("DowJones","Nasdaq","SP500") # Standard and Poor's 500
names(df)=nombre
head(df)
##            DowJones  Nasdaq   SP500
## 2007-01-03 12474.52 2423.16 1416.60
## 2007-01-04 12480.69 2453.43 1418.34
## 2007-01-05 12398.01 2434.25 1409.71
## 2007-01-08 12423.49 2438.20 1412.84
## 2007-01-09 12416.60 2443.83 1412.11
## 2007-01-10 12442.16 2459.33 1414.85
#install.packages("tidyquant")
library(tidyquant)
## Loading required package: lubridate
## 
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
## Loading required package: PerformanceAnalytics
## 
## Attaching package: 'PerformanceAnalytics'
## The following object is masked from 'package:graphics':
## 
##     legend
#install.packages("plotly")
library(plotly)
## Loading required package: ggplot2
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
tickers = c("^DJI", "^IXIC", "^GSPC")
for (i in tickers){
  getSymbols(i,
             from = "2018-01-01",
             to = "2019-12-31")}
stock <- data.frame(DJI$DJI.Adjusted,
                    IXIC$IXIC.Adjusted,
                    GSPC$GSPC.Adjusted)
stock$DJI.Adjusted=stock$DJI.Adjusted/stock$DJI.Adjusted[1]
stock$IXIC.Adjusted=stock$IXIC.Adjusted/stock$IXIC.Adjusted[1]
stock$GSPC.Adjusted=stock$GSPC.Adjusted/stock$GSPC.Adjusted[1]
stock <- data.frame(stock,rownames(stock))
colnames(stock) <- append(tickers,'Dates')
fig <- plot_ly(stock, type = 'scatter', mode = 'lines')%>%
  add_trace(x = ~Dates, y = ~`^DJI`, name = 'DowJones')%>%
  add_trace(x = ~Dates, y = ~`^IXIC`, name = 'Nasdaq')%>%
  add_trace(x = ~Dates, y = ~`^GSPC`, name = 'S&P500')%>%
  layout(title = 'USA Indices',legend=list(title=list(text='variable')),
         xaxis = list(dtick = "M1", tickformat="%b<br>%Y"), width = 1000)
## Warning: Specifying width/height in layout() is now deprecated.
## Please specify in ggplotly() or plot_ly()
options(warn = -1)
fig <- fig %>%
  layout(
         xaxis = list(zerolinecolor = '#ffff',
                      zerolinewidth = 2,
                      gridcolor = 'ffff'),
         yaxis = list(zerolinecolor = '#ffff',
                      zerolinewidth = 2,
                      gridcolor = 'ffff'),
         plot_bgcolor='#e5ecf6')


fig
# Compare Values of the time series between DowJones, Nasdaq, and S&P500
plot(df, 
     main="DowJones, Nasdaq, S&P500 ",
     xlab="Dates",
     ylab="",
     legend.loc="topleft")

library(psych)
## 
## Attaching package: 'psych'
## The following objects are masked from 'package:ggplot2':
## 
##     %+%, alpha
C=cor(df)
corPlot(df,
        main=" Debido a la alta correlacion solo se debe 
        usar uno para el modelo",
        min.length = 2,
        cex = 1.25,
        pval = TRUE,
        upper = FALSE,
        colors=TRUE)

# create a waterfall plot from the table
#install.packages("ggplot2")
library(ggplot2)
#install.packages("waterfalls")
library(waterfalls)
# create company income statement
category <- c("DowJones","Nasdaq","S&P500")
wdf <- data.frame(category,df[4264]) 
waterfall(wdf,  # create waterfall chart with total column
          value=FALSE,
          calc_total=TRUE, 
          total_axis_text = "Total", 
          total_rect_text_color="black",
          total_rect_color="goldenrod1") +
  scale_y_continuous(label=scales::dollar) +
  labs(title = "USA Indices", 
       subtitle = "Years 2017-2023",
       y="", 
       x="") +
  theme_minimal()