library(xml2)
## Warning: package 'xml2' was built under R version 3.6.3
library(tidyverse)
## Warning: package 'tidyverse' was built under R version 3.6.3
## -- Attaching packages ------------------------------------------------------------------------------------------------ tidyverse 1.3.0 --
## v ggplot2 3.3.0     v purrr   0.3.3
## v tibble  3.0.0     v dplyr   0.8.5
## v tidyr   1.0.2     v stringr 1.4.0
## v readr   1.3.1     v forcats 0.5.0
## Warning: package 'tibble' was built under R version 3.6.3
## Warning: package 'tidyr' was built under R version 3.6.3
## Warning: package 'readr' was built under R version 3.6.3
## Warning: package 'purrr' was built under R version 3.6.3
## Warning: package 'dplyr' was built under R version 3.6.3
## Warning: package 'stringr' was built under R version 3.6.3
## Warning: package 'forcats' was built under R version 3.6.3
## -- Conflicts --------------------------------------------------------------------------------------------------- tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(tidyquant)
## Warning: package 'tidyquant' was built under R version 3.6.3
## Loading required package: lubridate
## Warning: package 'lubridate' was built under R version 3.6.3
## 
## Attaching package: 'lubridate'
## The following objects are masked from 'package:dplyr':
## 
##     intersect, setdiff, union
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
## Loading required package: PerformanceAnalytics
## Warning: package 'PerformanceAnalytics' was built under R version 3.6.3
## Loading required package: xts
## Warning: package 'xts' was built under R version 3.6.3
## Loading required package: zoo
## Warning: package 'zoo' was built under R version 3.6.3
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## 
## Attaching package: 'xts'
## The following objects are masked from 'package:dplyr':
## 
##     first, last
## 
## Attaching package: 'PerformanceAnalytics'
## The following object is masked from 'package:graphics':
## 
##     legend
## Loading required package: quantmod
## Warning: package 'quantmod' was built under R version 3.6.3
## Loading required package: TTR
## Warning: package 'TTR' was built under R version 3.6.3
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
## Version 0.4-0 included new data defaults. See ?getSymbols.
## == Need to Learn tidyquant? =============================================================================================================
## Business Science offers a 1-hour course - Learning Lab #9: Performance Analysis & Portfolio Optimization with tidyquant!
## </> Learn more at: https://university.business-science.io/p/learning-labs-pro </>
library(dygraphs)
## Warning: package 'dygraphs' was built under R version 3.6.3
library(reshape2)
## Warning: package 'reshape2' was built under R version 3.6.3
## 
## Attaching package: 'reshape2'
## The following object is masked from 'package:tidyr':
## 
##     smiths
Ra <- c("AAPL", "GOOG", "NFLX", "XLK") %>%
    tq_get(get  = "stock.prices",
           from = "2010-01-01",
           to   = "2020-04-09") %>%
    group_by(symbol)

 
RaReturn<-Ra%>%
    tq_transmute(select     = adjusted, 
                 mutate_fun = periodReturn, 
                 period     = "monthly", 
                 col_rename = "Ra")
 options("scipen"=100, "digits"=4)
 Ra
Ra<-Ra[,c(1,2,8)] 
Ra_w<-dcast(melt(Ra, id.vars=c("date", "symbol")), date~symbol+variable)
dates<-seq(as.Date("2010-01-01"), length=2584,by="days" )

Ra_w<-xts(Ra_w[,c(2:5)], Ra_w$date)
 
 
dygraph(Ra_w)%>%dyLegend(show="always")
RaReturn
RaR_w<-dcast(melt(RaReturn, id.vars=c("date", "symbol")), date~symbol+variable)
dates<-seq(as.Date("2010-01-29"), length=124,by="months" )

RaR_w<-xts(RaR_w[,c(2:5)],RaR_w$date)
 
 
dygraph(RaR_w)%>%dyLegend(show="always")
RaReturn<-Ra%>%
    tq_transmute(select     = adjusted, 
                 mutate_fun = periodReturn, 
                 period     = "yearly", 
                 col_rename = "Ra")
 options("scipen"=100, "digits"=4)
 

 RaReturn
RaReturn %>%
    ggplot(aes(x = date, y = Ra, fill = symbol)) +
    geom_col() +
    geom_hline(yintercept = 0, color = palette_light()[[1]]) +
    scale_y_continuous(labels = scales::percent) +
    labs(title = "Annual Returns",
         subtitle = "Get annual returns quickly with tq_transmute!",
         y = "Annual Returns", x = "") + 
    facet_wrap(~ symbol, ncol = 2, scales = "free_y") +
    theme_tq() + 
    scale_fill_tq()

RaReturn_daily<-Ra%>%
    tq_transmute(select     = adjusted, 
                 mutate_fun = periodReturn, 
                 period     = "daily", 
                 col_rename = "Ra")
 options("scipen"=100, "digits"=4)
 

 RaReturn_daily
 RaReturn_daily %>%
    ggplot(aes(x = Ra, fill = symbol)) +
    geom_density(alpha = 0.5) +
    labs(title = " Charting the Daily Log Returns",
         x = "daily Returns", y = "Density") +
    theme_tq() +
    scale_fill_tq() + 
    facet_wrap(~ symbol, ncol = 2)

RaReturn_max<-Ra%>%
    tq_transmute(select     = adjusted, 
                 mutate_fun = apply.quarterly,
                 FUN=max, 
                 col_rename = "max.adjusted")

RaReturn_min<-Ra%>%
    tq_transmute(select     = adjusted, 
                 mutate_fun = apply.quarterly, 
                 FUN=min, 
                 col_rename = "min.adjusted")
 options("scipen"=100, "digits"=4)
 
 
Min_max<-left_join(RaReturn_max,RaReturn_min )
## Joining, by = c("symbol", "date")
Min_max
 Min_max %>%
    ggplot(aes(x = date, color = symbol)) +
    geom_segment(aes(xend = date, y = min.adjusted, yend = max.adjusted),
                 size = 1) +
    geom_point(aes(y = max.adjusted), size = 2) +
    geom_point(aes(y = min.adjusted), size = 2) +
    facet_wrap(~ symbol, ncol = 2, scale = "free_y") +
    labs(title = " Min/Max Price By Quarter",
         y = "Stock Price", color = "") +
    theme_tq() +
    scale_color_tq() +
    scale_y_continuous(labels = scales::dollar) +
    theme(axis.text.x = element_text(angle = 90, hjust = 1),
          axis.title.x = element_blank())

Ra <- c("MA", "V") %>%
    tq_get(get  = "stock.prices",
           from = "2015-01-01",
           to   = "2020-04-08") %>%
    group_by(symbol) 

Ra_pairs <- Ra %>%
    tq_transmute(select     = adjusted,
                 mutate_fun = periodReturn,
                 period     = "daily",
                 type       = "log",
                 col_rename = "returns") %>%
    spread(key = symbol, value = returns)
Ra_pairs
Ra_pairs %>%
    ggplot(aes(x = MA, y = V)) +
    geom_point(color = palette_light()[[1]], alpha = 0.5) +
    geom_smooth(method = "lm") +
    labs(title = "Visualizing Returns Relationship of Stock Pairs") +
    theme_tq()
## `geom_smooth()` using formula 'y ~ x'

lm(MA ~ V, data = Ra_pairs) %>%
    summary()
## 
## Call:
## lm(formula = MA ~ V, data = Ra_pairs)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.03712 -0.00355 -0.00008  0.00381  0.05234 
## 
## Coefficients:
##             Estimate Std. Error t value            Pr(>|t|)    
## (Intercept) 0.000153   0.000204    0.75                0.45    
## V           0.959891   0.012861   74.63 <0.0000000000000002 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.0074 on 1323 degrees of freedom
## Multiple R-squared:  0.808,  Adjusted R-squared:  0.808 
## F-statistic: 5.57e+03 on 1 and 1323 DF,  p-value: <0.0000000000000002
regr_fun <- function(data) {
    coef(lm(MA ~ V, data = timetk::tk_tbl(data, silent = TRUE)))
}

stock_pairs <- Ra_pairs %>%
         tq_mutate(mutate_fun = rollapply,
                   width      = 90,
                   FUN        = regr_fun,
                   by.column  = FALSE,
                   col_rename = c("coef.0", "coef.1"))
stock_pairs
stock_pairs %>%
    ggplot(aes(x = date, y = coef.1)) +
    geom_line(size = 1, color = palette_light()[[1]]) +
    geom_hline(yintercept = 0.9598, size = 1, color = palette_light()[[2]]) +
    labs(title = "MA ~ V: Visualizing Rolling Regression Coefficient", x = "") +
    theme_tq()
## Warning: Removed 89 row(s) containing missing values (geom_path).

Ra %>%
    tq_transmute(adjusted, 
                 periodReturn, 
                 period = "daily", 
                 type = "log", 
                 col_rename = "returns") %>%
    mutate(wealth.index = 100 * cumprod(1 + returns)) %>%
    ggplot(aes(x = date, y = wealth.index, color = symbol)) +
    geom_line(size = 1) +
    labs(title = "MA and V: Stock Prices") +
    theme_tq() + 
    scale_color_tq()

RaReturn<-Ra%>%
    tq_transmute(select     = adjusted, 
                 mutate_fun = periodReturn, 
                 period     = "yearly", 
                 col_rename = "Ra")
 options("scipen"=100, "digits"=4)
 

 RaReturn
Ra%>%
    group_by(symbol) %>%
    tq_transmute(adjusted, periodReturn, period = "daily") %>%
    tq_transmute(daily.returns, Return.clean, alpha = 0.05) %>%
    tq_transmute(daily.returns, Return.excess, Rf = 0.03 / 252)
GS<-getQuote("GS", from="2020-04-01", what = yahooQF(c("Market Capitalization", "Earnings/Share", 
         "P/E Ratio", "Book Value", "EBITDA", "52-week Low","52-week High" )))
#RaRb_capm %>% select(symbol, Alpha, Beta)
quandl_api_key("feCffvprJPn9gRsdAGCK")
#quandl_search(query = "Oil", database_code = "NSE", per_page = 3)
#AAPL<-Quandl.datatable('SHARADAR/SF1', dimension='MRY', ticker='AAPL')
#Quandl.datatable('SHARADAR/SF1', calendardate.gte='2013-12-31', ticker='AAPL')
tiingo_api_key('f5c376557f134a9a1f3bf02576124ba45b7be6d2')

# Tiingo Prices (Free alternative to Yahoo Finance!)
tq_get(c("AAPL", "GOOG"), get = "tiingo", from = "2010-01-01")
tq_get(c("AAPL", "GOOG"),
       get = "tiingo.iex",
       from   = "2020-01-01",
       to     = "2020-01-15",
       resample_frequency = "5min")
library(httr)
## Warning: package 'httr' was built under R version 3.6.3
library(jsonlite)
## Warning: package 'jsonlite' was built under R version 3.6.3
## 
## Attaching package: 'jsonlite'
## The following object is masked from 'package:purrr':
## 
##     flatten
ticker <- "AAPL"
apiKey <- "fgOZWUlhmZvcwxOJ2PYqaKaNA3zNrVJ2"
url <- paste("https://simfin.com/api/v1/info/find-id/ticker/",ticker,"?api-key=",apiKey,sep="")

get_data <- GET(url)

data <- fromJSON(content(get_data, "text"),flatten = TRUE)

simfinID <- data[,c("simId")]

statement <- "pl"
ptype <- "TTM"
fyear <- ""

url <- paste("https://simfin.com/api/v1/companies/id/",simfinID,"/statements/standardised","?api-key=",apiKey,
"&stype=",statement,"&ptype=",ptype,"&fyear=",fyear,
sep="")

get_data <- GET(url)

data <- fromJSON(content(get_data, "text"),flatten = TRUE)

print(data)
## $calculationScheme
##   period fyear restated sign
## 1     Q1  2020        1    1
## 2     FY  2019        1    1
## 3     Q1  2019        1   -1
## 
## $calculated
## [1] TRUE
## 
## $periodEndDate
## [1] "2019-12-31"
## 
## $dataQualityCheck
## [1] TRUE
## 
## $industryTemplate
## [1] "general"
## 
## $values
##    tid uid                            standardisedName parent_tid displayLevel
## 1    1   1                                     Revenue          4            0
## 2    3   0                    Sales & Services Revenue          1            1
## 3    5   0                           Financing Revenue          1            1
## 4    6   0                               Other Revenue          1            1
## 5    2   2                             Cost of revenue          4            0
## 6    7   0                    Cost of Goods & Services          2            1
## 7    8   0                   Cost of Financing Revenue          2            1
## 8    9   0                       Cost of Other Revenue          2            1
## 9    4   4                                Gross Profit         19            0
## 10  10  10                      Other Operating Income         19            0
## 11  11  11                          Operating Expenses         19            0
## 12  12  12           Selling, General & Administrative         11            1
## 13  13   0                         Selling & Marketing         12            2
## 14  14   0                    General & Administrative         12            2
## 15  15  15                      Research & Development         11            1
## 16  16  16                 Depreciation & Amortization         11            1
## 17  17  17             Provision For Doubtful Accounts         11            1
## 18  18  18                     Other Operating Expense         11            1
## 19  19  19                     Operating Income (Loss)         28            0
## 20  20  20                 Non-Operating Income (Loss)         28            0
## 21  21  21                       Interest Expense, net         20            1
## 22  22   0                            Interest Expense         21            2
## 23  23   0                             Interest Income         21            2
## 24  24   0              Other Investment Income (Loss)         20            1
## 25  25   0                Foreign Exchange Gain (Loss)         20            1
## 26  26  26               Income (Loss) from Affiliates         20            1
## 27  27  27           Other Non-Operating Income (Loss)         20            1
## 28  28  28              Pretax Income (Loss), Adjusted         43            0
## 29  29  29                     Abnormal Gains (Losses)         43            0
## 30  30   0                     Acquired In-Process R&D         29            1
## 31  31  31                Merger / Acquisition Expense         29            1
## 32  32  32                        Abnormal Derivatives         29            1
## 33  33  33                          Disposal of Assets         29            1
## 34  34  34                Early extinguishment of Debt         29            1
## 35  35  35                            Asset Write-Down         29            1
## 36  36  36        Impairment of Goodwill & Intangibles         29            1
## 37  37  37                            Sale of Business         29            1
## 38  38  38                            Legal Settlement         29            1
## 39  39  39                       Restructuring Charges         29            1
## 40  40   0          Sale of and Unrealized Investments         29            1
## 41  41   0                        Insurance Settlement         29            1
## 42  42  42                        Other Abnormal Items         29            1
## 43  43  43                        Pretax Income (Loss)         49            0
## 44  44  44           Income Tax (Expense) Benefit, net         49            0
## 45  45  45                          Current Income Tax         44            1
## 46  46  46                         Deferred Income Tax         44            1
## 47  47  47                        Tax Allowance/Credit         44            1
## 48  48  48 Income (Loss) from Affiliates, net of taxes         49            0
## 49  49  49    Income (Loss) from Continuing Operations         53            0
## 50  50  50            Net Extraordinary Gains (Losses)         53            0
## 51  51  51                     Discontinued Operations         50            1
## 52  52  52             XO & Accounting Charges & Other         50            1
## 53  53  53   Income (Loss) Including Minority Interest         55            0
## 54  54  54                           Minority Interest         55            0
## 55  55  55                                  Net Income         58            0
## 56  56  56                         Preferred Dividends         58            0
## 57  57  57                           Other Adjustments         58            0
## 58  58  58 Net Income Available to Common Shareholders          0            0
##    valueAssigned valueCalculated   valueChosen checkPossible
## 1   267683000000               0  267683000000         FALSE
## 2             NA               0            NA         FALSE
## 3             NA               0            NA         FALSE
## 4             NA               0            NA         FALSE
## 5  -166105000000               0 -166105000000         FALSE
## 6             NA               0            NA         FALSE
## 7             NA               0            NA         FALSE
## 8             NA               0            NA         FALSE
## 9   101578000000    101578000000  101578000000          TRUE
## 10            NA               0            NA         FALSE
## 11            NA    -35425000000  -35425000000         FALSE
## 12  -18659000000               0  -18659000000         FALSE
## 13            NA               0            NA         FALSE
## 14            NA               0            NA         FALSE
## 15  -16766000000               0  -16766000000         FALSE
## 16            NA               0            NA         FALSE
## 17            NA               0            NA         FALSE
## 18            NA               0            NA         FALSE
## 19   66153000000     66153000000   66153000000          TRUE
## 20            NA      1596000000    1596000000         FALSE
## 21            NA               0            NA         FALSE
## 22            NA               0            NA         FALSE
## 23            NA               0            NA         FALSE
## 24            NA               0            NA         FALSE
## 25            NA               0            NA         FALSE
## 26            NA               0            NA         FALSE
## 27    1596000000               0    1596000000         FALSE
## 28            NA     67749000000   67749000000         FALSE
## 29            NA               0            NA         FALSE
## 30            NA               0            NA         FALSE
## 31            NA               0            NA         FALSE
## 32            NA               0            NA         FALSE
## 33            NA               0            NA         FALSE
## 34            NA               0            NA         FALSE
## 35            NA               0            NA         FALSE
## 36            NA               0            NA         FALSE
## 37            NA               0            NA         FALSE
## 38            NA               0            NA         FALSE
## 39            NA               0            NA         FALSE
## 40            NA               0            NA         FALSE
## 41            NA               0            NA         FALSE
## 42            NA               0            NA         FALSE
## 43   67749000000     67749000000   67749000000          TRUE
## 44  -10222000000               0  -10222000000         FALSE
## 45            NA               0            NA         FALSE
## 46            NA               0            NA         FALSE
## 47            NA               0            NA         FALSE
## 48            NA               0            NA         FALSE
## 49            NA     57527000000   57527000000         FALSE
## 50            NA               0            NA         FALSE
## 51            NA               0            NA         FALSE
## 52            NA               0            NA         FALSE
## 53            NA     57527000000   57527000000         FALSE
## 54            NA               0            NA         FALSE
## 55   57527000000     57527000000   57527000000          TRUE
## 56            NA               0            NA         FALSE
## 57            NA               0            NA         FALSE
## 58            NA     57527000000   57527000000         FALSE
#https://www.macrotrends.net/stocks/charts/CCL/carnival/pe-ratio
#https://www.macrotrends.net/stocks/charts/CCL/carnival/pe-ratio
#tq_performance_fun_options