diff --git a/articles/TQ00-introduction-to-tidyquant.html b/articles/TQ00-introduction-to-tidyquant.html index 89b4ab1e..0e19e2c5 100644 --- a/articles/TQ00-introduction-to-tidyquant.html +++ b/articles/TQ00-introduction-to-tidyquant.html @@ -101,7 +101,7 @@

Matt Dancho

-

2023-09-29

+

2023-10-01

Source: vignettes/TQ00-introduction-to-tidyquant.Rmd
TQ00-introduction-to-tidyquant.Rmd
diff --git a/articles/TQ01-core-functions-in-tidyquant.html b/articles/TQ01-core-functions-in-tidyquant.html index ef7f3dd8..f6b1caf2 100644 --- a/articles/TQ01-core-functions-in-tidyquant.html +++ b/articles/TQ01-core-functions-in-tidyquant.html @@ -101,7 +101,7 @@

Matt Dancho

-

2023-09-29

+

2023-10-01

Source: vignettes/TQ01-core-functions-in-tidyquant.Rmd
TQ01-core-functions-in-tidyquant.Rmd
@@ -219,7 +219,7 @@

2.1 Yahoo! Finance
 aapl_prices  <- tq_get("AAPL", get = "stock.prices", from = " 1990-01-01")
 aapl_prices 
-
## # A tibble: 8,501 × 8
+
## # A tibble: 8,502 × 8
 ##    symbol date        open  high   low close    volume adjusted
 ##    <chr>  <date>     <dbl> <dbl> <dbl> <dbl>     <dbl>    <dbl>
 ##  1 AAPL   1990-01-02 0.315 0.335 0.312 0.333 183198400    0.264
@@ -232,7 +232,7 @@ 

2.1 Yahoo! Finance## 8 AAPL 1990-01-11 0.324 0.324 0.308 0.308 211052800 0.244 ## 9 AAPL 1990-01-12 0.306 0.310 0.301 0.308 171897600 0.244 ## 10 AAPL 1990-01-15 0.308 0.319 0.306 0.306 161739200 0.243 -## # ℹ 8,491 more rows

+## # ℹ 8,492 more rows

Yahoo Japan stock prices can be retrieved using a similar call, get = "stock.prices.japan".

diff --git a/articles/TQ02-quant-integrations-in-tidyquant.html b/articles/TQ02-quant-integrations-in-tidyquant.html
index cb30ce68..073fea6e 100644
--- a/articles/TQ02-quant-integrations-in-tidyquant.html
+++ b/articles/TQ02-quant-integrations-in-tidyquant.html
@@ -101,7 +101,7 @@ 
                         

Matt Dancho

-

2023-09-29

+

2023-10-01

Source:
vignettes/TQ02-quant-integrations-in-tidyquant.Rmd
TQ02-quant-integrations-in-tidyquant.Rmd
@@ -699,7 +699,7 @@

E ## 7 META 2013-07-31 0.479 0.0373 ## 8 META 2013-08-30 0.122 -0.0104 ## 9 META 2013-09-30 0.217 0.0253 -## 10 META 2013-10-31 -0.000398 0.0502 +## 10 META 2013-10-31 -0.000398 0.0503 ## # ℹ 182 more rows

The TTR::runCor function can be used to evaluate rolling correlations using the xy pattern. Looking at the documentation @@ -928,12 +928,12 @@

Example 6 ## ## Residuals: ## Min 1Q Median 3Q Max -## -0.0269572 -0.0039655 0.0002147 0.0039656 0.0289464 +## -0.0269576 -0.0039656 0.0002149 0.0039652 0.0289463 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 0.0001130 0.0003097 0.365 0.715 -## V 0.8133673 0.0226393 35.927 <2e-16 *** +## V 0.8133658 0.0226394 35.927 <2e-16 *** ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ## diff --git a/articles/TQ02-quant-integrations-in-tidyquant_files/figure-html/unnamed-chunk-20-1.png b/articles/TQ02-quant-integrations-in-tidyquant_files/figure-html/unnamed-chunk-20-1.png index 0f158348..a345c1d4 100644 Binary files a/articles/TQ02-quant-integrations-in-tidyquant_files/figure-html/unnamed-chunk-20-1.png and b/articles/TQ02-quant-integrations-in-tidyquant_files/figure-html/unnamed-chunk-20-1.png differ diff --git a/articles/TQ02-quant-integrations-in-tidyquant_files/figure-html/unnamed-chunk-27-1.png b/articles/TQ02-quant-integrations-in-tidyquant_files/figure-html/unnamed-chunk-27-1.png index 31b2b958..8ccfaeeb 100644 Binary files a/articles/TQ02-quant-integrations-in-tidyquant_files/figure-html/unnamed-chunk-27-1.png and b/articles/TQ02-quant-integrations-in-tidyquant_files/figure-html/unnamed-chunk-27-1.png differ diff --git a/articles/TQ02-quant-integrations-in-tidyquant_files/figure-html/unnamed-chunk-31-1.png b/articles/TQ02-quant-integrations-in-tidyquant_files/figure-html/unnamed-chunk-31-1.png index cd9e6c3a..5043a4d0 100644 Binary files a/articles/TQ02-quant-integrations-in-tidyquant_files/figure-html/unnamed-chunk-31-1.png and b/articles/TQ02-quant-integrations-in-tidyquant_files/figure-html/unnamed-chunk-31-1.png differ diff --git a/articles/TQ02-quant-integrations-in-tidyquant_files/figure-html/unnamed-chunk-32-1.png b/articles/TQ02-quant-integrations-in-tidyquant_files/figure-html/unnamed-chunk-32-1.png index 4138c92b..21649a33 100644 Binary files a/articles/TQ02-quant-integrations-in-tidyquant_files/figure-html/unnamed-chunk-32-1.png and b/articles/TQ02-quant-integrations-in-tidyquant_files/figure-html/unnamed-chunk-32-1.png differ diff --git a/articles/TQ03-scaling-and-modeling-with-tidyquant.html b/articles/TQ03-scaling-and-modeling-with-tidyquant.html index cc007e56..83447365 100644 --- a/articles/TQ03-scaling-and-modeling-with-tidyquant.html +++ b/articles/TQ03-scaling-and-modeling-with-tidyquant.html @@ -101,7 +101,7 @@

Matt Dancho

-

2023-09-29

+

2023-10-01

Source: vignettes/TQ03-scaling-and-modeling-with-tidyquant.Rmd
TQ03-scaling-and-modeling-with-tidyquant.Rmd
@@ -259,7 +259,7 @@

Method 2B: Use index or exchangetq_index("DOW") %>% slice(1:3) %>% tq_get(get = "stock.prices")

-
## # A tibble: 8,112 × 15
+
## # A tibble: 8,115 × 15
 ##    symbol company      identifier sedol weight sector shares_held local_currency
 ##    <chr>  <chr>        <chr>      <chr>  <dbl> <chr>        <dbl> <chr>         
 ##  1 UNH    UNITEDHEALT… 91324P102  2917… 0.0996 -          5477820 USD           
@@ -272,7 +272,7 @@ 

Method 2B: Use index or exchange## 8 UNH UNITEDHEALT… 91324P102 2917… 0.0996 - 5477820 USD ## 9 UNH UNITEDHEALT… 91324P102 2917… 0.0996 - 5477820 USD ## 10 UNH UNITEDHEALT… 91324P102 2917… 0.0996 - 5477820 USD -## # ℹ 8,102 more rows +## # ℹ 8,105 more rows ## # ℹ 7 more variables: date <date>, open <dbl>, high <dbl>, low <dbl>, ## # close <dbl>, volume <dbl>, adjusted <dbl>

You can use any applicable “getter” to get data for every @@ -429,7 +429,7 @@

Analyze a Single Stock## ## Coefficients: ## (Intercept) year(date) -## 58.86281 -0.02915

+## 58.86280 -0.02915

We can utilize the broom package to get “tidy” data from the model. There’s three primary functions:

    @@ -588,7 +588,7 @@

    Bad Apples Fail Gracefully, tq_get## ! x = 'BAD APPLE', get = 'stock.prices': Error in getSymbols.yahoo(Symbols = "BAD APPLE", env = <environment>, : Unable to import "BAD APPLE". ## URL using bad/illegal format or missing URL ## Removing BAD APPLE. -
    ## # A tibble: 5,408 × 8
    +
    ## # A tibble: 5,410 × 8
     ##    symbol date        open  high   low close    volume adjusted
     ##    <chr>  <date>     <dbl> <dbl> <dbl> <dbl>     <dbl>    <dbl>
     ##  1 AAPL   2013-01-02  19.8  19.8  19.3  19.6 560518000     16.8
    @@ -601,7 +601,7 @@ 

    Bad Apples Fail Gracefully, tq_get## 8 AAPL 2013-01-11 18.6 18.8 18.5 18.6 350506800 15.9 ## 9 AAPL 2013-01-14 18.0 18.1 17.8 17.9 734207600 15.3 ## 10 AAPL 2013-01-15 17.8 17.8 17.3 17.4 876772400 14.9 -## # ℹ 5,398 more rows

    +## # ℹ 5,400 more rows

    Now switching complete_cases = FALSE will retain any errors as NA values in a nested data frame. Notice that the error message and output change. The error message now states that the @@ -615,7 +615,7 @@

    Bad Apples Fail Gracefully, tq_get## Caused by warning: ## ! x = 'BAD APPLE', get = 'stock.prices': Error in getSymbols.yahoo(Symbols = "BAD APPLE", env = <environment>, : Unable to import "BAD APPLE". ## URL using bad/illegal format or missing URL -
    ## # A tibble: 5,409 × 8
    +
    ## # A tibble: 5,411 × 8
     ##    symbol date        open  high   low close    volume adjusted
     ##    <chr>  <date>     <dbl> <dbl> <dbl> <dbl>     <dbl>    <dbl>
     ##  1 AAPL   2013-01-02  19.8  19.8  19.3  19.6 560518000     16.8
    @@ -628,7 +628,7 @@ 

    Bad Apples Fail Gracefully, tq_get## 8 AAPL 2013-01-11 18.6 18.8 18.5 18.6 350506800 15.9 ## 9 AAPL 2013-01-14 18.0 18.1 17.8 17.9 734207600 15.3 ## 10 AAPL 2013-01-15 17.8 17.8 17.3 17.4 876772400 14.9 -## # ℹ 5,399 more rows

    +## # ℹ 5,401 more rows

    In both cases, the prudent user will review the warnings to determine what happened and whether or not this is acceptable. In the complete_cases = FALSE example, if the user attempts to diff --git a/articles/TQ03-scaling-and-modeling-with-tidyquant_files/figure-html/unnamed-chunk-15-1.png b/articles/TQ03-scaling-and-modeling-with-tidyquant_files/figure-html/unnamed-chunk-15-1.png index 059eb055..0e32484b 100644 Binary files a/articles/TQ03-scaling-and-modeling-with-tidyquant_files/figure-html/unnamed-chunk-15-1.png and b/articles/TQ03-scaling-and-modeling-with-tidyquant_files/figure-html/unnamed-chunk-15-1.png differ diff --git a/articles/TQ04-charting-with-tidyquant.html b/articles/TQ04-charting-with-tidyquant.html index f3cec43f..5d74595a 100644 --- a/articles/TQ04-charting-with-tidyquant.html +++ b/articles/TQ04-charting-with-tidyquant.html @@ -101,7 +101,7 @@

    Matt Dancho

    -

    2023-09-29

    +

    2023-10-01

    Source:
    vignettes/TQ04-charting-with-tidyquant.Rmd
    TQ04-charting-with-tidyquant.Rmd
    diff --git a/articles/TQ04-charting-with-tidyquant_files/figure-html/unnamed-chunk-23-1.png b/articles/TQ04-charting-with-tidyquant_files/figure-html/unnamed-chunk-23-1.png index 997f8d83..cdb82d35 100644 Binary files a/articles/TQ04-charting-with-tidyquant_files/figure-html/unnamed-chunk-23-1.png and b/articles/TQ04-charting-with-tidyquant_files/figure-html/unnamed-chunk-23-1.png differ diff --git a/articles/TQ05-performance-analysis-with-tidyquant.html b/articles/TQ05-performance-analysis-with-tidyquant.html index c99eb560..cc62b2c5 100644 --- a/articles/TQ05-performance-analysis-with-tidyquant.html +++ b/articles/TQ05-performance-analysis-with-tidyquant.html @@ -101,7 +101,7 @@

    Matt Dancho

    -

    2023-09-29

    +

    2023-10-01

    Source: vignettes/TQ05-performance-analysis-with-tidyquant.Rmd
    TQ05-performance-analysis-with-tidyquant.Rmd
    diff --git a/articles/TQ05-performance-analysis-with-tidyquant_files/figure-html/unnamed-chunk-44-1.png b/articles/TQ05-performance-analysis-with-tidyquant_files/figure-html/unnamed-chunk-44-1.png index 2263a96c..e8f9b9d7 100644 Binary files a/articles/TQ05-performance-analysis-with-tidyquant_files/figure-html/unnamed-chunk-44-1.png and b/articles/TQ05-performance-analysis-with-tidyquant_files/figure-html/unnamed-chunk-44-1.png differ diff --git a/articles/TQ05-performance-analysis-with-tidyquant_files/figure-html/unnamed-chunk-46-1.png b/articles/TQ05-performance-analysis-with-tidyquant_files/figure-html/unnamed-chunk-46-1.png index dec8a315..8f8265ac 100644 Binary files a/articles/TQ05-performance-analysis-with-tidyquant_files/figure-html/unnamed-chunk-46-1.png and b/articles/TQ05-performance-analysis-with-tidyquant_files/figure-html/unnamed-chunk-46-1.png differ diff --git a/articles/TQ05-performance-analysis-with-tidyquant_files/figure-html/unnamed-chunk-48-1.png b/articles/TQ05-performance-analysis-with-tidyquant_files/figure-html/unnamed-chunk-48-1.png index 86abd8f0..eb51e9ad 100644 Binary files a/articles/TQ05-performance-analysis-with-tidyquant_files/figure-html/unnamed-chunk-48-1.png and b/articles/TQ05-performance-analysis-with-tidyquant_files/figure-html/unnamed-chunk-48-1.png differ diff --git a/pkgdown.yml b/pkgdown.yml index 47d17d44..4896b5a8 100644 --- a/pkgdown.yml +++ b/pkgdown.yml @@ -9,5 +9,5 @@ articles: TQ04-charting-with-tidyquant: TQ04-charting-with-tidyquant.html TQ05-performance-analysis-with-tidyquant: TQ05-performance-analysis-with-tidyquant.html TQ06-excel-in-r: TQ06-excel-in-r.html -last_built: 2023-09-29T20:45Z +last_built: 2023-10-01T00:11Z diff --git a/reference/coord_x_date-1.png b/reference/coord_x_date-1.png index f7c0b1e6..ed520975 100644 Binary files a/reference/coord_x_date-1.png and b/reference/coord_x_date-1.png differ diff --git a/reference/excel_date_functions.html b/reference/excel_date_functions.html index ab6ca143..aa01e6a3 100644 --- a/reference/excel_date_functions.html +++ b/reference/excel_date_functions.html @@ -384,9 +384,9 @@

    Examples # Current Date-Time --- NOW() -#> [1] "2023-09-29 20:45:11 UTC" +#> [1] "2023-10-01 00:11:35 UTC" TODAY() -#> [1] "2023-09-29" +#> [1] "2023-10-01" # Date Math --- EOMONTH("2020-01-01") diff --git a/reference/scale_manual-1.png b/reference/scale_manual-1.png index b56b370e..8f00484d 100644 Binary files a/reference/scale_manual-1.png and b/reference/scale_manual-1.png differ diff --git a/search.json b/search.json index 32bbbb62..5343409c 100644 --- a/search.json +++ b/search.json @@ -1 +1 @@ -[{"path":"/articles/TQ00-introduction-to-tidyquant.html","id":"minutes-to-tidyquant","dir":"Articles","previous_headings":"","what":"2-Minutes To Tidyquant","title":"Introduction to tidyquant","text":"short introduction tidyquant YouTube. Check entire Software Intro Series YouTube!","code":""},{"path":"/articles/TQ00-introduction-to-tidyquant.html","id":"benefits","dir":"Articles","previous_headings":"","what":"Benefits","title":"Introduction to tidyquant","text":"core functions lot power Integrates quantitative analysis functionality zoo, xts, quantmod, TTR, PerformanceAnalytics Designed modeling scaling analyses using tidyverse tools R Data Science Implements ggplot2 functionality beautiful meaningful financial visualizations User-friendly documentation get speed quickly!","code":""},{"path":"/articles/TQ00-introduction-to-tidyquant.html","id":"a-few-core-functions-with-a-lot-of-power","dir":"Articles","previous_headings":"Benefits","what":"A Few Core Functions with A Lot of Power","title":"Introduction to tidyquant","text":"Minimizing number functions reduces learning curve. ’ve done group core functions four categories: Get Stock Index, tq_index(), Stock Exchange, tq_exchange(): Returns stock symbols various attributes every stock index exchange. Eighteen indexes three exchanges available. Get Quantitative Data, tq_get(): one-stop shop get data various web-sources. Transmute, tq_transmute(), Mutate, tq_mutate(), Quantitative Data: Perform scale financial calculations completely within tidyverse. workhorse functions integrate xts, zoo, quantmod, TTR, PerformanceAnalytics packages. Performance analysis, tq_performance(), portfolio aggregation, tq_portfolio(): PerformanceAnalytics integration enables analyzing performance assets portfolios. Refer Performance Analysis tidyquant. information, refer first topic-specific vignette, Core Functions tidyquant.","code":""},{"path":"/articles/TQ00-introduction-to-tidyquant.html","id":"integrates-the-quantitative-analysis-functionality-of-xtszoo-quantmod-ttr-and-performance-analytics","dir":"Articles","previous_headings":"Benefits","what":"Integrates the Quantitative Analysis Functionality of xts/zoo, quantmod TTR and Performance Analytics","title":"Introduction to tidyquant","text":"’s wide range useful quantitative analysis functions (QAF) work time-series objects. problem many wonderful functions don’t work data frames tidyverse workflow. now. tidyquant package integrates useful functions xts, zoo, quantmod, TTR, PerformanceAnalytics packages, enabling seamless usage within tidyverse workflow. Refer information performance analysis portfolio attribution PerformanceAnalytics integration. information, refer second topic-specific vignette, R Quantitative Analysis Package Integrations tidyquant.","code":""},{"path":"/articles/TQ00-introduction-to-tidyquant.html","id":"designed-for-the-data-science-workflow-of-the-tidyverse","dir":"Articles","previous_headings":"Benefits","what":"Designed for the data science workflow of the tidyverse","title":"Introduction to tidyquant","text":"greatest benefit tidyquant ability easily model scale financial analysis. Scaling process creating analysis one security extending multiple groups. idea scaling incredibly useful financial analysts typically one wants compare many securities make informed decisions. Fortunately, tidyquant package integrates tidyverse making scaling super simple! tidyquant functions return data tibble (tidy data frame) format, allows interaction within tidyverse. means can: Seamlessly scale data retrieval mutations Use pipe (%>%) chaining operations Use dplyr tidyr: select, filter, group_by, nest/unnest, spread/gather, etc Use purrr: mapping functions map information, refer third topic-specific vignette, Scaling Modeling tidyquant.","code":""},{"path":"/articles/TQ00-introduction-to-tidyquant.html","id":"implements-ggplot2-functionality-for-financial-visualizations","dir":"Articles","previous_headings":"Benefits","what":"Implements ggplot2 Functionality for Financial Visualizations","title":"Introduction to tidyquant","text":"tidyquant package includes charting tools assist users developing quick visualizations ggplot2 using grammar graphics format workflow. information, refer fourth topic-specific vignette, Charting tidyquant.","code":""},{"path":"/articles/TQ00-introduction-to-tidyquant.html","id":"performance-analysis-of-asset-and-portfolio-returns","dir":"Articles","previous_headings":"Benefits","what":"Performance Analysis of Asset and Portfolio Returns","title":"Introduction to tidyquant","text":"Asset portfolio performance analysis deep field wide range theories methods analyzing risk versus reward. PerformanceAnalytics package consolidates many widely used performance metrics functions can applied stock portfolio returns. tidquant implements functionality two primary functions: tq_performance implements performance analysis functions tidy way, enabling scaling analysis using split, apply, combine framework. tq_portfolio provides useful toolset aggregating group individual asset returns one many portfolios. Performance based statistical properties returns, result functions use returns opposed stock prices. information, refer fifth topic-specific vignette, Performance Analysis tidyquant.","code":""},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"overview","dir":"Articles","previous_headings":"","what":"Overview","title":"Core Functions in tidyquant","text":"tidyquant package core functions lot power. functions means less learning curve user, handful functions user needs learn perform vast majority financial analysis tasks. main functions : Get Stock Index, tq_index(), Stock Exchange, tq_exchange(): Returns stock symbols various attributes every stock index exchange. Eighteen indexes three exchanges available. Get Quantitative Data, tq_get(): one-stop shop get data various web-sources. Transmute, tq_transmute(), Mutate, tq_mutate(), Quantitative Data: Perform scale financial calculations completely within tidyverse. workhorse functions integrate xts, zoo, quantmod, TTR packages. Performance analysis, tq_performance(), portfolio aggregation, tq_portfolio(): PerformanceAnalytics integration enables analyzing performance assets portfolios. breadth topic, refer Performance Analysis tidyquant tutorial functions.","code":""},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"prerequisites","dir":"Articles","previous_headings":"","what":"Prerequisites","title":"Core Functions in tidyquant","text":"Load tidyquant package get started.","code":"# Loads tidyquant, lubridate, xts, quantmod, TTR library(dplyr) library(tidyquant)"},{"path":[]},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"stock-indexes","dir":"Articles","previous_headings":"1.0 Retrieve Consolidated Symbol Data","what":"1.1 Stock Indexes","title":"Core Functions in tidyquant","text":"wide range stock index / exchange lists can retrieved using tq_index(). get full list options, use tq_index_options(). Set x one options list options get desired stock index / exchange. data source State Street Global Advisors - US SPDRS ETFs.","code":"tq_index_options() ## [1] \"DOW\" \"DOWGLOBAL\" \"SP400\" \"SP500\" \"SP600\" tq_index(\"SP500\")"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"stock-exchanges","dir":"Articles","previous_headings":"1.0 Retrieve Consolidated Symbol Data","what":"1.2 Stock Exchanges","title":"Core Functions in tidyquant","text":"Stock lists three stock exchanges available: NASDAQ, NYSE, AMEX. forget, just use tq_exchange_options(). can easily get full list stocks NASDAQ exchange.","code":"tq_exchange(\"NASDAQ\")"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"get-quantitative-data","dir":"Articles","previous_headings":"","what":"1.0 Get Quantitative Data","title":"Core Functions in tidyquant","text":"tq_get() function used collect data changing get argument. data sources: Yahoo Finance - Daily stock data FRED - Economic data Quandl - Economic, Energy, & Financial Data API Tiingo - Financial API sub-daily stock data crypto-currency Alpha Vantage - Financial API sub-daily, ForEx, crypto-currency data Bloomberg - Financial API. Paid account required. Use tq_get_options() see full list.","code":"tq_get_options() ## [1] \"stock.prices\" \"stock.prices.japan\" \"dividends\" ## [4] \"splits\" \"economic.data\" \"quandl\" ## [7] \"quandl.datatable\" \"tiingo\" \"tiingo.iex\" ## [10] \"tiingo.crypto\" \"alphavantager\" \"alphavantage\" ## [13] \"rblpapi\""},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"yahoo-finance","dir":"Articles","previous_headings":"1.0 Get Quantitative Data","what":"2.1 Yahoo! Finance","title":"Core Functions in tidyquant","text":"stock prices can retrieved succinctly using get = \"stock.prices\". returns stock price data Yahoo Finance. Yahoo Japan stock prices can retrieved using similar call, get = \"stock.prices.japan\". data source Yahoo Finance (https://finance.yahoo.com/) Yahoo Finance Japan (https://finance.yahoo.co.jp/).","code":"aapl_prices <- tq_get(\"AAPL\", get = \"stock.prices\", from = \" 1990-01-01\") aapl_prices ## # A tibble: 8,501 × 8 ## symbol date open high low close volume adjusted ## ## 1 AAPL 1990-01-02 0.315 0.335 0.312 0.333 183198400 0.264 ## 2 AAPL 1990-01-03 0.339 0.339 0.335 0.335 207995200 0.266 ## 3 AAPL 1990-01-04 0.342 0.346 0.333 0.336 221513600 0.266 ## 4 AAPL 1990-01-05 0.337 0.342 0.330 0.337 123312000 0.267 ## 5 AAPL 1990-01-08 0.335 0.339 0.330 0.339 101572800 0.269 ## 6 AAPL 1990-01-09 0.339 0.339 0.330 0.336 86139200 0.266 ## 7 AAPL 1990-01-10 0.336 0.336 0.319 0.321 199718400 0.255 ## 8 AAPL 1990-01-11 0.324 0.324 0.308 0.308 211052800 0.244 ## 9 AAPL 1990-01-12 0.306 0.310 0.301 0.308 171897600 0.244 ## 10 AAPL 1990-01-15 0.308 0.319 0.306 0.306 161739200 0.243 ## # ℹ 8,491 more rows x8411T <- tq_get(\"8411.T\", get = \"stock.prices.japan\", from = \"2016-01-01\", to = \"2016-12-31\")"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"fred-economic-data","dir":"Articles","previous_headings":"1.0 Get Quantitative Data","what":"2.2 FRED Economic Data","title":"Core Functions in tidyquant","text":"wealth economic data can extracted Federal Reserve Economic Data (FRED) database. FRED contains 10K data sets free use. See FRED categories narrow data base get data codes. WTI Crude Oil Prices shown .","code":"wti_price_usd <- tq_get(\"DCOILWTICO\", get = \"economic.data\") wti_price_usd ## # A tibble: 2,800 × 3 ## symbol date price ## ## 1 DCOILWTICO 2013-01-01 NA ## 2 DCOILWTICO 2013-01-02 93.1 ## 3 DCOILWTICO 2013-01-03 93.0 ## 4 DCOILWTICO 2013-01-04 93.1 ## 5 DCOILWTICO 2013-01-07 93.2 ## 6 DCOILWTICO 2013-01-08 93.2 ## 7 DCOILWTICO 2013-01-09 93.1 ## 8 DCOILWTICO 2013-01-10 93.8 ## 9 DCOILWTICO 2013-01-11 93.6 ## 10 DCOILWTICO 2013-01-14 94.3 ## # ℹ 2,790 more rows"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"nasdaq-data-link-quandl-api","dir":"Articles","previous_headings":"1.0 Get Quantitative Data","what":"2.3 Nasdaq Data Link (Quandl) API","title":"Core Functions in tidyquant","text":"Quandl provides access vast number financial economic databases. Quandl packages must installed separately.","code":"install.packages(\"Quandl\")"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"authentication","dir":"Articles","previous_headings":"1.0 Get Quantitative Data > 2.3 Nasdaq Data Link (Quandl) API","what":"Authentication","title":"Core Functions in tidyquant","text":"make full use integration recommend set api key. create sign Quandl account go account api key page.","code":"quandl_api_key(\"\")"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"search","dir":"Articles","previous_headings":"1.0 Get Quantitative Data > 2.3 Nasdaq Data Link (Quandl) API","what":"Search","title":"Core Functions in tidyquant","text":"Searching Quandl within R console possible quandl_search(), wrapper Quandl::Quandl.search(). example search shown . required argument query. can also visit Quandl Search webpage search available database codes.","code":"quandl_search(query = \"Oil\", database_code = \"NSE\", per_page = 3)"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"getting-quandl-data","dir":"Articles","previous_headings":"1.0 Get Quantitative Data > 2.3 Nasdaq Data Link (Quandl) API","what":"Getting Quandl Data","title":"Core Functions in tidyquant","text":"Getting data integrated tq_get(). Two get options exist retrieve Quandl data: get = \"quandl\": Get’s Quandl time series data. wrapper Quandl(). get = \"quandl.datatable\": Gets Quandl datatables (larger data sets may time series). wrapper Quandl.datatable(). Getting data Quandl can achieved much way “get” options. Just pass “codes” data along desired arguments underlying function. following uses get = \"quandl\" “WIKI” database download daily stock prices AAPL 2016. output tidy data frame. following time series options available passed underlying Quandl() function: start_date () = “yyyy-mm-dd” | end_date () = “yyyy-mm-dd” column_index = numeric column number (e.g. 1) rows = numeric row number indicating first n rows (e.g. 100) collapse = “none”, “daily”, “weekly”, “monthly”, “quarterly”, “annual” transform = “none”, “diff”, “rdiff”, “cumul”, “normalize” ’s example get period returns adj.close (column index 11) using column_index, collapse transform arguments. Datatables larger data sets. can downloaded using get = \"quandl.datatable\". Note time series arguments work data tables. ’s several examples Zacks Fundamentals Collection B","code":"c(\"WIKI/AAPL\") %>% tq_get(get = \"quandl\", from = \"2016-01-01\", to = \"2016-12-31\") \"WIKI/AAPL\" %>% tq_get(get = \"quandl\", from = \"2007-01-01\", to = \"2016-12-31\", column_index = 11, collapse = \"annual\", transform = \"rdiff\") # Zacks Fundamentals Collection B (DOW 30 Available to non subscribers) tq_get(\"ZACKS/FC\", get = \"quandl.datatable\") # Zacks Fundamentals Condensed tq_get(\"ZACKS/FR\", get = \"quandl.datatable\") # Zacks Fundamental Ratios tq_get(\"ZACKS/MT\", get = \"quandl.datatable\") # Zacks Master Table tq_get(\"ZACKS/MKTV\", get = \"quandl.datatable\") # Zacks Market Value Supplement tq_get(\"ZACKS/SHRS\", get = \"quandl.datatable\") # Zacks Shares Out Supplement"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"tiingo-api","dir":"Articles","previous_headings":"1.0 Get Quantitative Data","what":"2.4 Tiingo API","title":"Core Functions in tidyquant","text":"Tiingo API free source stock prices, cryptocurrencies, intraday feeds IEX (Investors Exchange). can serve alternate source data Yahoo! Finance.","code":""},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"authentication-1","dir":"Articles","previous_headings":"1.0 Get Quantitative Data > 2.4 Tiingo API","what":"Authentication","title":"Core Functions in tidyquant","text":"make full use integration need get API key set api key. don’t one already, go Tiingo account get FREE API key. can set follows:","code":"tiingo_api_key('')"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"getting-tiingo-data","dir":"Articles","previous_headings":"1.0 Get Quantitative Data > 2.4 Tiingo API","what":"Getting Tiingo Data","title":"Core Functions in tidyquant","text":"tidyquant package provides convenient wrappers riingo package (R interface Tiingo). ’s tq_get() maps riingo: Tiingo Prices: tq_get(get = \"tiingo\") = riingo::riingo_prices() Tiingo IEX Data: tq_get(get = \"tiingo.iex\") = riingo::riingo_iex_prices() Tiingo Crypto Data: tq_get(get = \"tiingo.crypto\") = riingo::riingo_crypto_prices()","code":"# Tiingo Prices (Free alternative to Yahoo Finance!) tq_get(c(\"AAPL\", \"GOOG\"), get = \"tiingo\", from = \"2010-01-01\") # Sub-daily prices from IEX ---- tq_get(c(\"AAPL\", \"GOOG\"), get = \"tiingo.iex\", from = \"2020-01-01\", to = \"2020-01-15\", resample_frequency = \"5min\") # Tiingo Bitcoin in USD ---- tq_get(c(\"btcusd\"), get = \"tiingo.crypto\", from = \"2020-01-01\", to = \"2020-01-15\", resample_frequency = \"5min\")"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"alpha-vantage-api","dir":"Articles","previous_headings":"1.0 Get Quantitative Data","what":"2.5 Alpha Vantage API","title":"Core Functions in tidyquant","text":"Alpha Vantage provides access real-time historical financial data. alphavantager package, lightweight R interface, integrated tidyquant follows. benefit integration scalability since can now get multiple symbols returned tidy format. need install first.","code":"install.packages(\"alphavantager\")"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"authentication-2","dir":"Articles","previous_headings":"1.0 Get Quantitative Data > 2.5 Alpha Vantage API","what":"Authentication","title":"Core Functions in tidyquant","text":"make full use integration need get API key set api key. don’t one already, go Alpha Vantage account get FREE API key. can set follows:","code":"# install.packages(\"alphavantager\") av_api_key(\"\")"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"getting-alpha-vantage-data","dir":"Articles","previous_headings":"1.0 Get Quantitative Data > 2.5 Alpha Vantage API","what":"Getting Alpha Vantage Data","title":"Core Functions in tidyquant","text":"Getting data simple structure follows Alpha Vantage API documentation. example, wish retrieve intraday data 5 minute intervals META MSFT, can build parameters x = c(\"META\", \"MSFT\"), get = \"alphavantager\", av_fun = \"TIME_SERIES_INTRADAY\", interval = \"5min\". familiar x get always use. av_fun argument comes alphavantager::av_get() Alpha Vantage documentation. interval argument comes docs well.","code":"# Scaling is as simple as supplying multiple symbols c(\"META\", \"MSFT\") %>% tq_get(get = \"alphavantage\", av_fun = \"TIME_SERIES_INTRADAY\", interval = \"5min\")"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"bloomberg","dir":"Articles","previous_headings":"1.0 Get Quantitative Data","what":"2.6 Bloomberg","title":"Core Functions in tidyquant","text":"Bloomberg provides access arguably comprehensive financial data actively used major financial instutions work financial data. Rblpapi package, R interface Bloomberg, integrated tidyquant follows. benefit integration scalability since can now get multiple symbols returned tidy format.","code":""},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"authentication-3","dir":"Articles","previous_headings":"1.0 Get Quantitative Data > 2.6 Bloomberg","what":"Authentication","title":"Core Functions in tidyquant","text":"make full use integration need Bloomberg Terminal account (Note free service). Bloomberg Terminal running machine, can connect follows:","code":"# install.packages(\"Rblpapi\") Rblpapi::blpConnect()"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"getting-bloomberg-data","dir":"Articles","previous_headings":"1.0 Get Quantitative Data > 2.6 Bloomberg","what":"Getting Bloomberg Data","title":"Core Functions in tidyquant","text":"Getting data simple structure follows Rblpapi API documentation. example, wish retrieve monthly data SPX Index AGTHX Equity, can build tq_get parameters follows: x = c('SPX Index','ODMAX Equity') get = \"rblpapi\" rblpapi_fun = \"bdh\" Note “bdh” default, options include “bdh” (Bloomberg Data History), “bds” (Bloomberg Data Set), “bdp” (Bloomberg Data Point) / get passed start.date end.date can provided “YYYY-MM-DD” character format. Note start.date end.date Rblpapi can used must converted date datetime. arguments: options depend rblpapi_fun. See Rblpapi documentation.","code":"# Get Bloomberg data in a tidy data frame my_bloomberg_data <- c('SPX Index','ODMAX Equity') %>% tq_get(get = \"Rblpapi\", rblpapi_fun = \"bdh\", fields = c(\"PX_LAST\"), options = c(\"periodicitySelection\" = \"WEEKLY\"), from = \"2016-01-01\", to = \"2016-12-31\")"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"mutate-quantitative-data","dir":"Articles","previous_headings":"","what":"3.0 Mutate Quantitative Data","title":"Core Functions in tidyquant","text":"Mutating functions enable xts/zoo, quantmod TTR functions shine. ’ll touch mutation functions briefly using FANG data set, consists daily prices META, AMZN, GOOG, NFLX beginning 2013 end 2016. ’ll apply functions grouped data sets get feel works detailed walkthrough compatible functions, see next vignette series, R Quantitative Analysis Package Integrations tidyquant.","code":"FANG ## # A tibble: 4,032 × 8 ## symbol date open high low close volume adjusted ## ## 1 META 2013-01-02 27.4 28.2 27.4 28 69846400 28 ## 2 META 2013-01-03 27.9 28.5 27.6 27.8 63140600 27.8 ## 3 META 2013-01-04 28.0 28.9 27.8 28.8 72715400 28.8 ## 4 META 2013-01-07 28.7 29.8 28.6 29.4 83781800 29.4 ## 5 META 2013-01-08 29.5 29.6 28.9 29.1 45871300 29.1 ## 6 META 2013-01-09 29.7 30.6 29.5 30.6 104787700 30.6 ## 7 META 2013-01-10 30.6 31.5 30.3 31.3 95316400 31.3 ## 8 META 2013-01-11 31.3 32.0 31.1 31.7 89598000 31.7 ## 9 META 2013-01-14 32.1 32.2 30.6 31.0 98892800 31.0 ## 10 META 2013-01-15 30.6 31.7 29.9 30.1 173242600 30.1 ## # ℹ 4,022 more rows"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"transmute-quantitative-data-tq_transmute","dir":"Articles","previous_headings":"3.0 Mutate Quantitative Data","what":"3.1 Transmute Quantitative Data, tq_transmute","title":"Core Functions in tidyquant","text":"Transmute results tq_get(). Transmute holds almost meaning dplyr, newly created columns returned, tq_transmute(), number rows returned can different original data frame. important changing periodicity. example periodicity aggregation daily monthly. Let’s go happened. select allows easily choose columns get passed mutate_fun. example , adjusted selects “adjusted” column data, sends mutate function, .monthly, mutates periodicity daily monthly. Additional arguments can passed mutate_fun way .... passing indexAt argument return date matches first date period.","code":"FANG %>% group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = to.monthly, indexAt = \"lastof\") ## # A tibble: 192 × 3 ## # Groups: symbol [4] ## symbol date adjusted ## ## 1 META 2013-01-31 31.0 ## 2 META 2013-02-28 27.2 ## 3 META 2013-03-31 25.6 ## 4 META 2013-04-30 27.8 ## 5 META 2013-05-31 24.4 ## 6 META 2013-06-30 24.9 ## 7 META 2013-07-31 36.8 ## 8 META 2013-08-31 41.3 ## 9 META 2013-09-30 50.2 ## 10 META 2013-10-31 50.2 ## # ℹ 182 more rows"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"working-with-non-ohlc-data","dir":"Articles","previous_headings":"3.0 Mutate Quantitative Data > 3.1 Transmute Quantitative Data, tq_transmute","what":"Working with non-OHLC data","title":"Core Functions in tidyquant","text":"Returns FRED, Oanda, sources open, high, low, close (OHLC) format. However, problem select. following example shows transmute WTI Crude daily prices monthly prices. Since single column pass, can leave select argument NULL selects columns default. sends price column .period mutate function.","code":"wti_prices <- tq_get(\"DCOILWTICO\", get = \"economic.data\") wti_prices %>% tq_transmute(mutate_fun = to.period, period = \"months\", col_rename = \"WTI Price\") ## # A tibble: 129 × 2 ## date `WTI Price` ## ## 1 2013-01-31 97.6 ## 2 2013-02-28 92.0 ## 3 2013-03-28 97.2 ## 4 2013-04-30 93.2 ## 5 2013-05-31 91.9 ## 6 2013-06-28 96.4 ## 7 2013-07-31 105. ## 8 2013-08-30 108. ## 9 2013-09-30 102. ## 10 2013-10-31 96.3 ## # ℹ 119 more rows"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"mutate-quantitative-data-tq_mutate","dir":"Articles","previous_headings":"3.0 Mutate Quantitative Data","what":"3.2 Mutate Quantitative Data, tq_mutate","title":"Core Functions in tidyquant","text":"Adds column set columns tibble calculated attributes (hence original tibble returned, mutated additional columns). example getting MACD close, mutates original input adding MACD Signal columns. Note can quickly rename columns using col_rename argument. Note mutation can occur , , mutation structure original tibble. words, calculation must number rows row.names (date fields), otherwise mutation performed.","code":"FANG %>% group_by(symbol) %>% tq_mutate(select = close, mutate_fun = MACD, col_rename = c(\"MACD\", \"Signal\")) ## # A tibble: 4,032 × 10 ## # Groups: symbol [4] ## symbol date open high low close volume adjusted MACD Signal ## ## 1 META 2013-01-02 27.4 28.2 27.4 28 69846400 28 NA NA ## 2 META 2013-01-03 27.9 28.5 27.6 27.8 63140600 27.8 NA NA ## 3 META 2013-01-04 28.0 28.9 27.8 28.8 72715400 28.8 NA NA ## 4 META 2013-01-07 28.7 29.8 28.6 29.4 83781800 29.4 NA NA ## 5 META 2013-01-08 29.5 29.6 28.9 29.1 45871300 29.1 NA NA ## 6 META 2013-01-09 29.7 30.6 29.5 30.6 104787700 30.6 NA NA ## 7 META 2013-01-10 30.6 31.5 30.3 31.3 95316400 31.3 NA NA ## 8 META 2013-01-11 31.3 32.0 31.1 31.7 89598000 31.7 NA NA ## 9 META 2013-01-14 32.1 32.2 30.6 31.0 98892800 31.0 NA NA ## 10 META 2013-01-15 30.6 31.7 29.9 30.1 173242600 30.1 NA NA ## # ℹ 4,022 more rows"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"mutate-rolling-regressions-with-rollapply","dir":"Articles","previous_headings":"3.0 Mutate Quantitative Data > 3.2 Mutate Quantitative Data, tq_mutate","what":"Mutate rolling regressions with rollapply","title":"Core Functions in tidyquant","text":"powerful example applying custom functions across rolling window using rollapply. specific example using rollapply function compute rolling regression. example slightly complicated broken three steps: Get returns Create custom function Apply custom function accross rolling window using tq_mutate(mutate_fun = rollapply) Step 1: Get Returns First, get combined returns. asset baseline returns wide format, needed lm function next step. Step 2: Create custom function Next, create custom regression function, used apply rolling window Step 3. important point “data” passed regression function xts object. timetk::tk_tbl function takes care converting data frame lm function work properly columns “fb.returns” “xlk.returns”. Step 3: Apply custom function Now can use tq_mutate() apply custom regression function rolling window using rollapply zoo package. Internally, since left select = NULL, returns_combined data frame passed automatically data argument rollapply function. need specify mutate_fun = rollapply additional arguments necessary apply rollapply function. ’ll specify 12 week window via width = 12. FUN argument custom regression function, regr_fun. ’s extremely important specify .column = FALSE, tells rollapply perform computation using data whole rather apply function column independently. col_rename argument used rename added columns. shown , rolling regression coefficients added data frame.","code":"fb_returns <- tq_get(\"META\", get = \"stock.prices\", from = \"2016-01-01\", to = \"2016-12-31\") %>% tq_transmute(adjusted, periodReturn, period = \"weekly\", col_rename = \"fb.returns\") xlk_returns <- tq_get(\"XLK\", from = \"2016-01-01\", to = \"2016-12-31\") %>% tq_transmute(adjusted, periodReturn, period = \"weekly\", col_rename = \"xlk.returns\") returns_combined <- left_join(fb_returns, xlk_returns, by = \"date\") returns_combined ## # A tibble: 52 × 3 ## date fb.returns xlk.returns ## ## 1 2016-01-08 -0.0478 -0.0516 ## 2 2016-01-15 -0.0242 -0.0187 ## 3 2016-01-22 0.0313 0.0264 ## 4 2016-01-29 0.146 0.0213 ## 5 2016-02-05 -0.0725 -0.0422 ## 6 2016-02-12 -0.0198 -0.00582 ## 7 2016-02-19 0.0251 0.0354 ## 8 2016-02-26 0.0320 0.0148 ## 9 2016-03-04 0.00436 0.0281 ## 10 2016-03-11 0.00941 0.0106 ## # ℹ 42 more rows regr_fun <- function(data) { coef(lm(fb.returns ~ xlk.returns, data = timetk::tk_tbl(data, silent = TRUE))) } returns_combined %>% tq_mutate(mutate_fun = rollapply, width = 12, FUN = regr_fun, by.column = FALSE, col_rename = c(\"coef.0\", \"coef.1\")) ## # A tibble: 52 × 5 ## date fb.returns xlk.returns coef.0 coef.1 ## ## 1 2016-01-08 -0.0478 -0.0516 NA NA ## 2 2016-01-15 -0.0242 -0.0187 NA NA ## 3 2016-01-22 0.0313 0.0264 NA NA ## 4 2016-01-29 0.146 0.0213 NA NA ## 5 2016-02-05 -0.0725 -0.0422 NA NA ## 6 2016-02-12 -0.0198 -0.00582 NA NA ## 7 2016-02-19 0.0251 0.0354 NA NA ## 8 2016-02-26 0.0320 0.0148 NA NA ## 9 2016-03-04 0.00436 0.0281 NA NA ## 10 2016-03-11 0.00941 0.0106 NA NA ## # ℹ 42 more rows returns_combined ## # A tibble: 52 × 3 ## date fb.returns xlk.returns ## ## 1 2016-01-08 -0.0478 -0.0516 ## 2 2016-01-15 -0.0242 -0.0187 ## 3 2016-01-22 0.0313 0.0264 ## 4 2016-01-29 0.146 0.0213 ## 5 2016-02-05 -0.0725 -0.0422 ## 6 2016-02-12 -0.0198 -0.00582 ## 7 2016-02-19 0.0251 0.0354 ## 8 2016-02-26 0.0320 0.0148 ## 9 2016-03-04 0.00436 0.0281 ## 10 2016-03-11 0.00941 0.0106 ## # ℹ 42 more rows"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"xy-variants-tq_mutate_xy-and-tq_transmute_xy","dir":"Articles","previous_headings":"3.0 Mutate Quantitative Data","what":"3.3 _xy Variants, tq_mutate_xy and tq_transmute_xy","title":"Core Functions in tidyquant","text":"Enables working mutation functions require two primary inputs (e.g. EVWMA, VWAP, etc).","code":""},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"mutate-with-two-primary-inputs","dir":"Articles","previous_headings":"3.0 Mutate Quantitative Data > 3.3 _xy Variants, tq_mutate_xy and tq_transmute_xy","what":"Mutate with two primary inputs","title":"Core Functions in tidyquant","text":"EVWMA (exponential volume-weighted moving average) requires two inputs, price volume. work columns, can switch xy variants, tq_transmute_xy() tq_mutate_xy(). difference instead select argument, use x y arguments pass columns needed based mutate_fun documentation.","code":"FANG %>% group_by(symbol) %>% tq_mutate_xy(x = close, y = volume, mutate_fun = EVWMA, col_rename = \"EVWMA\") ## # A tibble: 4,032 × 9 ## # Groups: symbol [4] ## symbol date open high low close volume adjusted EVWMA ## ## 1 META 2013-01-02 27.4 28.2 27.4 28 69846400 28 NA ## 2 META 2013-01-03 27.9 28.5 27.6 27.8 63140600 27.8 NA ## 3 META 2013-01-04 28.0 28.9 27.8 28.8 72715400 28.8 NA ## 4 META 2013-01-07 28.7 29.8 28.6 29.4 83781800 29.4 NA ## 5 META 2013-01-08 29.5 29.6 28.9 29.1 45871300 29.1 NA ## 6 META 2013-01-09 29.7 30.6 29.5 30.6 104787700 30.6 NA ## 7 META 2013-01-10 30.6 31.5 30.3 31.3 95316400 31.3 NA ## 8 META 2013-01-11 31.3 32.0 31.1 31.7 89598000 31.7 NA ## 9 META 2013-01-14 32.1 32.2 30.6 31.0 98892800 31.0 NA ## 10 META 2013-01-15 30.6 31.7 29.9 30.1 173242600 30.1 30.1 ## # ℹ 4,022 more rows"},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"overview","dir":"Articles","previous_headings":"","what":"Overview","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"’s wide range useful quantitative analysis functions work time-series objects. problem many wonderful functions don’t work data frames tidyverse workflow. now! tidyquant package integrates useful functions xts, zoo, quantmod, TTR, PerformanceAnalytics packages. vignette focuses following core functions demonstrate integratation works quantitative finance packages: Transmute, tq_transmute(): Returns new tidy data frame typically different periodicity input. Mutate, tq_mutate(): Adds columns existing tidy data frame. Refer Performance Analysis tidyquant full discussion performance analysis portfolio attribution tidyquant.","code":""},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"prerequisites","dir":"Articles","previous_headings":"","what":"Prerequisites","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"Load tidyquant package get started.","code":"# Loads tidyquant, lubridate, xts, quantmod, TTR library(tidyquant) library(lubridate) library(dplyr) library(tidyr) library(ggplot2)"},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"function-compatibility","dir":"Articles","previous_headings":"","what":"1.0 Function Compatibility","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"tq_transmute_fun_options() returns list compatible mutate functions package. ’ll discuss options package briefly.","code":"tq_transmute_fun_options() %>% str() ## List of 5 ## $ zoo : chr [1:14] \"rollapply\" \"rollapplyr\" \"rollmax\" \"rollmax.default\" ... ## $ xts : chr [1:27] \"apply.daily\" \"apply.monthly\" \"apply.quarterly\" \"apply.weekly\" ... ## $ quantmod : chr [1:25] \"allReturns\" \"annualReturn\" \"ClCl\" \"dailyReturn\" ... ## $ TTR : chr [1:64] \"adjRatios\" \"ADX\" \"ALMA\" \"aroon\" ... ## $ PerformanceAnalytics: chr [1:7] \"Return.annualized\" \"Return.annualized.excess\" \"Return.clean\" \"Return.cumulative\" ..."},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"zoo-functionality","dir":"Articles","previous_headings":"1.0 Function Compatibility","what":"zoo Functionality","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"zoo functions compatible listed . Generally speaking, : generic function applying function rolling margins. Form: rollapply(data, width, FUN, ..., = 1, .column = TRUE, fill = (na.pad) NA, na.pad = FALSE, partial = FALSE, align = c(\"center\", \"left\", \"right\"), coredata = TRUE). Options include rollmax, rollmean, rollmedian, rollsum, etc.","code":"# Get zoo functions that work with tq_transmute and tq_mutate tq_transmute_fun_options()$zoo ## [1] \"rollapply\" \"rollapplyr\" \"rollmax\" ## [4] \"rollmax.default\" \"rollmaxr\" \"rollmean\" ## [7] \"rollmean.default\" \"rollmeanr\" \"rollmedian\" ## [10] \"rollmedian.default\" \"rollmedianr\" \"rollsum\" ## [13] \"rollsum.default\" \"rollsumr\""},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"xts-functionality","dir":"Articles","previous_headings":"1.0 Function Compatibility","what":"xts Functionality","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"xts functions compatible listed . Generally speaking, : Apply function time segment (e.g. max, min, mean, etc). Form: apply.daily(x, FUN, ...). Options include apply.daily, weekly, monthly, quarterly, yearly. Convert time series time series lower periodicity (e.g. convert daily monthly periodicity). Form: .period(x, period = 'months', k = 1, indexAt, name = NULL, OHLC = TRUE, ...). Options include .minutes, hourly, daily, weekly, monthly, quarterly, yearly. Note 1 (Important): return structure different .period .monthly (.weekly, .quarterly, etc) forms. .period returns date, .months returns character MON YYYY. Best use .period want work time-series via lubridate.","code":"# Get xts functions that work with tq_transmute and tq_mutate tq_transmute_fun_options()$xts ## [1] \"apply.daily\" \"apply.monthly\" \"apply.quarterly\" \"apply.weekly\" ## [5] \"apply.yearly\" \"diff.xts\" \"lag.xts\" \"period.apply\" ## [9] \"period.max\" \"period.min\" \"period.prod\" \"period.sum\" ## [13] \"periodicity\" \"to_period\" \"to.daily\" \"to.hourly\" ## [17] \"to.minutes\" \"to.minutes10\" \"to.minutes15\" \"to.minutes3\" ## [21] \"to.minutes30\" \"to.minutes5\" \"to.monthly\" \"to.period\" ## [25] \"to.quarterly\" \"to.weekly\" \"to.yearly\""},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"quantmod-functionality","dir":"Articles","previous_headings":"1.0 Function Compatibility","what":"quantmod Functionality","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"quantmod functions compatible listed . Generally speaking, : Variations Delt: ClCl, HiCl, LoCl, LoHi, OpCl, OpHi, OpLo, OpOp Form: OpCl(OHLC) Lag: Lag(x, k = 1) / Next: Next(x, k = 1) (Can also use dplyr::lag dplyr::lead) Get arithmetic logarithmic returns various periodicity, include daily, weekly, monthly, quarterly, yearly. Form: periodReturn(x, period = 'monthly', subset = NULL, type = 'arithmetic', leading = TRUE, ...) Return values describe series. Options include describing increases/decreases, acceleration/deceleration, hi/low. Forms: seriesHi(x), seriesIncr(x, thresh = 0, diff. = 1L), seriesAccel(x)","code":"# Get quantmod functions that work with tq_transmute and tq_mutate tq_transmute_fun_options()$quantmod ## [1] \"allReturns\" \"annualReturn\" \"ClCl\" \"dailyReturn\" ## [5] \"Delt\" \"HiCl\" \"Lag\" \"LoCl\" ## [9] \"LoHi\" \"monthlyReturn\" \"Next\" \"OpCl\" ## [13] \"OpHi\" \"OpLo\" \"OpOp\" \"periodReturn\" ## [17] \"quarterlyReturn\" \"seriesAccel\" \"seriesDecel\" \"seriesDecr\" ## [21] \"seriesHi\" \"seriesIncr\" \"seriesLo\" \"weeklyReturn\" ## [25] \"yearlyReturn\""},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"ttr-functionality","dir":"Articles","previous_headings":"1.0 Function Compatibility","what":"TTR Functionality","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"’ brief description popular functions TTR: ADX(HLC, n = 14, maType, ...) BBands(HLC, n = 20, maType, sd = 2, ...): Bollinger Bands ROC(x, n = 1, type = c(\"continuous\", \"discrete\"), na.pad = TRUE): Rate Change momentum(x, n = 1, na.pad = TRUE): Momentum SMA(x, n = 10, ...): Simple Moving Average EMA(x, n = 10, wilder = FALSE, ratio = NULL, ...): Exponential Moving Average DEMA(x, n = 10, v = 1, wilder = FALSE, ratio = NULL): Double Exponential Moving Average WMA(x, n = 10, wts = 1:n, ...): Weighted Moving Average EVWMA(price, volume, n = 10, ...): Elastic, Volume-Weighted Moving Average ZLEMA(x, n = 10, ratio = NULL, ...): Zero Lag Exponential Moving Average VWAP(price, volume, n = 10, ...): Volume-Weighted Moving Average Price VMA(x, w, ratio = 1, ...): Variable-Length Moving Average HMA(x, n = 20, ...): Hull Moving Average ALMA(x, n = 9, offset = 0.85, sigma = 6, ...): Arnaud Legoux Moving Average MACD(x, nFast = 12, nSlow = 26, nSig = 9, maType, percent = TRUE, ...) RSI(price, n = 14, maType, ...) runSum(x, n = 10, cumulative = FALSE): returns sums n-period moving window. runMin(x, n = 10, cumulative = FALSE): returns minimums n-period moving window. runMax(x, n = 10, cumulative = FALSE): returns maximums n-period moving window. runMean(x, n = 10, cumulative = FALSE): returns means n-period moving window. runMedian(x, n = 10, non.unique = \"mean\", cumulative = FALSE): returns medians n-period moving window. runCov(x, y, n = 10, use = \".obs\", sample = TRUE, cumulative = FALSE): returns covariances n-period moving window. runCor(x, y, n = 10, use = \".obs\", sample = TRUE, cumulative = FALSE): returns correlations n-period moving window. runVar(x, y = NULL, n = 10, sample = TRUE, cumulative = FALSE): returns variances n-period moving window. runSD(x, n = 10, sample = TRUE, cumulative = FALSE): returns standard deviations n-period moving window. runMAD(x, n = 10, center = NULL, stat = \"median\", constant = 1.4826, non.unique = \"mean\", cumulative = FALSE): returns median/mean absolute deviations n-period moving window. wilderSum(x, n = 10): retuns Welles Wilder style weighted sum n-period moving window. stoch(HLC, nFastK = 14, nFastD = 3, nSlowD = 3, maType, bounded = TRUE, smooth = 1, ...): Stochastic Oscillator SMI(HLC, n = 13, nFast = 2, nSlow = 25, nSig = 9, maType, bounded = TRUE, ...): Stochastic Momentum Index","code":"# Get TTR functions that work with tq_transmute and tq_mutate tq_transmute_fun_options()$TTR ## [1] \"adjRatios\" \"ADX\" \"ALMA\" ## [4] \"aroon\" \"ATR\" \"BBands\" ## [7] \"CCI\" \"chaikinAD\" \"chaikinVolatility\" ## [10] \"CLV\" \"CMF\" \"CMO\" ## [13] \"CTI\" \"DEMA\" \"DonchianChannel\" ## [16] \"DPO\" \"DVI\" \"EMA\" ## [19] \"EMV\" \"EVWMA\" \"GMMA\" ## [22] \"growth\" \"HMA\" \"keltnerChannels\" ## [25] \"KST\" \"lags\" \"MACD\" ## [28] \"MFI\" \"momentum\" \"OBV\" ## [31] \"PBands\" \"ROC\" \"rollSFM\" ## [34] \"RSI\" \"runCor\" \"runCov\" ## [37] \"runMAD\" \"runMax\" \"runMean\" ## [40] \"runMedian\" \"runMin\" \"runPercentRank\" ## [43] \"runSD\" \"runSum\" \"runVar\" ## [46] \"SAR\" \"SMA\" \"SMI\" ## [49] \"SNR\" \"stoch\" \"TDI\" ## [52] \"TRIX\" \"ultimateOscillator\" \"VHF\" ## [55] \"VMA\" \"volatility\" \"VWAP\" ## [58] \"VWMA\" \"wilderSum\" \"williamsAD\" ## [61] \"WMA\" \"WPR\" \"ZigZag\" ## [64] \"ZLEMA\""},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"performanceanalytics-functionality","dir":"Articles","previous_headings":"1.0 Function Compatibility","what":"PerformanceAnalytics Functionality","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"PerformanceAnalytics mutation functions deal returns: Return.annualized Return.annualized.excess: Takes period returns consolidates annualized returns Return.clean: Removes outliers returns Return.excess: Removes risk-free rate returns yield returns excess risk-free rate zerofill: Used replace NA values zeros.","code":"# Get PerformanceAnalytics functions that work with tq_transmute and tq_mutate tq_transmute_fun_options()$PerformanceAnalytics ## [1] \"Return.annualized\" \"Return.annualized.excess\" ## [3] \"Return.clean\" \"Return.cumulative\" ## [5] \"Return.excess\" \"Return.Geltner\" ## [7] \"zerofill\""},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"quantitative-power-in-action","dir":"Articles","previous_headings":"","what":"2.0 Quantitative Power In Action","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"’ll go examples, first let’s get data. FANG data set used consists stock prices META, AMZN, NFLX, GOOG beginning 2013 end 2016.","code":"FANG ## # A tibble: 4,032 × 8 ## symbol date open high low close volume adjusted ## ## 1 META 2013-01-02 27.4 28.2 27.4 28 69846400 28 ## 2 META 2013-01-03 27.9 28.5 27.6 27.8 63140600 27.8 ## 3 META 2013-01-04 28.0 28.9 27.8 28.8 72715400 28.8 ## 4 META 2013-01-07 28.7 29.8 28.6 29.4 83781800 29.4 ## 5 META 2013-01-08 29.5 29.6 28.9 29.1 45871300 29.1 ## 6 META 2013-01-09 29.7 30.6 29.5 30.6 104787700 30.6 ## 7 META 2013-01-10 30.6 31.5 30.3 31.3 95316400 31.3 ## 8 META 2013-01-11 31.3 32.0 31.1 31.7 89598000 31.7 ## 9 META 2013-01-14 32.1 32.2 30.6 31.0 98892800 31.0 ## 10 META 2013-01-15 30.6 31.7 29.9 30.1 173242600 30.1 ## # ℹ 4,022 more rows"},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"example-1-use-quantmod-periodreturn-to-convert-prices-to-returns","dir":"Articles","previous_headings":"2.0 Quantitative Power In Action","what":"Example 1: Use quantmod periodReturn to Convert Prices to Returns","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"quantmod::periodReturn() function generates returns periodicity. ’ll go couple usage cases.","code":""},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"example-1a-getting-and-charting-annual-returns","dir":"Articles","previous_headings":"2.0 Quantitative Power In Action > Example 1: Use quantmod periodReturn to Convert Prices to Returns","what":"Example 1A: Getting and Charting Annual Returns","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"want use adjusted closing prices column (adjusted stock splits, can make appear stock performing poorly split included). set select = adjusted. research periodReturn function, found accepts type = \"arithmetic\" period = \"yearly\", returns annual returns. Charting annual returns just quick use ggplot2 package.","code":"FANG_annual_returns <- FANG %>% group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"yearly\", type = \"arithmetic\") FANG_annual_returns ## # A tibble: 16 × 3 ## # Groups: symbol [4] ## symbol date yearly.returns ## ## 1 META 2013-12-31 0.952 ## 2 META 2014-12-31 0.428 ## 3 META 2015-12-31 0.341 ## 4 META 2016-12-30 0.0993 ## 5 AMZN 2013-12-31 0.550 ## 6 AMZN 2014-12-31 -0.222 ## 7 AMZN 2015-12-31 1.18 ## 8 AMZN 2016-12-30 0.109 ## 9 NFLX 2013-12-31 3.00 ## 10 NFLX 2014-12-31 -0.0721 ## 11 NFLX 2015-12-31 1.34 ## 12 NFLX 2016-12-30 0.0824 ## 13 GOOG 2013-12-31 0.550 ## 14 GOOG 2014-12-31 -0.0597 ## 15 GOOG 2015-12-31 0.442 ## 16 GOOG 2016-12-30 0.0171 FANG_annual_returns %>% ggplot(aes(x = date, y = yearly.returns, fill = symbol)) + geom_col() + geom_hline(yintercept = 0, color = palette_light()[[1]]) + scale_y_continuous(labels = scales::percent) + labs(title = \"FANG: 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()"},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"example-1b-getting-daily-log-returns","dir":"Articles","previous_headings":"2.0 Quantitative Power In Action > Example 1: Use quantmod periodReturn to Convert Prices to Returns","what":"Example 1B: Getting Daily Log Returns","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"Daily log returns follows similar approach. Normally go transmute function, tq_transmute, periodReturn function accepts different periodicity options, anything daily blow mutation. , situation period returns periodicity stock prices periodicity (daily), can use either. want use adjusted closing prices column (adjusted stock splits, can make appear stock performing poorly split included), set select = adjusted. researched periodReturn function, found accepts type = \"log\" period = \"daily\", returns daily log returns.","code":"FANG_daily_log_returns <- FANG %>% group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"daily\", type = \"log\", col_rename = \"monthly.returns\") FANG_daily_log_returns %>% ggplot(aes(x = monthly.returns, fill = symbol)) + geom_density(alpha = 0.5) + labs(title = \"FANG: Charting the Daily Log Returns\", x = \"Monthly Returns\", y = \"Density\") + theme_tq() + scale_fill_tq() + facet_wrap(~ symbol, ncol = 2)"},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"example-2-use-xts-to-period-to-change-the-periodicity-from-daily-to-monthly","dir":"Articles","previous_headings":"2.0 Quantitative Power In Action","what":"Example 2: Use xts to.period to Change the Periodicity from Daily to Monthly","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"xts::.period function used periodicity aggregation (converting lower level periodicity higher level minutes hours months years). seeking return structure different time scale input (daily versus weekly), need use transmute function. select tq_transmute() pass open, high, low, close volume columns via select = open:volume. Looking documentation .period, see accepts period argument can set \"weeks\". result OHLCV data returned dates changed one day per week. common usage case reduce number points smooth time series plots. Let’s check difference daily monthly plots.","code":"FANG %>% group_by(symbol) %>% tq_transmute(select = open:volume, mutate_fun = to.period, period = \"months\") ## # A tibble: 192 × 7 ## # Groups: symbol [4] ## symbol date open high low close volume ## ## 1 META 2013-01-31 29.2 31.5 28.7 31.0 190744900 ## 2 META 2013-02-28 26.8 27.3 26.3 27.2 83027800 ## 3 META 2013-03-28 26.1 26.2 25.5 25.6 28585700 ## 4 META 2013-04-30 27.1 27.8 27.0 27.8 36245700 ## 5 META 2013-05-31 24.6 25.0 24.3 24.4 35925000 ## 6 META 2013-06-28 24.7 25.0 24.4 24.9 96778900 ## 7 META 2013-07-31 38.0 38.3 36.3 36.8 154828700 ## 8 META 2013-08-30 42.0 42.3 41.1 41.3 67735100 ## 9 META 2013-09-30 50.1 51.6 49.8 50.2 100095000 ## 10 META 2013-10-31 47.2 52 46.5 50.2 248809000 ## # ℹ 182 more rows"},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"without-periodicity-aggregation","dir":"Articles","previous_headings":"2.0 Quantitative Power In Action > Example 2: Use xts to.period to Change the Periodicity from Daily to Monthly","what":"Without Periodicity Aggregation","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"","code":"FANG_daily <- FANG %>% group_by(symbol) FANG_daily %>% ggplot(aes(x = date, y = adjusted, color = symbol)) + geom_line(linewidth = 1) + labs(title = \"Daily Stock Prices\", x = \"\", y = \"Adjusted Prices\", color = \"\") + facet_wrap(~ symbol, ncol = 2, scales = \"free_y\") + scale_y_continuous(labels = scales::dollar) + theme_tq() + scale_color_tq()"},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"with-monthly-periodicity-aggregation","dir":"Articles","previous_headings":"2.0 Quantitative Power In Action > Example 2: Use xts to.period to Change the Periodicity from Daily to Monthly","what":"With Monthly Periodicity Aggregation","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"","code":"FANG_monthly <- FANG %>% group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = to.period, period = \"months\") FANG_monthly %>% ggplot(aes(x = date, y = adjusted, color = symbol)) + geom_line(linewidth = 1) + labs(title = \"Monthly Stock Prices\", x = \"\", y = \"Adjusted Prices\", color = \"\") + facet_wrap(~ symbol, ncol = 2, scales = \"free_y\") + scale_y_continuous(labels = scales::dollar) + theme_tq() + scale_color_tq()"},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"example-3-use-ttr-runcor-to-visualize-rolling-correlations-of-returns","dir":"Articles","previous_headings":"2.0 Quantitative Power In Action","what":"Example 3: Use TTR runCor to Visualize Rolling Correlations of Returns","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"Return correlations common way analyze closely asset portfolio mimics baseline index fund. need set returns stocks baseline. stock FANG data set baseline Spdr XLK technology sector. prices “FANG” stocks, use tq_get retrieve “XLK” prices. returns can calculated “adjusted” prices using process Example 1. Next, join asset returns baseline returns date. TTR::runCor function can used evaluate rolling correlations using xy pattern. Looking documentation (?runCor), can see arguments include x y along additional arguments including n width rolling correlation. scale monthly, ’ll go n = 6 6-month rolling correlation. col_rename argument enables easy renaming output column(s). , can plot rolling correlations FANG stocks.","code":"# Asset Returns FANG_returns_monthly <- FANG %>% dplyr::group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"monthly\") # Baseline Returns baseline_returns_monthly <- \"XLK\" %>% tq_get(get = \"stock.prices\", from = \"2013-01-01\", to = \"2016-12-31\") %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"monthly\") returns_joined <- left_join(FANG_returns_monthly, baseline_returns_monthly, by = \"date\") returns_joined ## # A tibble: 192 × 4 ## # Groups: symbol [4] ## symbol date monthly.returns.x monthly.returns.y ## ## 1 META 2013-01-31 0.106 -0.0138 ## 2 META 2013-02-28 -0.120 0.00782 ## 3 META 2013-03-28 -0.0613 0.0258 ## 4 META 2013-04-30 0.0856 0.0175 ## 5 META 2013-05-31 -0.123 0.0279 ## 6 META 2013-06-28 0.0218 -0.0289 ## 7 META 2013-07-31 0.479 0.0373 ## 8 META 2013-08-30 0.122 -0.0104 ## 9 META 2013-09-30 0.217 0.0253 ## 10 META 2013-10-31 -0.000398 0.0502 ## # ℹ 182 more rows FANG_rolling_corr <- returns_joined %>% tq_transmute_xy(x = monthly.returns.x, y = monthly.returns.y, mutate_fun = runCor, n = 6, col_rename = \"rolling.corr.6\") FANG_rolling_corr %>% ggplot(aes(x = date, y = rolling.corr.6, color = symbol)) + geom_hline(yintercept = 0, color = palette_light()[[1]]) + geom_line(linewidth = 1) + labs(title = \"FANG: Six Month Rolling Correlation to XLK\", x = \"\", y = \"Correlation\", color = \"\") + facet_wrap(~ symbol, ncol = 2) + theme_tq() + scale_color_tq()"},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"example-4-use-ttr-macd-to-visualize-moving-average-convergence-divergence","dir":"Articles","previous_headings":"2.0 Quantitative Power In Action","what":"Example 4: Use TTR MACD to Visualize Moving Average Convergence Divergence","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"reviewing available options TTR package, see MACD get us Moving Average Convergence Divergence (MACD). researching documentation, return periodicity input functions work OHLC functions, can use tq_mutate(). MACD requires price, select close. , can visualize data like .","code":"FANG_macd <- FANG %>% group_by(symbol) %>% tq_mutate(select = close, mutate_fun = MACD, nFast = 12, nSlow = 26, nSig = 9, maType = SMA) %>% mutate(diff = macd - signal) %>% select(-(open:volume)) FANG_macd ## # A tibble: 4,032 × 6 ## # Groups: symbol [4] ## symbol date adjusted macd signal diff ## ## 1 META 2013-01-02 28 NA NA NA ## 2 META 2013-01-03 27.8 NA NA NA ## 3 META 2013-01-04 28.8 NA NA NA ## 4 META 2013-01-07 29.4 NA NA NA ## 5 META 2013-01-08 29.1 NA NA NA ## 6 META 2013-01-09 30.6 NA NA NA ## 7 META 2013-01-10 31.3 NA NA NA ## 8 META 2013-01-11 31.7 NA NA NA ## 9 META 2013-01-14 31.0 NA NA NA ## 10 META 2013-01-15 30.1 NA NA NA ## # ℹ 4,022 more rows FANG_macd %>% filter(date >= as_date(\"2016-10-01\")) %>% ggplot(aes(x = date)) + geom_hline(yintercept = 0, color = palette_light()[[1]]) + geom_line(aes(y = macd, col = symbol)) + geom_line(aes(y = signal), color = \"blue\", linetype = 2) + geom_bar(aes(y = diff), stat = \"identity\", color = palette_light()[[1]]) + facet_wrap(~ symbol, ncol = 2, scale = \"free_y\") + labs(title = \"FANG: Moving Average Convergence Divergence\", y = \"MACD\", x = \"\", color = \"\") + theme_tq() + scale_color_tq()"},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"example-5-use-xts-apply-quarterly-to-get-the-max-and-min-price-for-each-quarter","dir":"Articles","previous_headings":"2.0 Quantitative Power In Action","what":"Example 5: Use xts apply.quarterly to Get the Max and Min Price for Each Quarter","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"xts::apply.quarterly() function part period apply group can used apply functions quarterly time segments. seeking return structure different time scale input (quarterly versus daily), need use transmute function. select tq_transmute pass close price using select, send subset data apply.quarterly function via mutate_fun argument. Looking documentation apply.quarterly, see can pass function argument, FUN. want maximum values, set FUN = max. result quarters returned date maximum closing price quarter returned double. minimum quarter can retrieved much way. data frames can joined using left_join get max min quarter. , can visualize data like .","code":"FANG_max_by_qtr <- FANG %>% group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = apply.quarterly, FUN = max, col_rename = \"max.close\") %>% mutate(year.qtr = paste0(year(date), \"-Q\", quarter(date))) %>% select(-date) FANG_max_by_qtr ## # A tibble: 64 × 3 ## # Groups: symbol [4] ## symbol max.close year.qtr ## ## 1 META 32.5 2013-Q1 ## 2 META 29.0 2013-Q2 ## 3 META 51.2 2013-Q3 ## 4 META 58.0 2013-Q4 ## 5 META 72.0 2014-Q1 ## 6 META 67.6 2014-Q2 ## 7 META 79.0 2014-Q3 ## 8 META 81.4 2014-Q4 ## 9 META 85.3 2015-Q1 ## 10 META 88.9 2015-Q2 ## # ℹ 54 more rows FANG_min_by_qtr <- FANG %>% group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = apply.quarterly, FUN = min, col_rename = \"min.close\") %>% mutate(year.qtr = paste0(year(date), \"-Q\", quarter(date))) %>% select(-date) FANG_by_qtr <- left_join(FANG_max_by_qtr, FANG_min_by_qtr, by = c(\"symbol\" = \"symbol\", \"year.qtr\" = \"year.qtr\")) FANG_by_qtr ## # A tibble: 64 × 4 ## # Groups: symbol [4] ## symbol max.close year.qtr min.close ## ## 1 META 32.5 2013-Q1 25.1 ## 2 META 29.0 2013-Q2 22.9 ## 3 META 51.2 2013-Q3 24.4 ## 4 META 58.0 2013-Q4 44.8 ## 5 META 72.0 2014-Q1 53.5 ## 6 META 67.6 2014-Q2 56.1 ## 7 META 79.0 2014-Q3 62.8 ## 8 META 81.4 2014-Q4 72.6 ## 9 META 85.3 2015-Q1 74.1 ## 10 META 88.9 2015-Q2 77.5 ## # ℹ 54 more rows FANG_by_qtr %>% ggplot(aes(x = year.qtr, color = symbol)) + geom_segment(aes(xend = year.qtr, y = min.close, yend = max.close), linewidth = 1) + geom_point(aes(y = max.close), size = 2) + geom_point(aes(y = min.close), size = 2) + facet_wrap(~ symbol, ncol = 2, scale = \"free_y\") + labs(title = \"FANG: 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())"},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"example-6-use-zoo-rollapply-to-visualize-a-rolling-regression","dir":"Articles","previous_headings":"2.0 Quantitative Power In Action","what":"Example 6: Use zoo rollapply to visualize a rolling regression","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"good way analyze relationships time using rolling calculations compare two assets. Pairs trading common mechanism similar assets. go pairs trade analysis, analyze relationship two similar assets precursor pairs trade. example analyze two similar assets, Mastercard (MA) Visa (V) show relationship via regression. analyze rolling regression, ’s helpful view overall trend returns. , use tq_get() get stock prices assets tq_transmute() transform daily prices daily returns. ’ll collect data visualize via scatter plot. can visualize relationship returns stock pairs like . can get statistcs relationship lm function. model highly correlated p-value essential zero. coefficient estimate V (Coefficient 1) 0.8134 indicating positive relationship, meaning V increases MA also tends increase. characterizes overall relationship, ’s missing time aspect. Fortunately, can use rollapply function zoo package plot rolling regression, showing model coefficent varies rolling basis time. calculate rolling regressions tq_mutate() two additional steps: Create custom function Apply function tq_mutate(mutate_fun = rollapply) First, create custom regression function. important point “data” passed regression function xts object. timetk::tk_tbl function takes care converting data frame. Now can use tq_mutate() apply custom regression function rolling window using rollapply zoo package. Internally, returns_combined data frame passed automatically data argument rollapply function. need specify mutate_fun = rollapply additional arguments necessary apply rollapply function. ’ll specify 90 day window via width = 90. FUN argument custom regression function, regr_fun. ’s extremely important specify .column = FALSE, tells rollapply perform computation using data whole rather apply function column independently. col_rename argument used rename added columns. Finally, can visualize first coefficient like . horizontal line added using full data set model. gives us insight points time relationship deviates significantly long run trend can explored potential pair trade opportunities. Stock returns time period.","code":"# Get stock pairs stock_prices <- c(\"MA\", \"V\") %>% tq_get(get = \"stock.prices\", from = \"2015-01-01\", to = \"2016-12-31\") %>% group_by(symbol) stock_pairs <- stock_prices %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"daily\", type = \"log\", col_rename = \"returns\") %>% spread(key = symbol, value = returns) stock_pairs %>% ggplot(aes(x = V, y = MA)) + geom_point(color = palette_light()[[1]], alpha = 0.5) + geom_smooth(method = \"lm\") + labs(title = \"Visualizing Returns Relationship of Stock Pairs\") + theme_tq() lm(MA ~ V, data = stock_pairs) %>% summary() ## ## Call: ## lm(formula = MA ~ V, data = stock_pairs) ## ## Residuals: ## Min 1Q Median 3Q Max ## -0.0269572 -0.0039655 0.0002147 0.0039656 0.0289464 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 0.0001130 0.0003097 0.365 0.715 ## V 0.8133673 0.0226393 35.927 <2e-16 *** ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ## ## Residual standard error: 0.00695 on 502 degrees of freedom ## Multiple R-squared: 0.72, Adjusted R-squared: 0.7194 ## F-statistic: 1291 on 1 and 502 DF, p-value: < 2.2e-16 regr_fun <- function(data) { coef(lm(MA ~ V, data = timetk::tk_tbl(data, silent = TRUE))) } stock_pairs <- stock_pairs %>% tq_mutate(mutate_fun = rollapply, width = 90, FUN = regr_fun, by.column = FALSE, col_rename = c(\"coef.0\", \"coef.1\")) stock_pairs ## # A tibble: 504 × 5 ## date MA V coef.0 coef.1 ## ## 1 2015-01-02 0 0 NA NA ## 2 2015-01-05 -0.0285 -0.0223 NA NA ## 3 2015-01-06 -0.00216 -0.00646 NA NA ## 4 2015-01-07 0.0154 0.0133 NA NA ## 5 2015-01-08 0.0154 0.0133 NA NA ## 6 2015-01-09 -0.0128 -0.0149 NA NA ## 7 2015-01-12 -0.0129 -0.00196 NA NA ## 8 2015-01-13 0.00228 0.00292 NA NA ## 9 2015-01-14 -0.00108 -0.0202 NA NA ## 10 2015-01-15 -0.0146 -0.00955 NA NA ## # ℹ 494 more rows stock_pairs %>% ggplot(aes(x = date, y = coef.1)) + geom_line(linewidth = 1, color = palette_light()[[1]]) + geom_hline(yintercept = 0.8134, linewidth = 1, color = palette_light()[[2]]) + labs(title = \"MA ~ V: Visualizing Rolling Regression Coefficient\", x = \"\") + theme_tq() stock_prices %>% 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(linewidth = 1) + labs(title = \"MA and V: Stock Prices\") + theme_tq() + scale_color_tq()"},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"example-7-use-return-clean-and-return-excess-to-clean-and-calculate-excess-returns","dir":"Articles","previous_headings":"2.0 Quantitative Power In Action","what":"Example 7: Use Return.clean and Return.excess to clean and calculate excess returns","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"example use several PerformanceAnalytics functions clean format returns. example uses three progressive applications tq_transmute apply various quant functions grouped stock prices FANG data set. First, calculate daily returns using quantmod::periodReturn. Next, use Return.clean clean outliers return data. alpha parameter percentage oultiers cleaned. Finally, excess returns calculated using risk-free rate 3% (divided 252 252 trade days one year).","code":"FANG %>% 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) ## # A tibble: 4,032 × 3 ## # Groups: symbol [4] ## symbol date `daily.returns > Rf` ## ## 1 META 2013-01-02 -0.000119 ## 2 META 2013-01-03 -0.00833 ## 3 META 2013-01-04 0.0355 ## 4 META 2013-01-07 0.0228 ## 5 META 2013-01-08 -0.0124 ## 6 META 2013-01-09 0.0525 ## 7 META 2013-01-10 0.0231 ## 8 META 2013-01-11 0.0133 ## 9 META 2013-01-14 -0.0244 ## 10 META 2013-01-15 -0.0276 ## # ℹ 4,022 more rows"},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"overview","dir":"Articles","previous_headings":"","what":"Overview","title":"Scaling and Modeling with tidyquant","text":"greatest benefit tidyquant ability apply data science workflow easily model scale financial analysis described R Data Science. Scaling process creating analysis one asset extending multiple groups. idea scaling incredibly useful financial analysts typically one wants compare many assets make informed decisions. Fortunately, tidyquant package integrates tidyverse making scaling super simple! tidyquant functions return data tibble (tidy data frame) format, allows interaction within tidyverse. means can: Seamlessly scale data retrieval mutations Use pipe (%>%) chaining operations Use dplyr tidyr: select, filter, group_by, nest/unnest, spread/gather, etc Use purrr: mapping functions map Model financial analysis using data science workflow R Data Science ’ll go useful techniques getting manipulating groups data.","code":""},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"prerequisites","dir":"Articles","previous_headings":"","what":"Prerequisites","title":"Scaling and Modeling with tidyquant","text":"Load tidyquant package get started.","code":"# Loads tidyquant, lubridate, xts, quantmod, TTR, and PerformanceAnalytics library(lubridate) library(dplyr) library(purrr) library(ggplot2) library(tidyr) library(tidyquant)"},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"scaling-the-getting-of-financial-data","dir":"Articles","previous_headings":"","what":"1.0 Scaling the Getting of Financial Data","title":"Scaling and Modeling with tidyquant","text":"basic example retrieving stock prices multiple stocks. three primary ways :","code":""},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"method-1-map-a-character-vector-with-multiple-stock-symbols","dir":"Articles","previous_headings":"1.0 Scaling the Getting of Financial Data","what":"Method 1: Map a character vector with multiple stock symbols","title":"Scaling and Modeling with tidyquant","text":"output single level tibble stock prices one tibble. auto-generated column name “symbol”, can pre-emptively renamed giving vector name (e.g. stocks <- c(\"AAPL\", \"GOOG\", \"META\")) piping tq_get.","code":"c(\"AAPL\", \"GOOG\", \"META\") %>% tq_get(get = \"stock.prices\", from = \"2016-01-01\", to = \"2017-01-01\") ## # A tibble: 756 × 8 ## symbol date open high low close volume adjusted ## ## 1 AAPL 2016-01-04 25.7 26.3 25.5 26.3 270597600 24.0 ## 2 AAPL 2016-01-05 26.4 26.5 25.6 25.7 223164000 23.4 ## 3 AAPL 2016-01-06 25.1 25.6 25.0 25.2 273829600 22.9 ## 4 AAPL 2016-01-07 24.7 25.0 24.1 24.1 324377600 22.0 ## 5 AAPL 2016-01-08 24.6 24.8 24.2 24.2 283192000 22.1 ## 6 AAPL 2016-01-11 24.7 24.8 24.3 24.6 198957600 22.5 ## 7 AAPL 2016-01-12 25.1 25.2 24.7 25.0 196616800 22.8 ## 8 AAPL 2016-01-13 25.1 25.3 24.3 24.3 249758400 22.2 ## 9 AAPL 2016-01-14 24.5 25.1 23.9 24.9 252680400 22.7 ## 10 AAPL 2016-01-15 24.0 24.4 23.8 24.3 319335600 22.1 ## # ℹ 746 more rows"},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"method-2-map-a-tibble-with-stocks-in-first-column","dir":"Articles","previous_headings":"1.0 Scaling the Getting of Financial Data","what":"Method 2: Map a tibble with stocks in first column","title":"Scaling and Modeling with tidyquant","text":"First, get stock list data frame format either making tibble retrieving tq_index / tq_exchange. stock symbols must first column.","code":""},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"method-2a-make-a-tibble","dir":"Articles","previous_headings":"1.0 Scaling the Getting of Financial Data > Method 2: Map a tibble with stocks in first column","what":"Method 2A: Make a tibble","title":"Scaling and Modeling with tidyquant","text":"Second, send stock list tq_get. Notice symbol industry columns automatically expanded length stock prices.","code":"stock_list <- tibble(stocks = c(\"AAPL\", \"JPM\", \"CVX\"), industry = c(\"Technology\", \"Financial\", \"Energy\")) stock_list ## # A tibble: 3 × 2 ## stocks industry ## ## 1 AAPL Technology ## 2 JPM Financial ## 3 CVX Energy stock_list %>% tq_get(get = \"stock.prices\", from = \"2016-01-01\", to = \"2017-01-01\") ## # A tibble: 756 × 9 ## stocks industry date open high low close volume adjusted ## ## 1 AAPL Technology 2016-01-04 25.7 26.3 25.5 26.3 270597600 24.0 ## 2 AAPL Technology 2016-01-05 26.4 26.5 25.6 25.7 223164000 23.4 ## 3 AAPL Technology 2016-01-06 25.1 25.6 25.0 25.2 273829600 22.9 ## 4 AAPL Technology 2016-01-07 24.7 25.0 24.1 24.1 324377600 22.0 ## 5 AAPL Technology 2016-01-08 24.6 24.8 24.2 24.2 283192000 22.1 ## 6 AAPL Technology 2016-01-11 24.7 24.8 24.3 24.6 198957600 22.5 ## 7 AAPL Technology 2016-01-12 25.1 25.2 24.7 25.0 196616800 22.8 ## 8 AAPL Technology 2016-01-13 25.1 25.3 24.3 24.3 249758400 22.2 ## 9 AAPL Technology 2016-01-14 24.5 25.1 23.9 24.9 252680400 22.7 ## 10 AAPL Technology 2016-01-15 24.0 24.4 23.8 24.3 319335600 22.1 ## # ℹ 746 more rows"},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"method-2b-use-index-or-exchange","dir":"Articles","previous_headings":"1.0 Scaling the Getting of Financial Data > Method 2: Map a tibble with stocks in first column","what":"Method 2B: Use index or exchange","title":"Scaling and Modeling with tidyquant","text":"Get index… …, get exchange. Send index exchange tq_get. Important Note: can take several minutes depending size index exchange, first three stocks evaluated vignette. can use applicable “getter” get data every stock index exchange! includes: “stock.prices”, “key.ratios”, “key.stats”, .","code":"tq_index(\"DOW\") ## # A tibble: 31 × 8 ## symbol company identifier sedol weight sector shares_held local_currency ## ## 1 UNH UNITEDHEALT… 91324P102 2917… 0.0996 - 5477820 USD ## 2 GS GOLDMAN SAC… 38141G104 2407… 0.0635 - 5477820 USD ## 3 MSFT MICROSOFT C… 594918104 2588… 0.0612 - 5477820 USD ## 4 HD HOME DEPOT … 437076102 2434… 0.0592 - 5477820 USD ## 5 CAT CATERPILLAR… 149123101 2180… 0.0539 - 5477820 USD ## 6 AMGN AMGEN INC 031162100 2023… 0.0529 - 5477820 USD ## 7 MCD MCDONALD S … 580135101 2550… 0.0518 - 5477820 USD ## 8 V VISA INC CL… 92826C839 B2PZ… 0.0452 - 5477820 USD ## 9 CRM SALESFORCE … 79466L302 2310… 0.0397 - 5477820 USD ## 10 BA BOEING CO/T… 097023105 2108… 0.0372 - 5477820 USD ## # ℹ 21 more rows tq_exchange(\"NYSE\") tq_index(\"DOW\") %>% slice(1:3) %>% tq_get(get = \"stock.prices\") ## # A tibble: 8,112 × 15 ## symbol company identifier sedol weight sector shares_held local_currency ## ## 1 UNH UNITEDHEALT… 91324P102 2917… 0.0996 - 5477820 USD ## 2 UNH UNITEDHEALT… 91324P102 2917… 0.0996 - 5477820 USD ## 3 UNH UNITEDHEALT… 91324P102 2917… 0.0996 - 5477820 USD ## 4 UNH UNITEDHEALT… 91324P102 2917… 0.0996 - 5477820 USD ## 5 UNH UNITEDHEALT… 91324P102 2917… 0.0996 - 5477820 USD ## 6 UNH UNITEDHEALT… 91324P102 2917… 0.0996 - 5477820 USD ## 7 UNH UNITEDHEALT… 91324P102 2917… 0.0996 - 5477820 USD ## 8 UNH UNITEDHEALT… 91324P102 2917… 0.0996 - 5477820 USD ## 9 UNH UNITEDHEALT… 91324P102 2917… 0.0996 - 5477820 USD ## 10 UNH UNITEDHEALT… 91324P102 2917… 0.0996 - 5477820 USD ## # ℹ 8,102 more rows ## # ℹ 7 more variables: date , open , high , low , ## # close , volume , adjusted "},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"scaling-the-mutation-of-financial-data","dir":"Articles","previous_headings":"","what":"2.0 Scaling the Mutation of Financial Data","title":"Scaling and Modeling with tidyquant","text":"get data, typically want something . can easily scale. Let’s get yearly returns multiple stocks using tq_transmute. First, get prices. ’ll use FANG data set, typically use tq_get retrieve data “tibble” format. Second, use group_by group stock symbol. Third, apply mutation. can one easy workflow. periodReturn function applied group stock prices, new data frame returned annual returns correct periodicity. Last, can visualize returns.","code":"FANG ## # A tibble: 4,032 × 8 ## symbol date open high low close volume adjusted ## ## 1 META 2013-01-02 27.4 28.2 27.4 28 69846400 28 ## 2 META 2013-01-03 27.9 28.5 27.6 27.8 63140600 27.8 ## 3 META 2013-01-04 28.0 28.9 27.8 28.8 72715400 28.8 ## 4 META 2013-01-07 28.7 29.8 28.6 29.4 83781800 29.4 ## 5 META 2013-01-08 29.5 29.6 28.9 29.1 45871300 29.1 ## 6 META 2013-01-09 29.7 30.6 29.5 30.6 104787700 30.6 ## 7 META 2013-01-10 30.6 31.5 30.3 31.3 95316400 31.3 ## 8 META 2013-01-11 31.3 32.0 31.1 31.7 89598000 31.7 ## 9 META 2013-01-14 32.1 32.2 30.6 31.0 98892800 31.0 ## 10 META 2013-01-15 30.6 31.7 29.9 30.1 173242600 30.1 ## # ℹ 4,022 more rows FANG_returns_yearly <- FANG %>% group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"yearly\", col_rename = \"yearly.returns\") FANG_returns_yearly %>% ggplot(aes(x = year(date), y = yearly.returns, fill = symbol)) + geom_bar(position = \"dodge\", stat = \"identity\") + labs(title = \"FANG: Annual Returns\", subtitle = \"Mutating at scale is quick and easy!\", y = \"Returns\", x = \"\", color = \"\") + scale_y_continuous(labels = scales::percent) + coord_flip() + theme_tq() + scale_fill_tq()"},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"modeling-financial-data-using-purrr","dir":"Articles","previous_headings":"","what":"3.0 Modeling Financial Data using purrr","title":"Scaling and Modeling with tidyquant","text":"Eventually want begin modeling (generally applying functions) scale! One best features tidyverse ability map functions nested tibbles using purrr. Many Models chapter “R Data Science”, can apply modeling workflow financial analysis. Using two step workflow: Model single stock Scale many stocks Let’s go example illustrate.","code":""},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"example-applying-a-regression-model-to-detect-a-positive-trend","dir":"Articles","previous_headings":"3.0 Modeling Financial Data using purrr","what":"Example: Applying a Regression Model to Detect a Positive Trend","title":"Scaling and Modeling with tidyquant","text":"example, ’ll use simple linear model identify trend annual returns determine stock returns decreasing increasing time.","code":""},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"analyze-a-single-stock","dir":"Articles","previous_headings":"3.0 Modeling Financial Data using purrr > Example: Applying a Regression Model to Detect a Positive Trend","what":"Analyze a Single Stock","title":"Scaling and Modeling with tidyquant","text":"First, let’s collect stock data tq_get() Next, come function help us collect annual log returns. function mutates stock prices period returns using tq_transmute(). add type = \"log\" period = \"monthly\" arguments ensure retrieve tibble monthly log returns. Last, take mean monthly returns get MMLR. Let’s test get_annual_returns . now annual log returns past ten years. Let’s visualize identify trends. can see linear trend line AAPL’s stock returns declining. Now, can get linear model using lm() function. However, one problem: output “tidy”. can utilize broom package get “tidy” data model. ’s three primary functions: augment: adds columns original data predictions, residuals cluster assignments glance: provides one-row summary model-level statistics tidy: summarizes model’s statistical findings coefficients regression ’ll use tidy retrieve model coefficients. Adding workflow, following: Testing single stock. can see “term” contains direction trend (slope) “year(date)”. interpetation year increases one unit, annual returns decrease 3%. Now identified trend direction, looks like ready scale.","code":"AAPL <- tq_get(\"AAPL\", from = \"2007-01-01\", to = \"2016-12-31\") AAPL ## # A tibble: 2,518 × 8 ## symbol date open high low close volume adjusted ## ## 1 AAPL 2007-01-03 3.08 3.09 2.92 2.99 1238319600 2.54 ## 2 AAPL 2007-01-04 3.00 3.07 2.99 3.06 847260400 2.60 ## 3 AAPL 2007-01-05 3.06 3.08 3.01 3.04 834741600 2.58 ## 4 AAPL 2007-01-08 3.07 3.09 3.05 3.05 797106800 2.59 ## 5 AAPL 2007-01-09 3.09 3.32 3.04 3.31 3349298400 2.81 ## 6 AAPL 2007-01-10 3.38 3.49 3.34 3.46 2952880000 2.94 ## 7 AAPL 2007-01-11 3.43 3.46 3.40 3.42 1440252800 2.90 ## 8 AAPL 2007-01-12 3.38 3.39 3.33 3.38 1312690400 2.87 ## 9 AAPL 2007-01-16 3.42 3.47 3.41 3.47 1244076400 2.94 ## 10 AAPL 2007-01-17 3.48 3.49 3.39 3.39 1646260000 2.88 ## # ℹ 2,508 more rows get_annual_returns <- function(stock.returns) { stock.returns %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, type = \"log\", period = \"yearly\") } AAPL_annual_log_returns <- get_annual_returns(AAPL) AAPL_annual_log_returns ## # A tibble: 10 × 2 ## date yearly.returns ## ## 1 2007-12-31 0.860 ## 2 2008-12-31 -0.842 ## 3 2009-12-31 0.904 ## 4 2010-12-31 0.426 ## 5 2011-12-30 0.228 ## 6 2012-12-31 0.282 ## 7 2013-12-31 0.0776 ## 8 2014-12-31 0.341 ## 9 2015-12-31 -0.0306 ## 10 2016-12-30 0.118 AAPL_annual_log_returns %>% ggplot(aes(x = year(date), y = yearly.returns)) + geom_hline(yintercept = 0, color = palette_light()[[1]]) + geom_point(size = 2, color = palette_light()[[3]]) + geom_line(linewidth = 1, color = palette_light()[[3]]) + geom_smooth(method = \"lm\", se = FALSE) + labs(title = \"AAPL: Visualizing Trends in Annual Returns\", x = \"\", y = \"Annual Returns\", color = \"\") + theme_tq() mod <- lm(yearly.returns ~ year(date), data = AAPL_annual_log_returns) mod ## ## Call: ## lm(formula = yearly.returns ~ year(date), data = AAPL_annual_log_returns) ## ## Coefficients: ## (Intercept) year(date) ## 58.86281 -0.02915 library(broom) tidy(mod) ## # A tibble: 2 × 5 ## term estimate std.error statistic p.value ## ## 1 (Intercept) 58.9 113. 0.520 0.617 ## 2 year(date) -0.0291 0.0562 -0.518 0.618 get_model <- function(stock_data) { annual_returns <- get_annual_returns(stock_data) mod <- lm(yearly.returns ~ year(date), data = annual_returns) tidy(mod) } get_model(AAPL) ## # A tibble: 2 × 5 ## term estimate std.error statistic p.value ## ## 1 (Intercept) 58.9 113. 0.520 0.617 ## 2 year(date) -0.0291 0.0562 -0.518 0.618"},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"scale-to-many-stocks","dir":"Articles","previous_headings":"3.0 Modeling Financial Data using purrr > Example: Applying a Regression Model to Detect a Positive Trend","what":"Scale to Many Stocks","title":"Scaling and Modeling with tidyquant","text":"analysis one stock done scale many stocks simple. brevity, ’ll randomly sample ten stocks S&P500 call dplyr::sample_n(). can now apply analysis function stocks using dplyr::mutate purrr::map. mutate() function adds column tibble, map() function maps custom get_model function tibble stocks using symbol column. tidyr::unnest function unrolls nested data frame model statistics accessable top data frame level. filter, arrange select steps just manipulate data frame isolate arrange data viewing. ’re done! now coefficient linear regression tracks direction trend line. can easily extend type analysis larger lists stock indexes. example, entire S&P500 analyzed removing sample_n() following call tq_index(\"SP500\").","code":"set.seed(10) stocks_tbl <- tq_index(\"SP500\") %>% sample_n(5) stocks_tbl ## # A tibble: 5 × 8 ## symbol company identifier sedol weight sector shares_held local_currency ## ## 1 TPR TAPESTRY INC 876030107 BF09… 1.81e-4 - 2586531 USD ## 2 FCX FREEPORT MC… 35671D857 2352… 1.48e-3 - 15983335 USD ## 3 HWM HOWMET AERO… 443201108 BKLJ… 5.04e-4 - 4369675 USD ## 4 ATO ATMOS ENERG… 049560105 2315… 4.35e-4 - 1656490 USD ## 5 EMN EASTMAN CHE… 277432100 2298… 2.55e-4 - 1338851 USD stocks_model_stats <- stocks_tbl %>% select(symbol, company) %>% tq_get(from = \"2007-01-01\", to = \"2016-12-31\") %>% # Nest group_by(symbol, company) %>% nest() %>% # Apply the get_model() function to the new \"nested\" data column mutate(model = map(data, get_model)) %>% # Unnest and collect slope unnest(model) %>% filter(term == \"year(date)\") %>% arrange(desc(estimate)) %>% select(-term) stocks_model_stats ## # A tibble: 5 × 7 ## # Groups: symbol, company [5] ## symbol company data estimate std.error statistic p.value ## ## 1 ATO ATMOS ENERGY CORP 0.0291 0.0126 2.32 0.0490 ## 2 EMN EASTMAN CHEMICAL CO 0.00566 0.0435 0.130 0.900 ## 3 TPR TAPESTRY INC 0.000725 0.0382 0.0190 0.985 ## 4 FCX FREEPORT MCMORAN INC -0.0460 0.0974 -0.472 0.649 ## 5 HWM HOWMET AEROSPACE INC NA NA NA NA"},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"error-handling-when-scaling","dir":"Articles","previous_headings":"","what":"4.0 Error Handling when Scaling","title":"Scaling and Modeling with tidyquant","text":"Eventually run stock index, stock symbol, FRED data code, etc retrieved. Possible reasons : index becomes date company goes private stock ticker symbol changes Yahoo / FRED just doesn’t like stock symbol / FRED code becomes painful scaling functions return errors. , tq_get() function designed handle errors gracefully. means NA value returned error generated along gentle error warning.","code":"tq_get(\"XYZ\", \"stock.prices\") ## [1] NA"},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"pros-and-cons-to-built-in-error-handling","dir":"Articles","previous_headings":"4.0 Error Handling when Scaling","what":"Pros and Cons to Built-In Error-Handling","title":"Scaling and Modeling with tidyquant","text":"pros cons approach may agree , believe helps long run. Just aware happens: Pros: Long running scripts interrupted one error Cons: Errors can inadvertently handled flow downstream users read warnings","code":""},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"bad-apples-fail-gracefully-tq_get","dir":"Articles","previous_headings":"4.0 Error Handling when Scaling","what":"Bad Apples Fail Gracefully, tq_get","title":"Scaling and Modeling with tidyquant","text":"Let’s see example using tq_get() get stock prices long list stocks one BAD APPLE. argument complete_cases comes handy. default TRUE, removes “bad apples” future analysis complete cases compute . Note gentle warning stating error occurred dealt removing rows results. Now switching complete_cases = FALSE retain errors NA values nested data frame. Notice error message output change. error message now states NA values exist output return “nested” data structure. cases, prudent user review warnings determine happened whether acceptable. complete_cases = FALSE example, user attempts perform downstream computations scale, computations likely fail grinding analysis hault. , advantage user easily able filter problem childs determine happened decide whether acceptable .","code":"c(\"AAPL\", \"GOOG\", \"BAD APPLE\") %>% tq_get(get = \"stock.prices\", complete_cases = TRUE) ## Warning: There was 1 warning in `dplyr::mutate()`. ## ℹ In argument: `data.. = purrr::map(...)`. ## Caused by warning: ## ! x = 'BAD APPLE', get = 'stock.prices': Error in getSymbols.yahoo(Symbols = \"BAD APPLE\", env = , : Unable to import \"BAD APPLE\". ## URL using bad/illegal format or missing URL ## Removing BAD APPLE. ## # A tibble: 5,408 × 8 ## symbol date open high low close volume adjusted ## ## 1 AAPL 2013-01-02 19.8 19.8 19.3 19.6 560518000 16.8 ## 2 AAPL 2013-01-03 19.6 19.6 19.3 19.4 352965200 16.6 ## 3 AAPL 2013-01-04 19.2 19.2 18.8 18.8 594333600 16.1 ## 4 AAPL 2013-01-07 18.6 18.9 18.4 18.7 484156400 16.0 ## 5 AAPL 2013-01-08 18.9 19.0 18.6 18.8 458707200 16.1 ## 6 AAPL 2013-01-09 18.7 18.8 18.4 18.5 407604400 15.8 ## 7 AAPL 2013-01-10 18.9 18.9 18.4 18.7 601146000 16.0 ## 8 AAPL 2013-01-11 18.6 18.8 18.5 18.6 350506800 15.9 ## 9 AAPL 2013-01-14 18.0 18.1 17.8 17.9 734207600 15.3 ## 10 AAPL 2013-01-15 17.8 17.8 17.3 17.4 876772400 14.9 ## # ℹ 5,398 more rows c(\"AAPL\", \"GOOG\", \"BAD APPLE\") %>% tq_get(get = \"stock.prices\", complete_cases = FALSE) ## Warning: There was 1 warning in `dplyr::mutate()`. ## ℹ In argument: `data.. = purrr::map(...)`. ## Caused by warning: ## ! x = 'BAD APPLE', get = 'stock.prices': Error in getSymbols.yahoo(Symbols = \"BAD APPLE\", env = , : Unable to import \"BAD APPLE\". ## URL using bad/illegal format or missing URL ## # A tibble: 5,409 × 8 ## symbol date open high low close volume adjusted ## ## 1 AAPL 2013-01-02 19.8 19.8 19.3 19.6 560518000 16.8 ## 2 AAPL 2013-01-03 19.6 19.6 19.3 19.4 352965200 16.6 ## 3 AAPL 2013-01-04 19.2 19.2 18.8 18.8 594333600 16.1 ## 4 AAPL 2013-01-07 18.6 18.9 18.4 18.7 484156400 16.0 ## 5 AAPL 2013-01-08 18.9 19.0 18.6 18.8 458707200 16.1 ## 6 AAPL 2013-01-09 18.7 18.8 18.4 18.5 407604400 15.8 ## 7 AAPL 2013-01-10 18.9 18.9 18.4 18.7 601146000 16.0 ## 8 AAPL 2013-01-11 18.6 18.8 18.5 18.6 350506800 15.9 ## 9 AAPL 2013-01-14 18.0 18.1 17.8 17.9 734207600 15.3 ## 10 AAPL 2013-01-15 17.8 17.8 17.3 17.4 876772400 14.9 ## # ℹ 5,399 more rows"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"overview","dir":"Articles","previous_headings":"","what":"Overview","title":"Charting with tidyquant","text":"tidyquant package includes charting tools assist users developing quick visualizations ggplot2 using grammar graphics format workflow. currently three primary geometry (geom) categories one coordinate manipulation (coord) category within tidyquant: Chart Types: Two chart type visualizations available using geom_barchart geom_candlestick. Moving Averages: Seven moving average visualizations available using geom_ma. Bollinger Bands: Bollinger bands can visualized using geom_bbands. BBand moving average can one seven available Moving Averages. Zooming Date Ranges: Two coord functions available (coord_x_date coord_x_datetime), prevent data loss zooming specific regions chart. important using moving average Bollinger band geoms.","code":""},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"prerequisites","dir":"Articles","previous_headings":"","what":"Prerequisites","title":"Charting with tidyquant","text":"Load tidyquant package get started. following stock data used examples. Use tq_get get stock prices. end date parameter used setting date limits throughout examples. AAPL_range_60 used adjust zoom plots.","code":"# Loads tidyquant, lubridate, xts, quantmod, TTR, and PerformanceAnalytics library(lubridate) library(dplyr) library(ggplot2) library(tidyquant) # Use FANG data set # Get AAPL and AMZN Stock Prices AAPL <- tq_get(\"AAPL\", get = \"stock.prices\", from = \"2015-09-01\", to = \"2016-12-31\") AMZN <- tq_get(\"AMZN\", get = \"stock.prices\", from = \"2000-01-01\", to = \"2016-12-31\") end <- as_date(\"2016-12-31\") end ## [1] \"2016-12-31\" aapl_range_60_tbl <- AAPL %>% tail(60) %>% summarise( max_high = max(high), min_low = min(low) ) aapl_range_60_tbl ## # A tibble: 1 × 2 ## max_high min_low ## ## 1 29.7 26.0"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"chart-types","dir":"Articles","previous_headings":"","what":"Chart Types","title":"Charting with tidyquant","text":"Financial charts provide visual cues open, high, low, close prices. following chart geoms available: Bar Chart: Use geom_barchart Candlestick Chart: Use geom_candlestick","code":""},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"line-chart","dir":"Articles","previous_headings":"Chart Types","what":"Line Chart","title":"Charting with tidyquant","text":"visualize bar charts candlestick charts using tidyquant geoms, let’s visualize stock prices simple line chart get sense “grammar graphics” workflow. done using geom_line ggplot2 package. workflow begins stock data, uses pipe operator (%>%) send ggplot() function. primary features controlling chart aesthetic arguments: used add data chart way aes() function. added inside ggplot() function, aesthetic arguments available underlying layers. Alternatively, aesthetic arguments can applied geom individually, typically minimized practice duplicates code. set aesthetic arguments, x = date y = close, chart closing price versus date. geom_line() function inherits aesthetic arguments ggplot() function produces line chart. Labels added separately using labs() function. Thus, chart built ground starting data progressively adding geoms, labels, coordinates / scales attributes create final chart. enables maximum flexibility wherein analyst can create complex charts using “grammar graphics”.","code":"AAPL %>% ggplot(aes(x = date, y = close)) + geom_line() + labs(title = \"AAPL Line Chart\", y = \"Closing Price\", x = \"\") + theme_tq()"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"bar-chart","dir":"Articles","previous_headings":"Chart Types","what":"Bar Chart","title":"Charting with tidyquant","text":"Visualizing bar chart simple replacing geom_line geom_barchart ggplot workflow. bar chart uses open, high, low, close prices visualization, need specify part aesthetic arguments, aes(). can internal geom ggplot() function. zoom specific sections using coord_x_date, xlim ylim arguments specified c(start, end) focus specific region chart. xlim, ’ll use lubridate convert character date date class, subtract six weeks using weeks() function. ylim zoom prices range 100 120. colors can modified using colour_up colour_down arguments, parameters size can used control appearance.","code":"AAPL %>% ggplot(aes(x = date, y = close)) + geom_barchart(aes(open = open, high = high, low = low, close = close)) + labs(title = \"AAPL Bar Chart\", y = \"Closing Price\", x = \"\") + theme_tq() AAPL %>% ggplot(aes(x = date, y = close)) + geom_barchart(aes(open = open, high = high, low = low, close = close)) + labs(title = \"AAPL Bar Chart\", subtitle = \"Zoomed in using coord_x_date\", y = \"Closing Price\", x = \"\") + coord_x_date(xlim = c(end - weeks(6), end), ylim = c(aapl_range_60_tbl$min_low, aapl_range_60_tbl$max_high)) + theme_tq() AAPL %>% ggplot(aes(x = date, y = close)) + geom_barchart(aes(open = open, high = high, low = low, close = close), colour_up = \"darkgreen\", colour_down = \"darkred\", size = 1) + labs(title = \"AAPL Bar Chart\", subtitle = \"Zoomed in, Experimenting with Formatting\", y = \"Closing Price\", x = \"\") + coord_x_date(xlim = c(end - lubridate::weeks(6), end), c(aapl_range_60_tbl$min_low, aapl_range_60_tbl$max_high)) + theme_tq()"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"candlestick-chart","dir":"Articles","previous_headings":"Chart Types","what":"Candlestick Chart","title":"Charting with tidyquant","text":"Creating candlestick chart similar process bar chart. Using geom_candlestick, can insert ggplot workflow. zoom specific sections using coord_x_date. colors can modified using colour_up colour_down, control line color, fill_up fill_down, control rectangle fills.","code":"AAPL %>% ggplot(aes(x = date, y = close)) + geom_candlestick(aes(open = open, high = high, low = low, close = close)) + labs(title = \"AAPL Candlestick Chart\", y = \"Closing Price\", x = \"\") + theme_tq() AAPL %>% ggplot(aes(x = date, y = close)) + geom_candlestick(aes(open = open, high = high, low = low, close = close)) + labs(title = \"AAPL Candlestick Chart\", subtitle = \"Zoomed in using coord_x_date\", y = \"Closing Price\", x = \"\") + coord_x_date(xlim = c(end - weeks(6), end), c(aapl_range_60_tbl$min_low, aapl_range_60_tbl$max_high)) + theme_tq() AAPL %>% ggplot(aes(x = date, y = close)) + geom_candlestick(aes(open = open, high = high, low = low, close = close), colour_up = \"darkgreen\", colour_down = \"darkred\", fill_up = \"darkgreen\", fill_down = \"darkred\") + labs(title = \"AAPL Candlestick Chart\", subtitle = \"Zoomed in, Experimenting with Formatting\", y = \"Closing Price\", x = \"\") + coord_x_date(xlim = c(end - weeks(6), end), c(aapl_range_60_tbl$min_low, aapl_range_60_tbl$max_high)) + theme_tq()"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"charting-multiple-securities","dir":"Articles","previous_headings":"Chart Types","what":"Charting Multiple Securities","title":"Charting with tidyquant","text":"can use facet_wrap visualize multiple stocks time. adding group aesthetic main ggplot() function combining facet_wrap() function end ggplot workflow, four “FANG” stocks can viewed simultaneously. may notice odd filter() call call ggplot(). ’ll discuss next. note --bounds data (“clipping”), particularly important faceting charting moving averages: coord_x_date coordinate function designed zoom specific sections chart without “clipping” data outside view. contrast scale_x_date, removes --bounds data charting. normal circumstances clipping big deal (actually helpful scaling y-axis), financial applications users want chart rolling/moving averages, lags, etc depend data outside view port. need --bounds data, trade-charting: much --bounds data distorts scale y-axis, little get moving average. optimal method include “just enough” --bounds data get chart want. FANG data filtered date double number moving-average days (2 * n) previous start date. yields nice y-axis scale still allows us create moving average line using geom_ma.","code":"start <- end - weeks(6) FANG %>% dplyr::filter(date >= start - days(2 * 15)) %>% ggplot(aes(x = date, y = close, group = symbol)) + geom_candlestick(aes(open = open, high = high, low = low, close = close)) + labs(title = \"FANG Candlestick Chart\", subtitle = \"Experimenting with Mulitple Stocks\", y = \"Closing Price\", x = \"\") + coord_x_date(xlim = c(start, end)) + facet_wrap(~ symbol, ncol = 2, scale = \"free_y\") + theme_tq() start <- end - weeks(6) FANG %>% dplyr::filter(date >= start - days(2 * 15)) %>% ggplot(aes(x = date, y = close, group = symbol)) + geom_candlestick(aes(open = open, high = high, low = low, close = close)) + geom_ma(ma_fun = SMA, n = 15, color = \"darkblue\", size = 1) + labs(title = \"FANG Candlestick Chart\", subtitle = \"Experimenting with Mulitple Stocks\", y = \"Closing Price\", x = \"\") + coord_x_date(xlim = c(start, end)) + facet_wrap(~ symbol, ncol = 2, scale = \"free_y\") + theme_tq()"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"visualizing-trends","dir":"Articles","previous_headings":"","what":"Visualizing Trends","title":"Charting with tidyquant","text":"Moving averages critical evaluating time-series trends. tidyquant includes geoms enable “rapid prototyping” quickly visualize signals using moving averages Bollinger bands.","code":""},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"moving-averages","dir":"Articles","previous_headings":"Visualizing Trends","what":"Moving Averages","title":"Charting with tidyquant","text":"following moving averages available: Simple moving averages (SMA) Exponential moving averages (EMA) Weighted moving averages (WMA) Double exponential moving averages (DEMA) Zero-lag exponential moving averages (ZLEMA) Volume-weighted moving averages (VWMA) (also known VWAP) Elastic, volume-weighted moving averages (EVWMA) (also known MVWAP) Moving averages applied added layer chart geom_ma function. geom wrapper underlying moving average functions TTR package: SMA, EMA, WMA, DEMA, ZLEMA, VWMA, EVWMA. ’s use geom: Select moving average function, ma_fun, want apply. Determine function arguments need passed ma_fun. can investigate underlying function searching ?TTR::SMA. Determine aesthetic arguments pass. typically aes(x = date, y = close). volume-weighted functions require volume argument aes() function. Apply moving average geom ggplot workflow. Important Note: zooming section, use coord_x_date coord_x_datetime prevent --bounds data loss. use scale_x_date, affect moving average calculation. Refer Charting Multiple Securities.","code":""},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"example-1-charting-the-50-day-and-200-day-simple-moving-average","dir":"Articles","previous_headings":"Visualizing Trends > Moving Averages","what":"Example 1: Charting the 50-day and 200-day simple moving average","title":"Charting with tidyquant","text":"want apply SMA, research TTR function see accepts, n, number periods average . see aesthetics required x, date, y, price. Since already main ggplot() function, don’t need add aesthetics geom. apply moving average geoms candlestick geom overlay moving averages top candlesticks. add two moving average calls, one 50-day 200-day. add color = \"red\" linetype = 5 distinguish 200-day 50-day.","code":"AAPL %>% ggplot(aes(x = date, y = close)) + geom_candlestick(aes(open = open, high = high, low = low, close = close)) + geom_ma(ma_fun = SMA, n = 50, linetype = 5, size = 1.25) + geom_ma(ma_fun = SMA, n = 200, color = \"red\", size = 1.25) + labs(title = \"AAPL Candlestick Chart\", subtitle = \"50 and 200-Day SMA\", y = \"Closing Price\", x = \"\") + coord_x_date(xlim = c(end - weeks(24), end), c(aapl_range_60_tbl$min_low * 0.9, aapl_range_60_tbl$max_high)) + theme_tq()"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"example-2-charting-exponential-moving-averages","dir":"Articles","previous_headings":"Visualizing Trends > Moving Averages","what":"Example 2: Charting exponential moving averages","title":"Charting with tidyquant","text":"want EMA, research TTR function see accepts, n, number periods average , wilder Boolean, ratio arguments. use wilder = TRUE go default ratio arg. see aesthetics required x, date, y, price. Since already main ggplot() function, don’t need modify geom. ready apply bar chart geom.","code":"AAPL %>% ggplot(aes(x = date, y = close)) + geom_barchart(aes(open = open, high = high, low = low, close = close)) + geom_ma(ma_fun = EMA, n = 50, wilder = TRUE, linetype = 5, size = 1.25) + geom_ma(ma_fun = EMA, n = 200, wilder = TRUE, color = \"red\", size = 1.25) + labs(title = \"AAPL Bar Chart\", subtitle = \"50 and 200-Day EMA\", y = \"Closing Price\", x = \"\") + coord_x_date(xlim = c(end - weeks(24), end), c(aapl_range_60_tbl$min_low * 0.9, aapl_range_60_tbl$max_high)) + theme_tq()"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"example-3-charting-moving-averages-for-multiple-stocks-at-once","dir":"Articles","previous_headings":"Visualizing Trends > Moving Averages","what":"Example 3: Charting moving averages for multiple stocks at once","title":"Charting with tidyquant","text":"’ll double using volume-weighted average (VWMA) apply FANG stocks . Since VWMA volume-weighted function, need add volume aesthetic. viewing multiple stocks, add group aesthetic setting symbol column contains FANG stock symbols. facet wrap added end create four charts instead one overlayed chart.","code":"start <- end - weeks(6) FANG %>% dplyr::filter(date >= start - days(2 * 50)) %>% ggplot(aes(x = date, y = close, volume = volume, group = symbol)) + geom_candlestick(aes(open = open, high = high, low = low, close = close)) + geom_ma(ma_fun = VWMA, n = 15, wilder = TRUE, linetype = 5) + geom_ma(ma_fun = VWMA, n = 50, wilder = TRUE, color = \"red\") + labs(title = \"FANG Bar Chart\", subtitle = \"50 and 200-Day EMA, Experimenting with Multiple Stocks\", y = \"Closing Price\", x = \"\") + coord_x_date(xlim = c(start, end)) + facet_wrap(~ symbol, ncol = 2, scales = \"free_y\") + theme_tq()"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"bollinger-bands","dir":"Articles","previous_headings":"Visualizing Trends","what":"Bollinger Bands","title":"Charting with tidyquant","text":"Bollinger Bands used visualize volatility plotting range around moving average typically two standard deviations . use moving average, geom_bbands function works almost identically geom_ma. seven moving averages compatible. main difference addition standard deviation, sd, argument 2 default, high, low close aesthetics required calculate bands. Refer Moving Averages detailed discussion moving averages available. Important Note: zooming section, use coord_x_date coord_x_datetime prevent --bounds data loss. use scale_x_date, affect moving average calculation. Refer Charting Multiple Securities.","code":""},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"example-1-applying-bbands-using-a-sma","dir":"Articles","previous_headings":"Visualizing Trends > Bollinger Bands","what":"Example 1: Applying BBands using a SMA","title":"Charting with tidyquant","text":"Let’s basic example add Bollinger Bands using simple moving average. candlestick geom BBands geom use high, low close prices, move aesthetics main ggplot() function avoid duplication. add BBands candlestick geom overlay BBands top.","code":"AAPL %>% ggplot(aes(x = date, y = close, open = open, high = high, low = low, close = close)) + geom_candlestick() + geom_bbands(ma_fun = SMA, sd = 2, n = 20) + labs(title = \"AAPL Candlestick Chart\", subtitle = \"BBands with SMA Applied\", y = \"Closing Price\", x = \"\") + coord_x_date(xlim = c(end - weeks(24), end), ylim = c(aapl_range_60_tbl$min_low * 0.85, aapl_range_60_tbl$max_high) * 1.05) + theme_tq()"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"example-2-modifying-the-appearance-of-bollinger-bands","dir":"Articles","previous_headings":"Visualizing Trends > Bollinger Bands","what":"Example 2: Modifying the appearance of Bollinger Bands","title":"Charting with tidyquant","text":"appearance can modified using color_ma, color_bands, alpha, fill arguments. ’s plot Example 1, new formatting applied BBands.","code":"AAPL %>% ggplot(aes(x = date, y = close, open = open, high = high, low = low, close = close)) + geom_candlestick() + geom_bbands(ma_fun = SMA, sd = 2, n = 20, linetype = 4, size = 1, alpha = 0.2, fill = palette_light()[[1]], color_bands = palette_light()[[1]], color_ma = palette_light()[[2]]) + labs(title = \"AAPL Candlestick Chart\", subtitle = \"BBands with SMA Applied, Experimenting with Formatting\", y = \"Closing Price\", x = \"\") + coord_x_date(xlim = c(end - weeks(24), end), ylim = c(aapl_range_60_tbl$min_low * 0.85, aapl_range_60_tbl$max_high) * 1.05) + theme_tq()"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"example-3-adding-bbands-to-multiple-stocks","dir":"Articles","previous_headings":"Visualizing Trends > Bollinger Bands","what":"Example 3: Adding BBands to multiple stocks","title":"Charting with tidyquant","text":"process similar charting moving averages multiple stocks.","code":"start <- end - weeks(24) FANG %>% dplyr::filter(date >= start - days(2 * 20)) %>% ggplot(aes(x = date, y = close, open = open, high = high, low = low, close = close, group = symbol)) + geom_barchart() + geom_bbands(ma_fun = SMA, sd = 2, n = 20, linetype = 5) + labs(title = \"FANG Bar Chart\", subtitle = \"BBands with SMA Applied, Experimenting with Multiple Stocks\", y = \"Closing Price\", x = \"\") + coord_x_date(xlim = c(start, end)) + facet_wrap(~ symbol, ncol = 2, scales = \"free_y\") + theme_tq()"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"ggplot2-functionality","dir":"Articles","previous_headings":"","what":"ggplot2 Functionality","title":"Charting with tidyquant","text":"Base ggplot2 ton functionality can useful analyzing financial data. ’ll go brief examples using Amazon (AMZN).","code":""},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"example-1-log-scale-with-scale_y_log10","dir":"Articles","previous_headings":"ggplot2 Functionality","what":"Example 1: Log Scale with scale_y_log10","title":"Charting with tidyquant","text":"ggplot2 scale_y_log10() function scale y-axis logarithmic scale. extremely helpful tends expose linear trends can analyzed. Continuous Scale: Log Scale:","code":"AMZN %>% ggplot(aes(x = date, y = adjusted)) + geom_line(color = palette_light()[[1]]) + scale_y_continuous() + labs(title = \"AMZN Line Chart\", subtitle = \"Continuous Scale\", y = \"Closing Price\", x = \"\") + theme_tq() AMZN %>% ggplot(aes(x = date, y = adjusted)) + geom_line(color = palette_light()[[1]]) + scale_y_log10() + labs(title = \"AMZN Line Chart\", subtitle = \"Log Scale\", y = \"Closing Price\", x = \"\") + theme_tq()"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"example-2-regression-trendlines-with-geom_smooth","dir":"Articles","previous_headings":"ggplot2 Functionality","what":"Example 2: Regression trendlines with geom_smooth","title":"Charting with tidyquant","text":"can apply trend line quickly adding geom_smooth() function workflow. function several prediction methods including linear (\"lm\") loess (\"loess\") name . Linear:","code":"AMZN %>% ggplot(aes(x = date, y = adjusted)) + geom_line(color = palette_light()[[1]]) + scale_y_log10() + geom_smooth(method = \"lm\") + labs(title = \"AMZN Line Chart\", subtitle = \"Log Scale, Applying Linear Trendline\", y = \"Adjusted Closing Price\", x = \"\") + theme_tq()"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"example-3-charting-volume-with-geom_segment","dir":"Articles","previous_headings":"ggplot2 Functionality","what":"Example 3: Charting volume with geom_segment","title":"Charting with tidyquant","text":"can use geom_segment() function chart daily volume, uses xy points beginning end line. Using aesthetic color argument, color based value volume make data stick . , can zoom specific region. Using scale_color_gradient can quickly visualize high low points, using geom_smooth can see trend.","code":"AMZN %>% ggplot(aes(x = date, y = volume)) + geom_segment(aes(xend = date, yend = 0, color = volume)) + geom_smooth(method = \"loess\", se = FALSE) + labs(title = \"AMZN Volume Chart\", subtitle = \"Charting Daily Volume\", y = \"Volume\", x = \"\") + theme_tq() + theme(legend.position = \"none\") start <- end - weeks(24) AMZN %>% dplyr::filter(date >= start - days(50)) %>% ggplot(aes(x = date, y = volume)) + geom_segment(aes(xend = date, yend = 0, color = volume)) + geom_smooth(method = \"loess\", se = FALSE) + labs(title = \"AMZN Bar Chart\", subtitle = \"Charting Daily Volume, Zooming In\", y = \"Volume\", x = \"\") + coord_x_date(xlim = c(start, end)) + scale_color_gradient(low = \"red\", high = \"darkblue\") + theme_tq() + theme(legend.position = \"none\")"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"themes","dir":"Articles","previous_headings":"","what":"Themes","title":"Charting with tidyquant","text":"tidyquant package comes three themes help quickly customize financial charts: Light: theme_tq() + scale_color_tq() + scale_fill_tq() Dark: theme_tq_dark() + scale_color_tq(theme = \"dark\") + scale_fill_tq(theme = \"dark\") Green: theme_tq_green() + scale_color_tq(theme = \"green\") + scale_fill_tq(theme = \"green\")","code":""},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"dark","dir":"Articles","previous_headings":"Themes","what":"Dark","title":"Charting with tidyquant","text":"","code":"n_mavg <- 50 # Number of periods (days) for moving average FANG %>% dplyr::filter(date >= start - days(2 * n_mavg)) %>% ggplot(aes(x = date, y = close, color = symbol)) + geom_line(linewidth = 1) + geom_ma(n = 15, color = \"darkblue\", size = 1) + geom_ma(n = n_mavg, color = \"red\", size = 1) + labs(title = \"Dark Theme\", x = \"\", y = \"Closing Price\") + coord_x_date(xlim = c(start, end)) + facet_wrap(~ symbol, scales = \"free_y\") + theme_tq_dark() + scale_color_tq(theme = \"dark\") + scale_y_continuous(labels = scales::label_dollar())"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"overview","dir":"Articles","previous_headings":"","what":"Overview","title":"Performance Analysis with tidyquant","text":"Financial asset (individual stocks, securities, etc) portfolio (groups stocks, securities, etc) performance analysis deep field wide range theories methods analyzing risk versus reward. PerformanceAnalytics package consolidates functions compute many widely used performance metrics. tidquant integrates functionality can used scale using split, apply, combine framework within tidyverse. Two primary functions integrate performance analysis functionality: tq_performance implements performance analysis functions tidy way, enabling scaling analysis using split, apply, combine framework. tq_portfolio provides useful tool set aggregating group individual asset returns one many portfolios. vignette aims cover three aspects performance analysis: general workflow go start finish asset portfolio level available techniques implement workflow implemented customize tq_portfolio tq_performance using ... parameter","code":""},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"key-concepts","dir":"Articles","previous_headings":"","what":"1.0 Key Concepts","title":"Performance Analysis with tidyquant","text":"important concept performance analysis based statistical properties returns (prices). result, package uses inputs time-based returns opposed stock prices. arguments change Ra asset returns Rb baseline returns. ’ll go get returns Workflow section. Another important concept baseline. baseline measuring performance . baseline can anything, many cases ’s representative average investment might perform little effort. Often indexes S&P500 used general market performance. times specific Exchange Traded Funds (ETFs) used SPDR Technology ETF (XLK). important concept measure asset performance (Ra) baseline (Rb). Now quick tutorial show PerformanceAnalytics package integration.","code":""},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"quick-example","dir":"Articles","previous_headings":"","what":"2.0 Quick Example","title":"Performance Analysis with tidyquant","text":"One widely used risk return metrics Capital Asset Pricing Model (CAPM). According Investopedia: capital asset pricing model (CAPM) model describes relationship systematic risk expected return assets, particularly stocks. CAPM widely used throughout finance pricing risky securities, generating expected returns assets given risk assets calculating costs capital. ’ll use PerformanceAnalytics function, table.CAPM, evaluate returns several technology stocks SPDR Technology ETF (XLK). First, load tidyquant package. Second, get stock returns stocks wish evaluate. use tq_get get stock prices Yahoo Finance, group_by group stock prices related symbol, tq_transmute retrieve period returns monthly periodicity using “adjusted” stock prices (adjusted stock splits, can throw returns, affecting performance analysis). Review output see three groups symbols indicating data grouped appropriately. Next, get baseline prices. ’ll use XLK. Note need group just getting one data set. Now, combine two data sets using “date” field using left_join dplyr package. Review results see still three groups returns, columns “Ra” “Rb” side--side. Finally, can retrieve performance metrics using tq_performance(). can use tq_performance_fun_options() see full list compatible performance functions. can quickly isolate attributes, alpha, measure growth, beta, measure risk. tidyquant ’s efficient easy get CAPM information! , ’s just one 129 available functions analyze stock portfolio return performance. Just use tq_performance_fun_options() see full list.","code":"library(dplyr) library(ggplot2) library(tidyquant) Ra <- c(\"AAPL\", \"GOOG\", \"NFLX\") %>% tq_get(get = \"stock.prices\", from = \"2010-01-01\", to = \"2015-12-31\") %>% group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"monthly\", col_rename = \"Ra\") Ra ## # A tibble: 216 × 3 ## # Groups: symbol [3] ## symbol date Ra ## ## 1 AAPL 2010-01-29 -0.103 ## 2 AAPL 2010-02-26 0.0654 ## 3 AAPL 2010-03-31 0.148 ## 4 AAPL 2010-04-30 0.111 ## 5 AAPL 2010-05-28 -0.0161 ## 6 AAPL 2010-06-30 -0.0208 ## 7 AAPL 2010-07-30 0.0227 ## 8 AAPL 2010-08-31 -0.0550 ## 9 AAPL 2010-09-30 0.167 ## 10 AAPL 2010-10-29 0.0607 ## # ℹ 206 more rows Rb <- \"XLK\" %>% tq_get(get = \"stock.prices\", from = \"2010-01-01\", to = \"2015-12-31\") %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"monthly\", col_rename = \"Rb\") Rb ## # A tibble: 72 × 2 ## date Rb ## ## 1 2010-01-29 -0.0993 ## 2 2010-02-26 0.0348 ## 3 2010-03-31 0.0684 ## 4 2010-04-30 0.0126 ## 5 2010-05-28 -0.0748 ## 6 2010-06-30 -0.0540 ## 7 2010-07-30 0.0745 ## 8 2010-08-31 -0.0561 ## 9 2010-09-30 0.117 ## 10 2010-10-29 0.0578 ## # ℹ 62 more rows RaRb <- left_join(Ra, Rb, by = c(\"date\" = \"date\")) RaRb ## # A tibble: 216 × 4 ## # Groups: symbol [3] ## symbol date Ra Rb ## ## 1 AAPL 2010-01-29 -0.103 -0.0993 ## 2 AAPL 2010-02-26 0.0654 0.0348 ## 3 AAPL 2010-03-31 0.148 0.0684 ## 4 AAPL 2010-04-30 0.111 0.0126 ## 5 AAPL 2010-05-28 -0.0161 -0.0748 ## 6 AAPL 2010-06-30 -0.0208 -0.0540 ## 7 AAPL 2010-07-30 0.0227 0.0745 ## 8 AAPL 2010-08-31 -0.0550 -0.0561 ## 9 AAPL 2010-09-30 0.167 0.117 ## 10 AAPL 2010-10-29 0.0607 0.0578 ## # ℹ 206 more rows RaRb_capm <- RaRb %>% tq_performance(Ra = Ra, Rb = Rb, performance_fun = table.CAPM) RaRb_capm ## # A tibble: 3 × 13 ## # Groups: symbol [3] ## symbol ActivePremium Alpha AnnualizedAlpha Beta `Beta-` `Beta+` Correlation ## ## 1 AAPL 0.119 0.0089 0.112 1.11 0.578 1.04 0.659 ## 2 GOOG 0.034 0.0028 0.034 1.14 1.39 1.16 0.644 ## 3 NFLX 0.447 0.053 0.859 0.384 -1.52 0.0045 0.0817 ## # ℹ 5 more variables: `Correlationp-value` , InformationRatio , ## # `R-squared` , TrackingError , TreynorRatio RaRb_capm %>% select(symbol, Alpha, Beta) ## # A tibble: 3 × 3 ## # Groups: symbol [3] ## symbol Alpha Beta ## ## 1 AAPL 0.0089 1.11 ## 2 GOOG 0.0028 1.14 ## 3 NFLX 0.053 0.384"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"workflow","dir":"Articles","previous_headings":"","what":"3.0 Workflow","title":"Performance Analysis with tidyquant","text":"general workflow shown diagram . ’ll step workflow first group individual assets (stocks) portfolios stocks. Performance Analysis Workflow","code":""},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"individual-assets","dir":"Articles","previous_headings":"3.0 Workflow","what":"3.1 Individual Assets","title":"Performance Analysis with tidyquant","text":"Individual assets simplest form analysis portfolio aggregation (Step 3A). ’ll re-“Quick Example” time getting Sharpe Ratio, measure reward--risk. get started let’s find performance function want use PerformanceAnalytics. Searching tq_performance_fun_options, can see SharpeRatio available. Type ?SharpeRatio, can see arguments : can actually skip baseline path function require Rb. function takes R, passed using Ra tq_performance(Ra, Rb, performance_fun, ...). little bit foresight saves us work.","code":"args(SharpeRatio) ## function (R, Rf = 0, p = 0.95, FUN = c(\"StdDev\", \"VaR\", \"ES\"), ## weights = NULL, annualize = FALSE, SE = FALSE, SE.control = NULL, ## ...) ## NULL"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"step-1a-get-stock-prices","dir":"Articles","previous_headings":"3.0 Workflow > 3.1 Individual Assets","what":"Step 1A: Get stock prices","title":"Performance Analysis with tidyquant","text":"Use tq_get() get stock prices.","code":"stock_prices <- c(\"AAPL\", \"GOOG\", \"NFLX\") %>% tq_get(get = \"stock.prices\", from = \"2010-01-01\", to = \"2015-12-31\") stock_prices ## # A tibble: 4,527 × 8 ## symbol date open high low close volume adjusted ## ## 1 AAPL 2010-01-04 7.62 7.66 7.59 7.64 493729600 6.49 ## 2 AAPL 2010-01-05 7.66 7.70 7.62 7.66 601904800 6.50 ## 3 AAPL 2010-01-06 7.66 7.69 7.53 7.53 552160000 6.40 ## 4 AAPL 2010-01-07 7.56 7.57 7.47 7.52 477131200 6.38 ## 5 AAPL 2010-01-08 7.51 7.57 7.47 7.57 447610800 6.43 ## 6 AAPL 2010-01-11 7.60 7.61 7.44 7.50 462229600 6.37 ## 7 AAPL 2010-01-12 7.47 7.49 7.37 7.42 594459600 6.30 ## 8 AAPL 2010-01-13 7.42 7.53 7.29 7.52 605892000 6.39 ## 9 AAPL 2010-01-14 7.50 7.52 7.47 7.48 432894000 6.35 ## 10 AAPL 2010-01-15 7.53 7.56 7.35 7.35 594067600 6.24 ## # ℹ 4,517 more rows"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"step-2a-mutate-to-returns","dir":"Articles","previous_headings":"3.0 Workflow > 3.1 Individual Assets","what":"Step 2A: Mutate to returns","title":"Performance Analysis with tidyquant","text":"Using tidyverse split, apply, combine framework, can mutate groups stocks first “grouping” group_by applying mutating function using tq_transmute. use quantmod function periodReturn mutating function. pass along arguments period = \"monthly\" return results monthly periodicity. Last, use col_rename argument rename output column.","code":"stock_returns_monthly <- stock_prices %>% group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"monthly\", col_rename = \"Ra\") stock_returns_monthly ## # A tibble: 216 × 3 ## # Groups: symbol [3] ## symbol date Ra ## ## 1 AAPL 2010-01-29 -0.103 ## 2 AAPL 2010-02-26 0.0654 ## 3 AAPL 2010-03-31 0.148 ## 4 AAPL 2010-04-30 0.111 ## 5 AAPL 2010-05-28 -0.0161 ## 6 AAPL 2010-06-30 -0.0208 ## 7 AAPL 2010-07-30 0.0227 ## 8 AAPL 2010-08-31 -0.0550 ## 9 AAPL 2010-09-30 0.167 ## 10 AAPL 2010-10-29 0.0607 ## # ℹ 206 more rows"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"step-3a-aggregate-to-portfolio-returns-skipped","dir":"Articles","previous_headings":"3.0 Workflow > 3.1 Individual Assets","what":"Step 3A: Aggregate to Portfolio Returns (Skipped)","title":"Performance Analysis with tidyquant","text":"Step 3A can skipped interested Sharpe Ratio individual stocks (portfolio). Step 3B can also skipped SharpeRatio function PerformanceAnalytics require baseline.","code":""},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"step-4-analyze-performance","dir":"Articles","previous_headings":"3.0 Workflow > 3.1 Individual Assets","what":"Step 4: Analyze Performance","title":"Performance Analysis with tidyquant","text":"last step apply SharpeRatio function groups stock returns. using tq_performance() arguments Ra = Ra, Rb = NULL (required), performance_fun = SharpeRatio. can also pass arguments SharpeRatio function Rf, p, FUN, annualize. just use defaults example. Now Sharpe Ratio three stocks. want adjust parameters function? can just add arguments underlying function.","code":"stock_returns_monthly %>% tq_performance( Ra = Ra, Rb = NULL, performance_fun = SharpeRatio ) ## # A tibble: 3 × 4 ## # Groups: symbol [3] ## symbol `ESSharpe(Rf=0%,p=95%)` StdDevSharpe(Rf=0%,p=9…¹ VaRSharpe(Rf=0%,p=95…² ## ## 1 AAPL 0.173 0.292 0.218 ## 2 GOOG 0.129 0.203 0.157 ## 3 NFLX 0.237 0.284 0.272 ## # ℹ abbreviated names: ¹​`StdDevSharpe(Rf=0%,p=95%)`, ²​`VaRSharpe(Rf=0%,p=95%)` stock_returns_monthly %>% tq_performance( Ra = Ra, Rb = NULL, performance_fun = SharpeRatio, Rf = 0.03 / 12, p = 0.99 ) ## # A tibble: 3 × 4 ## # Groups: symbol [3] ## symbol `ESSharpe(Rf=0.2%,p=99%)` StdDevSharpe(Rf=0.2%…¹ VaRSharpe(Rf=0.2%,p=…² ## ## 1 AAPL 0.116 0.258 0.134 ## 2 GOOG 0.0826 0.170 0.0998 ## 3 NFLX 0.115 0.272 0.142 ## # ℹ abbreviated names: ¹​`StdDevSharpe(Rf=0.2%,p=99%)`, ## # ²​`VaRSharpe(Rf=0.2%,p=99%)`"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"portfolios-asset-groups","dir":"Articles","previous_headings":"3.0 Workflow","what":"3.2 Portfolios (Asset Groups)","title":"Performance Analysis with tidyquant","text":"Portfolios slightly complicated now dealing groups assets versus individual stocks, need aggregate weighted returns. Fortunately, one extra step tidyquant using tq_portfolio().","code":""},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"single-portfolio","dir":"Articles","previous_headings":"3.0 Workflow > 3.2 Portfolios (Asset Groups)","what":"Single Portfolio","title":"Performance Analysis with tidyquant","text":"Let’s recreate CAPM analysis “Quick Example” time comparing portfolio technology stocks SPDR Technology ETF (XLK).","code":""},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"steps-1a-and-2a-asset-period-returns","dir":"Articles","previous_headings":"3.0 Workflow > 3.2 Portfolios (Asset Groups) > Single Portfolio","what":"Steps 1A and 2A: Asset Period Returns","title":"Performance Analysis with tidyquant","text":"previously get monthly returns groups individual stock prices. use split, apply, combine framework using workflow tq_get, group_by, tq_transmute.","code":"stock_returns_monthly <- c(\"AAPL\", \"GOOG\", \"NFLX\") %>% tq_get(get = \"stock.prices\", from = \"2010-01-01\", to = \"2015-12-31\") %>% group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"monthly\", col_rename = \"Ra\") stock_returns_monthly ## # A tibble: 216 × 3 ## # Groups: symbol [3] ## symbol date Ra ## ## 1 AAPL 2010-01-29 -0.103 ## 2 AAPL 2010-02-26 0.0654 ## 3 AAPL 2010-03-31 0.148 ## 4 AAPL 2010-04-30 0.111 ## 5 AAPL 2010-05-28 -0.0161 ## 6 AAPL 2010-06-30 -0.0208 ## 7 AAPL 2010-07-30 0.0227 ## 8 AAPL 2010-08-31 -0.0550 ## 9 AAPL 2010-09-30 0.167 ## 10 AAPL 2010-10-29 0.0607 ## # ℹ 206 more rows"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"steps-1b-and-2b-baseline-period-returns","dir":"Articles","previous_headings":"3.0 Workflow > 3.2 Portfolios (Asset Groups) > Single Portfolio","what":"Steps 1B and 2B: Baseline Period Returns","title":"Performance Analysis with tidyquant","text":"also done previously.","code":"baseline_returns_monthly <- \"XLK\" %>% tq_get(get = \"stock.prices\", from = \"2010-01-01\", to = \"2015-12-31\") %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"monthly\", col_rename = \"Rb\") baseline_returns_monthly ## # A tibble: 72 × 2 ## date Rb ## ## 1 2010-01-29 -0.0993 ## 2 2010-02-26 0.0348 ## 3 2010-03-31 0.0684 ## 4 2010-04-30 0.0126 ## 5 2010-05-28 -0.0748 ## 6 2010-06-30 -0.0540 ## 7 2010-07-30 0.0745 ## 8 2010-08-31 -0.0561 ## 9 2010-09-30 0.117 ## 10 2010-10-29 0.0578 ## # ℹ 62 more rows"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"step-3a-aggregate-to-portfolio-period-returns","dir":"Articles","previous_headings":"3.0 Workflow > 3.2 Portfolios (Asset Groups) > Single Portfolio","what":"Step 3A: Aggregate to Portfolio Period Returns","title":"Performance Analysis with tidyquant","text":"tidyquant function, tq_portfolio() aggregates group individual assets single return using weighted composition underlying assets. need first develop portfolio weights. two ways single portfolio: Supplying vector weights Supplying two column tidy data frame (tibble) stock symbols first column weights map second. Suppose want split portfolio evenly AAPL NFLX. ’ll show using methods.","code":""},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"method-1-aggregating-a-portfolio-using-vector-of-weights","dir":"Articles","previous_headings":"","what":"Performance Analysis with tidyquant","title":"Performance Analysis with tidyquant","text":"’ll use weight vector, c(0.5, 0, 0.5). Two important aspects supplying numeric vector weights: First, notice length (3) equal number assets (3). requirement. Second, notice sum weighting vector equal 1. “required”, best practice. sum 1, weights distributed accordingly scaling vector 1, warning message appear. now aggregated portfolio 50/50 blend AAPL NFLX. may asking didn’t use GOOG? important thing understand assets asset returns don’t need used creating portfolio! enables us scale individual stock returns vary weights optimize portfolio (subject address future!)","code":"wts <- c(0.5, 0.0, 0.5) portfolio_returns_monthly <- stock_returns_monthly %>% tq_portfolio(assets_col = symbol, returns_col = Ra, weights = wts, col_rename = \"Ra\") portfolio_returns_monthly ## # A tibble: 72 × 2 ## date Ra ## ## 1 2010-01-29 0.0307 ## 2 2010-02-26 0.0629 ## 3 2010-03-31 0.130 ## 4 2010-04-30 0.239 ## 5 2010-05-28 0.0682 ## 6 2010-06-30 -0.0219 ## 7 2010-07-30 -0.0272 ## 8 2010-08-31 0.116 ## 9 2010-09-30 0.251 ## 10 2010-10-29 0.0674 ## # ℹ 62 more rows"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"method-2-aggregating-a-portfolio-using-two-column-tibble-with-symbols-and-weights","dir":"Articles","previous_headings":"","what":"Performance Analysis with tidyquant","title":"Performance Analysis with tidyquant","text":"possibly useful method aggregating returns using tibble symbols weights mapped portfolio. ’ll recreate previous portfolio example using mapped weights. Next, supply two column tibble, symbols first column weights second, weights argument tq_performance(). aggregated returns exactly . advantage method symbols need specified. symbol specified default gets weight zero. Now, imagine entire index, Russell 2000, 2000 individual stock returns nice tidy data frame. easy adjust portfolios compute blended returns, need supply symbols want blend. symbols default zero!","code":"wts_map <- tibble( symbols = c(\"AAPL\", \"NFLX\"), weights = c(0.5, 0.5) ) wts_map ## # A tibble: 2 × 2 ## symbols weights ## ## 1 AAPL 0.5 ## 2 NFLX 0.5 stock_returns_monthly %>% tq_portfolio(assets_col = symbol, returns_col = Ra, weights = wts_map, col_rename = \"Ra_using_wts_map\") ## # A tibble: 72 × 2 ## date Ra_using_wts_map ## ## 1 2010-01-29 0.0307 ## 2 2010-02-26 0.0629 ## 3 2010-03-31 0.130 ## 4 2010-04-30 0.239 ## 5 2010-05-28 0.0682 ## 6 2010-06-30 -0.0219 ## 7 2010-07-30 -0.0272 ## 8 2010-08-31 0.116 ## 9 2010-09-30 0.251 ## 10 2010-10-29 0.0674 ## # ℹ 62 more rows"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"step-3b-merging-ra-and-rb","dir":"Articles","previous_headings":"3.0 Workflow > 3.2 Portfolios (Asset Groups) > Single Portfolio","what":"Step 3B: Merging Ra and Rb","title":"Performance Analysis with tidyquant","text":"Now aggregated portfolio returns (“Ra”) Step 3A baseline returns (“Rb”) Step 2B, can merge get consolidated table asset baseline returns. Nothing new .","code":"RaRb_single_portfolio <- left_join(portfolio_returns_monthly, baseline_returns_monthly, by = \"date\") RaRb_single_portfolio ## # A tibble: 72 × 3 ## date Ra Rb ## ## 1 2010-01-29 0.0307 -0.0993 ## 2 2010-02-26 0.0629 0.0348 ## 3 2010-03-31 0.130 0.0684 ## 4 2010-04-30 0.239 0.0126 ## 5 2010-05-28 0.0682 -0.0748 ## 6 2010-06-30 -0.0219 -0.0540 ## 7 2010-07-30 -0.0272 0.0745 ## 8 2010-08-31 0.116 -0.0561 ## 9 2010-09-30 0.251 0.117 ## 10 2010-10-29 0.0674 0.0578 ## # ℹ 62 more rows"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"step-4-computing-the-capm-table","dir":"Articles","previous_headings":"3.0 Workflow > 3.2 Portfolios (Asset Groups) > Single Portfolio","what":"Step 4: Computing the CAPM Table","title":"Performance Analysis with tidyquant","text":"CAPM table computed function table.CAPM PerformanceAnalytics. just perform task performed “Quick Example”. Now CAPM performance metrics portfolio! cool, ’s cooler multiple portfolios. Let’s see .","code":"RaRb_single_portfolio %>% tq_performance(Ra = Ra, Rb = Rb, performance_fun = table.CAPM) ## # A tibble: 1 × 12 ## ActivePremium Alpha AnnualizedAlpha Beta `Beta-` `Beta+` Correlation ## ## 1 0.327 0.0299 0.425 0.754 -0.243 0.503 0.283 ## # ℹ 5 more variables: `Correlationp-value` , InformationRatio , ## # `R-squared` , TrackingError , TreynorRatio "},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"multiple-portfolios","dir":"Articles","previous_headings":"3.0 Workflow > 3.2 Portfolios (Asset Groups)","what":"Multiple Portfolios","title":"Performance Analysis with tidyquant","text":"understand process single portfolio using Step 3A, Method 2 (aggregating weights mapping), scaling multiple portfolios just building concept. Let’s recreate example “Single Portfolio” Example time three portfolios: 50% AAPL, 25% GOOG, 25% NFLX 25% AAPL, 50% GOOG, 25% NFLX 25% AAPL, 25% GOOG, 50% NFLX","code":""},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"steps-1-and-2-are-the-exact-same-as-the-single-portfolio-example","dir":"Articles","previous_headings":"3.0 Workflow > 3.2 Portfolios (Asset Groups) > Multiple Portfolios","what":"Steps 1 and 2 are the Exact Same as the Single Portfolio Example","title":"Performance Analysis with tidyquant","text":"First, get individual asset returns grouped asset, exact Steps 1A 1B Single Portfolio example. Second, get baseline asset returns, exact Steps 1B 2B Single Portfolio example.","code":"stock_returns_monthly <- c(\"AAPL\", \"GOOG\", \"NFLX\") %>% tq_get(get = \"stock.prices\", from = \"2010-01-01\", to = \"2015-12-31\") %>% group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"monthly\", col_rename = \"Ra\") baseline_returns_monthly <- \"XLK\" %>% tq_get(get = \"stock.prices\", from = \"2010-01-01\", to = \"2015-12-31\") %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"monthly\", col_rename = \"Rb\")"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"step-3a-aggregate-portfolio-returns-for-multiple-portfolios","dir":"Articles","previous_headings":"3.0 Workflow > 3.2 Portfolios (Asset Groups) > Multiple Portfolios","what":"Step 3A: Aggregate Portfolio Returns for Multiple Portfolios","title":"Performance Analysis with tidyquant","text":"gets fun. picked Single Portfolio, Step3A, Method 2 (mapping weights), just extension multiple portfolios. First, need grow portfolios. tidyquant handy, albeit simple, function, tq_repeat_df(), scaling single portfolio many. takes data frame, number repeats, n, index_col_name, adds sequential index. Let’s see works example. need three portfolios: Examining results, can see things happened: length (number rows) tripled. essence tq_repeat_df: grows data frame length-wise, repeating data frame n times. case, n = 3. data frame, grouped symbol, ungrouped. needed prevent tq_portfolio blending individual stocks. tq_portfolio works groups stocks. new column, named “portfolio”. “portfolio” column name key tells tq_portfolio multiple groups exist analyze. Just note multiple portfolio analysis, “portfolio” column name required. three groups portfolios. tq_portfolio split, apply (aggregate), combine . Now tricky part: need new table weights map . ’s requirements: must supply three column tibble following columns: “portfolio”, asset, weight order. “portfolio” column must named “portfolio” since key name mapping. tibble must grouped portfolio column. ’s weights table look like example: Now just pass expanded stock_returns_monthly_multi weights_table tq_portfolio portfolio aggregation. Let’s assess output. now single, “long” format data frame portfolio returns. three groups aggregated portfolios blended mapping weight_table.","code":"stock_returns_monthly_multi <- stock_returns_monthly %>% tq_repeat_df(n = 3) stock_returns_monthly_multi ## # A tibble: 648 × 4 ## # Groups: portfolio [3] ## portfolio symbol date Ra ## ## 1 1 AAPL 2010-01-29 -0.103 ## 2 1 AAPL 2010-02-26 0.0654 ## 3 1 AAPL 2010-03-31 0.148 ## 4 1 AAPL 2010-04-30 0.111 ## 5 1 AAPL 2010-05-28 -0.0161 ## 6 1 AAPL 2010-06-30 -0.0208 ## 7 1 AAPL 2010-07-30 0.0227 ## 8 1 AAPL 2010-08-31 -0.0550 ## 9 1 AAPL 2010-09-30 0.167 ## 10 1 AAPL 2010-10-29 0.0607 ## # ℹ 638 more rows weights <- c( 0.50, 0.25, 0.25, 0.25, 0.50, 0.25, 0.25, 0.25, 0.50 ) stocks <- c(\"AAPL\", \"GOOG\", \"NFLX\") weights_table <- tibble(stocks) %>% tq_repeat_df(n = 3) %>% bind_cols(tibble(weights)) %>% group_by(portfolio) weights_table ## # A tibble: 9 × 3 ## # Groups: portfolio [3] ## portfolio stocks weights ## ## 1 1 AAPL 0.5 ## 2 1 GOOG 0.25 ## 3 1 NFLX 0.25 ## 4 2 AAPL 0.25 ## 5 2 GOOG 0.5 ## 6 2 NFLX 0.25 ## 7 3 AAPL 0.25 ## 8 3 GOOG 0.25 ## 9 3 NFLX 0.5 portfolio_returns_monthly_multi <- stock_returns_monthly_multi %>% tq_portfolio(assets_col = symbol, returns_col = Ra, weights = weights_table, col_rename = \"Ra\") portfolio_returns_monthly_multi ## # A tibble: 216 × 3 ## # Groups: portfolio [3] ## portfolio date Ra ## ## 1 1 2010-01-29 -0.0489 ## 2 1 2010-02-26 0.0482 ## 3 1 2010-03-31 0.123 ## 4 1 2010-04-30 0.145 ## 5 1 2010-05-28 0.0245 ## 6 1 2010-06-30 -0.0308 ## 7 1 2010-07-30 0.000600 ## 8 1 2010-08-31 0.0474 ## 9 1 2010-09-30 0.222 ## 10 1 2010-10-29 0.0789 ## # ℹ 206 more rows"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"steps-3b-and-4-merging-and-assessing-performance","dir":"Articles","previous_headings":"3.0 Workflow > 3.2 Portfolios (Asset Groups) > Multiple Portfolios","what":"Steps 3B and 4: Merging and Assessing Performance","title":"Performance Analysis with tidyquant","text":"steps exact Single Portfolio example. First, merge baseline using “date” key. Finally, calculate performance portfolios using tq_performance. Make sure data frame grouped “portfolio”. Inspecting results, now multiple portfolio comparison CAPM table PerformanceAnalytics. can thing SharpeRatio well.","code":"RaRb_multiple_portfolio <- left_join(portfolio_returns_monthly_multi, baseline_returns_monthly, by = \"date\") RaRb_multiple_portfolio ## # A tibble: 216 × 4 ## # Groups: portfolio [3] ## portfolio date Ra Rb ## ## 1 1 2010-01-29 -0.0489 -0.0993 ## 2 1 2010-02-26 0.0482 0.0348 ## 3 1 2010-03-31 0.123 0.0684 ## 4 1 2010-04-30 0.145 0.0126 ## 5 1 2010-05-28 0.0245 -0.0748 ## 6 1 2010-06-30 -0.0308 -0.0540 ## 7 1 2010-07-30 0.000600 0.0745 ## 8 1 2010-08-31 0.0474 -0.0561 ## 9 1 2010-09-30 0.222 0.117 ## 10 1 2010-10-29 0.0789 0.0578 ## # ℹ 206 more rows RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = Rb, performance_fun = table.CAPM) ## # A tibble: 3 × 13 ## # Groups: portfolio [3] ## portfolio ActivePremium Alpha AnnualizedAlpha Beta `Beta-` `Beta+` ## ## 1 1 0.231 0.0193 0.258 0.908 0.312 0.741 ## 2 2 0.219 0.0192 0.256 0.886 0.436 0.660 ## 3 3 0.319 0.0308 0.439 0.721 -0.179 0.394 ## # ℹ 6 more variables: Correlation , `Correlationp-value` , ## # InformationRatio , `R-squared` , TrackingError , ## # TreynorRatio RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = NULL, performance_fun = SharpeRatio) ## # A tibble: 3 × 4 ## # Groups: portfolio [3] ## portfolio ESSharpe(Rf=0%,p=95%…¹ StdDevSharpe(Rf=0%,p…² VaRSharpe(Rf=0%,p=95…³ ## ## 1 1 0.172 0.355 0.263 ## 2 2 0.146 0.334 0.236 ## 3 3 0.150 0.317 0.238 ## # ℹ abbreviated names: ¹​`ESSharpe(Rf=0%,p=95%)`, ²​`StdDevSharpe(Rf=0%,p=95%)`, ## # ³​`VaRSharpe(Rf=0%,p=95%)`"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"available-functions","dir":"Articles","previous_headings":"","what":"4.0 Available Functions","title":"Performance Analysis with tidyquant","text":"’ve scratched surface analysis functions available PerformanceAnalytics. list includes compatible functions grouped function type. table functions useful get cross section metrics. ’ll touch . ’ll also go VaR SharpeRatio commonly used performance measures.","code":"tq_performance_fun_options() ## $table.funs ## [1] \"table.AnnualizedReturns\" \"table.Arbitrary\" ## [3] \"table.Autocorrelation\" \"table.CAPM\" ## [5] \"table.CaptureRatios\" \"table.Correlation\" ## [7] \"table.Distributions\" \"table.DownsideRisk\" ## [9] \"table.DownsideRiskRatio\" \"table.DrawdownsRatio\" ## [11] \"table.HigherMoments\" \"table.InformationRatio\" ## [13] \"table.RollingPeriods\" \"table.SFM\" ## [15] \"table.SpecificRisk\" \"table.Stats\" ## [17] \"table.TrailingPeriods\" \"table.UpDownRatios\" ## [19] \"table.Variability\" ## ## $CAPM.funs ## [1] \"CAPM.alpha\" \"CAPM.beta\" \"CAPM.beta.bear\" \"CAPM.beta.bull\" ## [5] \"CAPM.CML\" \"CAPM.CML.slope\" \"CAPM.dynamic\" \"CAPM.epsilon\" ## [9] \"CAPM.jensenAlpha\" \"CAPM.RiskPremium\" \"CAPM.SML.slope\" \"TimingRatio\" ## [13] \"MarketTiming\" ## ## $SFM.funs ## [1] \"SFM.alpha\" \"SFM.beta\" \"SFM.CML\" \"SFM.CML.slope\" ## [5] \"SFM.dynamic\" \"SFM.epsilon\" \"SFM.jensenAlpha\" ## ## $descriptive.funs ## [1] \"mean\" \"sd\" \"min\" \"max\" ## [5] \"cor\" \"mean.geometric\" \"mean.stderr\" \"mean.LCL\" ## [9] \"mean.UCL\" ## ## $annualized.funs ## [1] \"Return.annualized\" \"Return.annualized.excess\" ## [3] \"sd.annualized\" \"SharpeRatio.annualized\" ## ## $VaR.funs ## [1] \"VaR\" \"ES\" \"ETL\" \"CDD\" \"CVaR\" ## ## $moment.funs ## [1] \"var\" \"cov\" \"skewness\" \"kurtosis\" ## [5] \"CoVariance\" \"CoSkewness\" \"CoSkewnessMatrix\" \"CoKurtosis\" ## [9] \"CoKurtosisMatrix\" \"M3.MM\" \"M4.MM\" \"BetaCoVariance\" ## [13] \"BetaCoSkewness\" \"BetaCoKurtosis\" ## ## $drawdown.funs ## [1] \"AverageDrawdown\" \"AverageLength\" \"AverageRecovery\" ## [4] \"DrawdownDeviation\" \"DrawdownPeak\" \"maxDrawdown\" ## ## $Bacon.risk.funs ## [1] \"MeanAbsoluteDeviation\" \"Frequency\" \"SharpeRatio\" ## [4] \"MSquared\" \"MSquaredExcess\" \"HurstIndex\" ## ## $Bacon.regression.funs ## [1] \"CAPM.alpha\" \"CAPM.beta\" \"CAPM.epsilon\" \"CAPM.jensenAlpha\" ## [5] \"SystematicRisk\" \"SpecificRisk\" \"TotalRisk\" \"TreynorRatio\" ## [9] \"AppraisalRatio\" \"FamaBeta\" \"Selectivity\" \"NetSelectivity\" ## ## $Bacon.relative.risk.funs ## [1] \"ActivePremium\" \"ActiveReturn\" \"TrackingError\" \"InformationRatio\" ## ## $Bacon.drawdown.funs ## [1] \"PainIndex\" \"PainRatio\" \"CalmarRatio\" \"SterlingRatio\" ## [5] \"BurkeRatio\" \"MartinRatio\" \"UlcerIndex\" ## ## $Bacon.downside.risk.funs ## [1] \"DownsideDeviation\" \"DownsidePotential\" \"DownsideFrequency\" ## [4] \"SemiDeviation\" \"SemiVariance\" \"UpsideRisk\" ## [7] \"UpsidePotentialRatio\" \"UpsideFrequency\" \"BernardoLedoitRatio\" ## [10] \"DRatio\" \"Omega\" \"OmegaSharpeRatio\" ## [13] \"OmegaExcessReturn\" \"SortinoRatio\" \"M2Sortino\" ## [16] \"Kappa\" \"VolatilitySkewness\" \"AdjustedSharpeRatio\" ## [19] \"SkewnessKurtosisRatio\" \"ProspectRatio\" ## ## $misc.funs ## [1] \"KellyRatio\" \"Modigliani\" \"UpDownRatios\""},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"table-stats","dir":"Articles","previous_headings":"4.0 Available Functions","what":"4.1 table.Stats","title":"Performance Analysis with tidyquant","text":"Returns basic set statistics match period data passed (e.g., monthly returns get monthly statistics, daily daily stats, ).","code":"RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = NULL, performance_fun = table.Stats) ## # A tibble: 3 × 17 ## # Groups: portfolio [3] ## portfolio ArithmeticMean GeometricMean Kurtosis `LCLMean(0.95)` Maximum Median ## ## 1 1 0.0293 0.0259 1.14 0.0099 0.222 0.0307 ## 2 2 0.029 0.0252 1.65 0.0086 0.227 0.037 ## 3 3 0.0388 0.0313 1.81 0.01 0.370 0.046 ## # ℹ 10 more variables: Minimum , NAs , Observations , ## # Quartile1 , Quartile3 , SEMean , Skewness , ## # Stdev , `UCLMean(0.95)` , Variance "},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"table-capm","dir":"Articles","previous_headings":"4.0 Available Functions","what":"4.2 table.CAPM","title":"Performance Analysis with tidyquant","text":"Takes set returns relates benchmark return. Provides set measures related excess return single factor model, CAPM.","code":"RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = Rb, performance_fun = table.CAPM) ## # A tibble: 3 × 13 ## # Groups: portfolio [3] ## portfolio ActivePremium Alpha AnnualizedAlpha Beta `Beta-` `Beta+` ## ## 1 1 0.231 0.0193 0.258 0.908 0.312 0.741 ## 2 2 0.219 0.0192 0.256 0.886 0.436 0.660 ## 3 3 0.319 0.0308 0.439 0.721 -0.179 0.394 ## # ℹ 6 more variables: Correlation , `Correlationp-value` , ## # InformationRatio , `R-squared` , TrackingError , ## # TreynorRatio "},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"table-annualizedreturns","dir":"Articles","previous_headings":"4.0 Available Functions","what":"4.3 table.AnnualizedReturns","title":"Performance Analysis with tidyquant","text":"Table Annualized Return, Annualized Std Dev, Annualized Sharpe.","code":"RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = NULL, performance_fun = table.AnnualizedReturns) ## # A tibble: 3 × 4 ## # Groups: portfolio [3] ## portfolio AnnualizedReturn `AnnualizedSharpe(Rf=0%)` AnnualizedStdDev ## ## 1 1 0.360 1.26 0.286 ## 2 2 0.348 1.16 0.301 ## 3 3 0.448 1.06 0.424"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"table-correlation","dir":"Articles","previous_headings":"4.0 Available Functions","what":"4.4 table.Correlation","title":"Performance Analysis with tidyquant","text":"wrapper calculating correlation significance column data provided.","code":"RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = Rb, performance_fun = table.Correlation) ## # A tibble: 3 × 5 ## # Groups: portfolio [3] ## portfolio `p-value` `Lower CI` `Upper CI` to.Rb ## ## 1 1 0.0000284 0.270 0.634 0.472 ## 2 2 0.000122 0.229 0.608 0.438 ## 3 3 0.0325 0.0220 0.457 0.252"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"table-downsiderisk","dir":"Articles","previous_headings":"4.0 Available Functions","what":"4.5 table.DownsideRisk","title":"Performance Analysis with tidyquant","text":"Creates table estimates downside risk measures comparison across multiple instruments funds.","code":"RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = NULL, performance_fun = table.DownsideRisk) ## # A tibble: 3 × 12 ## # Groups: portfolio [3] ## portfolio DownsideDeviation(0%…¹ DownsideDeviation(MA…² DownsideDeviation(Rf…³ ## ## 1 1 0.045 0.0488 0.045 ## 2 2 0.0501 0.0538 0.0501 ## 3 3 0.0684 0.0721 0.0684 ## # ℹ abbreviated names: ¹​`DownsideDeviation(0%)`, ²​`DownsideDeviation(MAR=10%)`, ## # ³​`DownsideDeviation(Rf=0%)` ## # ℹ 8 more variables: GainDeviation , `HistoricalES(95%)` , ## # `HistoricalVaR(95%)` , LossDeviation , MaximumDrawdown , ## # `ModifiedES(95%)` , `ModifiedVaR(95%)` , SemiDeviation "},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"table-downsideriskratio","dir":"Articles","previous_headings":"4.0 Available Functions","what":"4.6 table.DownsideRiskRatio","title":"Performance Analysis with tidyquant","text":"Table Monthly downside risk, Annualized downside risk, Downside potential, Omega, Sortino ratio, Upside potential, Upside potential ratio Omega-Sharpe ratio.","code":"RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = NULL, performance_fun = table.DownsideRiskRatio) ## # A tibble: 3 × 9 ## # Groups: portfolio [3] ## portfolio Annualiseddownsiderisk Downsidepotential monthlydownsiderisk Omega ## ## 1 1 0.156 0.0198 0.045 2.48 ## 2 2 0.173 0.0217 0.0501 2.34 ## 3 3 0.237 0.0294 0.0684 2.32 ## # ℹ 4 more variables: `Omega-sharperatio` , Sortinoratio , ## # Upsidepotential , Upsidepotentialratio "},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"table-highermoments","dir":"Articles","previous_headings":"4.0 Available Functions","what":"4.7 table.HigherMoments","title":"Performance Analysis with tidyquant","text":"Summary higher moments Co-Moments return distribution. Used determine diversification potential. Also called “systematic” moments several papers.","code":"RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = Rb, performance_fun = table.HigherMoments) ## # A tibble: 3 × 6 ## # Groups: portfolio [3] ## portfolio BetaCoKurtosis BetaCoSkewness BetaCoVariance CoKurtosis CoSkewness ## ## 1 1 0.756 0.196 0.908 0 0 ## 2 2 0.772 1.71 0.886 0 0 ## 3 3 0.455 0.369 0.721 0 0"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"table-informationratio","dir":"Articles","previous_headings":"4.0 Available Functions","what":"4.8 table.InformationRatio","title":"Performance Analysis with tidyquant","text":"Table Tracking error, Annualized tracking error Information ratio.","code":"RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = Rb, performance_fun = table.InformationRatio) ## # A tibble: 3 × 4 ## # Groups: portfolio [3] ## portfolio AnnualisedTrackingError InformationRatio TrackingError ## ## 1 1 0.252 0.917 0.0728 ## 2 2 0.271 0.809 0.0782 ## 3 3 0.412 0.774 0.119"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"table-variability","dir":"Articles","previous_headings":"4.0 Available Functions","what":"4.9 table.Variability","title":"Performance Analysis with tidyquant","text":"Table Mean absolute difference, Monthly standard deviation annualized standard deviation.","code":"RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = NULL, performance_fun = table.Variability) ## # A tibble: 3 × 4 ## # Groups: portfolio [3] ## portfolio AnnualizedStdDev MeanAbsolutedeviation monthlyStdDev ## ## 1 1 0.286 0.0658 0.0825 ## 2 2 0.301 0.0679 0.0868 ## 3 3 0.424 0.091 0.122"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"var","dir":"Articles","previous_headings":"4.0 Available Functions","what":"4.10 VaR","title":"Performance Analysis with tidyquant","text":"Calculates Value--Risk (VaR) univariate, component, marginal cases using variety analytical methods.","code":"RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = NULL, performance_fun = VaR) ## # A tibble: 3 × 2 ## # Groups: portfolio [3] ## portfolio VaR ## ## 1 1 -0.111 ## 2 2 -0.123 ## 3 3 -0.163"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"sharperatio","dir":"Articles","previous_headings":"4.0 Available Functions","what":"4.11 SharpeRatio","title":"Performance Analysis with tidyquant","text":"Sharpe ratio simply return per unit risk (represented variability). classic case, unit risk standard deviation returns.","code":"RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = NULL, performance_fun = SharpeRatio) ## # A tibble: 3 × 4 ## # Groups: portfolio [3] ## portfolio ESSharpe(Rf=0%,p=95%…¹ StdDevSharpe(Rf=0%,p…² VaRSharpe(Rf=0%,p=95…³ ## ## 1 1 0.172 0.355 0.263 ## 2 2 0.146 0.334 0.236 ## 3 3 0.150 0.317 0.238 ## # ℹ abbreviated names: ¹​`ESSharpe(Rf=0%,p=95%)`, ²​`StdDevSharpe(Rf=0%,p=95%)`, ## # ³​`VaRSharpe(Rf=0%,p=95%)`"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"customizing-using-the","dir":"Articles","previous_headings":"","what":"5.0 Customizing using the …","title":"Performance Analysis with tidyquant","text":"One best features tq_portfolio tq_performance able pass features underlying functions. , just wrappers PerformanceAnalytics, probably want able make full use underlying functions. Passing parameters using ... can incredibly useful, let’s see .","code":""},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"customizing-tq_portfolio","dir":"Articles","previous_headings":"5.0 Customizing using the …","what":"5.1 Customizing tq_portfolio","title":"Performance Analysis with tidyquant","text":"tq_portfolio function wrapper Return.portfolio. means portfolio aggregation process, can make use Return.portfolio arguments wealth.index, contribution, geometric, rebalance_on, value. ’s arguments underlying function: Let’s see example passing parameters .... Suppose want instead see money grows $10,000 investment. ’ll use “Single Portfolio” example, portfolio mix 50% AAPL, 0% GOOG, 50% NFLX. Method 3A, Aggregating Portfolio Returns, showed us two methods aggregate single portfolio. Either work example. simplicity, ’ll examine first. ’s original output, without adjusting parameters. good, want see $10,000 initial investment growing. simple underlying Return.portfolio argument, wealth.index = TRUE. need add additional parameters tq_portfolio! Finally, taking one step , apply process “Multiple Portfolio” example: 50% AAPL, 25% GOOG, 25% NFLX 25% AAPL, 50% GOOG, 25% NFLX 25% AAPL, 25% GOOG, 50% NFLX","code":"args(Return.portfolio) ## function (R, weights = NULL, wealth.index = FALSE, contribution = FALSE, ## geometric = TRUE, rebalance_on = c(NA, \"years\", \"quarters\", ## \"months\", \"weeks\", \"days\"), value = 1, verbose = FALSE, ## ...) ## NULL wts <- c(0.5, 0.0, 0.5) portfolio_returns_monthly <- stock_returns_monthly %>% tq_portfolio(assets_col = symbol, returns_col = Ra, weights = wts, col_rename = \"Ra\") portfolio_returns_monthly %>% ggplot(aes(x = date, y = Ra)) + geom_bar(stat = \"identity\", fill = palette_light()[[1]]) + labs(title = \"Portfolio Returns\", subtitle = \"50% AAPL, 0% GOOG, and 50% NFLX\", caption = \"Shows an above-zero trend meaning positive returns\", x = \"\", y = \"Monthly Returns\") + geom_smooth(method = \"lm\") + theme_tq() + scale_color_tq() + scale_y_continuous(labels = scales::percent) wts <- c(0.5, 0, 0.5) portfolio_growth_monthly <- stock_returns_monthly %>% tq_portfolio(assets_col = symbol, returns_col = Ra, weights = wts, col_rename = \"investment.growth\", wealth.index = TRUE) %>% mutate(investment.growth = investment.growth * 10000) portfolio_growth_monthly %>% ggplot(aes(x = date, y = investment.growth)) + geom_line(linewidth = 2, color = palette_light()[[1]]) + labs(title = \"Portfolio Growth\", subtitle = \"50% AAPL, 0% GOOG, and 50% NFLX\", caption = \"Now we can really visualize performance!\", x = \"\", y = \"Portfolio Value\") + geom_smooth(method = \"loess\") + theme_tq() + scale_color_tq() + scale_y_continuous(labels = scales::dollar) portfolio_growth_monthly_multi <- stock_returns_monthly_multi %>% tq_portfolio(assets_col = symbol, returns_col = Ra, weights = weights_table, col_rename = \"investment.growth\", wealth.index = TRUE) %>% mutate(investment.growth = investment.growth * 10000) portfolio_growth_monthly_multi %>% ggplot(aes(x = date, y = investment.growth, color = factor(portfolio))) + geom_line(linewidth = 2) + labs(title = \"Portfolio Growth\", subtitle = \"Comparing Multiple Portfolios\", caption = \"Portfolio 3 is a Standout!\", x = \"\", y = \"Portfolio Value\", color = \"Portfolio\") + geom_smooth(method = \"loess\") + theme_tq() + scale_color_tq() + scale_y_continuous(labels = scales::dollar)"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"customizing-tq_performance","dir":"Articles","previous_headings":"5.0 Customizing using the …","what":"5.2 Customizing tq_performance","title":"Performance Analysis with tidyquant","text":"Finally, concept passing arguments works tidyquant functions wrappers including tq_transmute, tq_mutate, tq_performance, etc. Let’s use final example SharpeRatio, following arguments. can see parameters Rf allows us apply risk-free rate p allows us vary confidence interval. Let’s compare Sharpe ratio annualized risk-free rate 3% confidence interval 0.99. Default: Rf = 0.03 / 12 (adjusted monthly periodicity): , Rf = 0.03 / 12 (adjusted monthly periodicity) p = 0.99:","code":"args(SharpeRatio) ## function (R, Rf = 0, p = 0.95, FUN = c(\"StdDev\", \"VaR\", \"ES\"), ## weights = NULL, annualize = FALSE, SE = FALSE, SE.control = NULL, ## ...) ## NULL RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, performance_fun = SharpeRatio) ## # A tibble: 3 × 4 ## # Groups: portfolio [3] ## portfolio ESSharpe(Rf=0%,p=95%…¹ StdDevSharpe(Rf=0%,p…² VaRSharpe(Rf=0%,p=95…³ ## ## 1 1 0.172 0.355 0.263 ## 2 2 0.146 0.334 0.236 ## 3 3 0.150 0.317 0.238 ## # ℹ abbreviated names: ¹​`ESSharpe(Rf=0%,p=95%)`, ²​`StdDevSharpe(Rf=0%,p=95%)`, ## # ³​`VaRSharpe(Rf=0%,p=95%)` RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, performance_fun = SharpeRatio, Rf = 0.03 / 12) ## # A tibble: 3 × 4 ## # Groups: portfolio [3] ## portfolio ESSharpe(Rf=0.2%,p=9…¹ StdDevSharpe(Rf=0.2%…² VaRSharpe(Rf=0.2%,p=…³ ## ## 1 1 0.157 0.325 0.241 ## 2 2 0.134 0.305 0.216 ## 3 3 0.141 0.296 0.222 ## # ℹ abbreviated names: ¹​`ESSharpe(Rf=0.2%,p=95%)`, ## # ²​`StdDevSharpe(Rf=0.2%,p=95%)`, ³​`VaRSharpe(Rf=0.2%,p=95%)` RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, performance_fun = SharpeRatio, Rf = 0.03 / 12, p = 0.99) ## # A tibble: 3 × 4 ## # Groups: portfolio [3] ## portfolio ESSharpe(Rf=0.2%,p=9…¹ StdDevSharpe(Rf=0.2%…² VaRSharpe(Rf=0.2%,p=…³ ## ## 1 1 0.105 0.325 0.134 ## 2 2 0.0952 0.305 0.115 ## 3 3 0.0915 0.296 0.117 ## # ℹ abbreviated names: ¹​`ESSharpe(Rf=0.2%,p=99%)`, ## # ²​`StdDevSharpe(Rf=0.2%,p=99%)`, ³​`VaRSharpe(Rf=0.2%,p=99%)`"},{"path":"/authors.html","id":null,"dir":"","previous_headings":"","what":"Authors","title":"Authors and Citation","text":"Matt Dancho. Author, maintainer. Davis Vaughan. Author.","code":""},{"path":"/authors.html","id":"citation","dir":"","previous_headings":"","what":"Citation","title":"Authors and Citation","text":"Dancho M, Vaughan D (2023). tidyquant: Tidy Quantitative Financial Analysis. https://business-science.github.io/tidyquant/, https://github.com/business-science/tidyquant.","code":"@Manual{, title = {tidyquant: Tidy Quantitative Financial Analysis}, author = {Matt Dancho and Davis Vaughan}, year = {2023}, note = {https://business-science.github.io/tidyquant/, https://github.com/business-science/tidyquant}, }"},{"path":"/index.html","id":"tidyquant-","dir":"","previous_headings":"","what":"Tidy Quantitative Financial Analysis","title":"Tidy Quantitative Financial Analysis","text":"Bringing financial business analysis tidyverse","code":""},{"path":"/index.html","id":"id_2-minutes-to-tidyquant","dir":"","previous_headings":"","what":"2-Minutes To tidyquant","title":"Tidy Quantitative Financial Analysis","text":"short introduction tidyquant YouTube.","code":""},{"path":"/index.html","id":"features-of-tidyquant","dir":"","previous_headings":"","what":"Features of tidyquant","title":"Tidy Quantitative Financial Analysis","text":"tidyquant integrates best resources collecting analyzing financial data, zoo, xts, quantmod, TTR, PerformanceAnalytics, tidy data infrastructure tidyverse allowing seamless interaction . can now perform complete financial analyses tidyverse. core functions lot power Integrates quantitative analysis functionality zoo, xts, quantmod, TTR, now PerformanceAnalytics Designed modeling scaling analyses using tidyverse tools R Data Science Implements ggplot2 functionality beautiful meaningful financial visualizations User-friendly documentation get speed quickly!","code":""},{"path":"/index.html","id":"new-excel-functionality-in-tidyquant","dir":"","previous_headings":"","what":"New Excel Functionality in tidyquant","title":"Tidy Quantitative Financial Analysis","text":"Excel R - Pivot Tables, VLOOKUPs, : Details Excel integrations covered blog article.","code":""},{"path":"/index.html","id":"one-stop-shop-for-serious-financial-analysis","dir":"","previous_headings":"","what":"One-Stop Shop for Serious Financial Analysis","title":"Tidy Quantitative Financial Analysis","text":"tidyquant benefits add one thing: one-stop shop serious financial analysis!","code":""},{"path":"/index.html","id":"core-functions","dir":"","previous_headings":"One-Stop Shop for Serious Financial Analysis","what":"Core Functions","title":"Tidy Quantitative Financial Analysis","text":"Getting Financial Data web: tq_get(). one-stop shop getting web-based financial data “tidy” data frame format. Get data daily stock prices (historical), key statistics (real-time), key ratios (historical), financial statements, dividends, splits, economic data FRED, FOREX rates Oanda. Manipulating Financial Data: tq_transmute() tq_mutate(). Integration many financial functions xts, zoo, quantmod,TTR PerformanceAnalytics packages. tq_mutate() used add column data frame, tq_transmute() used return new data frame necessary periodicity changes. Performance Analysis Portfolio Analysis: tq_performance() tq_portfolio(). newest additions tidyquant family integrate PerformanceAnalytics functions. tq_performance() converts investment returns performance metrics. tq_portfolio() aggregates group (multiple groups) asset returns one portfolios.","code":""},{"path":"/index.html","id":"comparing-stock-prices","dir":"","previous_headings":"One-Stop Shop for Serious Financial Analysis","what":"Comparing Stock Prices","title":"Tidy Quantitative Financial Analysis","text":"Visualizing stock price volatility four stocks side--side quick easy…","code":""},{"path":"/index.html","id":"evaluating-stock-performance","dir":"","previous_headings":"One-Stop Shop for Serious Financial Analysis","what":"Evaluating Stock Performance","title":"Tidy Quantitative Financial Analysis","text":"stock performance? Quickly visualize $10,000 investment various stocks perform.","code":""},{"path":"/index.html","id":"evaluating-portfolio-performance","dir":"","previous_headings":"One-Stop Shop for Serious Financial Analysis","what":"Evaluating Portfolio Performance","title":"Tidy Quantitative Financial Analysis","text":"Ok, stocks easy. portfolios? PerformanceAnalytics integration, visualizing blended portfolios easy ! Portfolio 1: 50% FB, 25% AMZN, 25% NFLX, 0% GOOG Portfolio 2: 0% FB, 50% AMZN, 25% NFLX, 25% GOOG Portfolio 3: 25% FB, 0% AMZN, 50% NFLX, 25% GOOG Portfolio 4: 25% FB, 25% AMZN, 0% NFLX, 50% GOOG just scratches surface tidyquant. ’s install get started.","code":""},{"path":"/index.html","id":"installation","dir":"","previous_headings":"","what":"Installation","title":"Tidy Quantitative Financial Analysis","text":"Development Version Latest Features: CRAN Approved Version:","code":"# install.packages(\"devtools\") devtools::install_github(\"business-science/tidyquant\") install.packages(\"tidyquant\")"},{"path":"/index.html","id":"further-information","dir":"","previous_headings":"","what":"Further Information","title":"Tidy Quantitative Financial Analysis","text":"tidyquant package includes several vignettes help users get speed quickly: TQ00 - Introduction tidyquant TQ01 - Core Functions tidyquant TQ02 - R Quantitative Analysis Package Integrations tidyquant TQ03 - Scaling Modeling tidyquant TQ04 - Charting tidyquant TQ05 - Performance Analysis tidyquant Blog Article: Excel R - Pivot Tables, VLOOKUPs, !","code":""},{"path":"/index.html","id":"want-to-learn-tidyquant","dir":"","previous_headings":"","what":"Want to Learn tidyquant?","title":"Tidy Quantitative Financial Analysis","text":"Learning Lab #9: Performance Analysis & Portfolio Optimization tidyquant - 1-hour course tidyquant Learning Labs PRO Learning Lab #10: Building API plumber - Build stock optimization API plumber tidyquant Learning Lab #16: Stock Portfolio Optimization Nonlinear Programming - Use ROI package tidyquant calculate optimal minimum variance portfolios develop efficient frontier. Learning Lab #30: Shiny Financial Analysis Tidyquant API & Excel Pivot Tables - Learn use new Excel Functionality make Pivot Tables, VLOOKUPs, Sum-’s, !","code":""},{"path":"/reference/FANG.html","id":null,"dir":"Reference","previous_headings":"","what":"Stock prices for the ","title":"Stock prices for the ","text":"dataset containing daily historical stock prices \"FANG\" tech stocks, \"META\", \"AMZN\", \"NFLX\", \"GOOG\", spanning beginning 2013 end 2016.","code":""},{"path":"/reference/FANG.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Stock prices for the ","text":"","code":"FANG"},{"path":"/reference/FANG.html","id":"format","dir":"Reference","previous_headings":"","what":"Format","title":"Stock prices for the ","text":"\"tibble\" (\"tidy\" data frame) 4,032 rows 8 variables: symbol stock ticker symbol date trade date open stock price open trading, USD high stock price highest point trading, USD low stock price lowest point trading, USD close stock price close trading, USD volume number shares traded adjusted stock price close trading adjusted stock splits, USD","code":""},{"path":"/reference/FANG.html","id":"source","dir":"Reference","previous_headings":"","what":"Source","title":"Stock prices for the ","text":"https://www.investopedia.com/terms/f/fang-stocks-fb-amzn.asp","code":""},{"path":"/reference/av_api_key.html","id":null,"dir":"Reference","previous_headings":"","what":"Set Alpha Vantage API Key — av_api_key","title":"Set Alpha Vantage API Key — av_api_key","text":"Requires alphavantager packager use.","code":""},{"path":"/reference/av_api_key.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Set Alpha Vantage API Key — av_api_key","text":"","code":"av_api_key(api_key)"},{"path":"/reference/av_api_key.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Set Alpha Vantage API Key — av_api_key","text":"api_key Optionally passed parameter set Alpha Vantage api_key.","code":""},{"path":"/reference/av_api_key.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Set Alpha Vantage API Key — av_api_key","text":"Returns invisibly currently set api_key","code":""},{"path":"/reference/av_api_key.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Set Alpha Vantage API Key — av_api_key","text":"wrapper alphavantager::av_api_key()","code":""},{"path":[]},{"path":"/reference/av_api_key.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Set Alpha Vantage API Key — av_api_key","text":"","code":"if (FALSE) { if (rlang::is_installed(\"alphavantager\")) { av_api_key(api_key = \"foobar\") } }"},{"path":"/reference/coord_x_date.html","id":null,"dir":"Reference","previous_headings":"","what":"Zoom in on plot regions using date ranges or date-time ranges — coord_x_date","title":"Zoom in on plot regions using date ranges or date-time ranges — coord_x_date","text":"Zoom plot regions using date ranges date-time ranges","code":""},{"path":"/reference/coord_x_date.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Zoom in on plot regions using date ranges or date-time ranges — coord_x_date","text":"","code":"coord_x_date(xlim = NULL, ylim = NULL, expand = TRUE) coord_x_datetime(xlim = NULL, ylim = NULL, expand = TRUE)"},{"path":"/reference/coord_x_date.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Zoom in on plot regions using date ranges or date-time ranges — coord_x_date","text":"xlim Limits x axis, entered character dates \"YYYY-MM-DD\" format date \"YYYY-MM-DD HH:MM:SS\" date-time. ylim Limits y axis, entered values expand TRUE, default, adds small expansion factor limits ensure data axes overlap. FALSE, limits taken exactly data xlim/ylim.","code":""},{"path":"/reference/coord_x_date.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Zoom in on plot regions using date ranges or date-time ranges — coord_x_date","text":"coord_ functions prevent loss data zooming, necessary zooming plots calculate stats using data outside zoom range (e.g. plotting moving averages geom_ma()). Setting limits using scale_x_date changes underlying data causes moving averages fail. coord_x_date wrapper coord_cartesian enables quickly zooming plot regions using date range. coord_x_datetime wrapper coord_cartesian enables quickly zooming plot regions using date-time range.","code":""},{"path":[]},{"path":"/reference/coord_x_date.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Zoom in on plot regions using date ranges or date-time ranges — coord_x_date","text":"","code":"# Load libraries library(dplyr) #> #> ######################### 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: ‘dplyr’ #> The following objects are masked from ‘package:xts’: #> #> first, last #> The following objects are masked from ‘package:stats’: #> #> filter, lag #> The following objects are masked from ‘package:base’: #> #> intersect, setdiff, setequal, union library(ggplot2) # coord_x_date AAPL <- tq_get(\"AAPL\", from = \"2013-01-01\", to = \"2016-12-31\") AAPL %>% ggplot(aes(x = date, y = adjusted)) + geom_line() + # Plot stock price geom_ma(n = 50) + # Plot 50-day Moving Average geom_ma(n = 200, color = \"red\") + # Plot 200-day Moving Average # Zoom in coord_x_date(xlim = c(\"2016-01-01\", \"2016-12-31\")) # coord_x_datetime time_index <- seq(from = as.POSIXct(\"2012-05-15 07:00\"), to = as.POSIXct(\"2012-05-17 18:00\"), by = \"hour\") set.seed(1) value <- rnorm(n = length(time_index)) hourly_data <- tibble(time.index = time_index, value = value) hourly_data %>% ggplot(aes(x = time.index, y = value)) + geom_point() + coord_x_datetime(xlim = c(\"2012-05-15 07:00:00\", \"2012-05-15 16:00:00\"))"},{"path":"/reference/deprecated.html","id":null,"dir":"Reference","previous_headings":"","what":"Deprecated functions — deprecated","title":"Deprecated functions — deprecated","text":"record functions deprecated.","code":""},{"path":"/reference/deprecated.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Deprecated functions — deprecated","text":"","code":"tq_transform(data, ohlc_fun = OHLCV, mutate_fun, col_rename = NULL, ...) tq_transform_xy(data, x, y = NULL, mutate_fun, col_rename = NULL, ...)"},{"path":"/reference/deprecated.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Deprecated functions — deprecated","text":"data tibble (tidy data frame) data typically tq_get(). ohlc_fun Deprecated. Use select. mutate_fun mutation function either xts, quantmod, TTR package. Execute tq_mutate_fun_options() see full list options package. col_rename string character vector containing names can used quickly rename columns. ... Additional parameters passed appropriate mutatation function. x, y Parameters used _xy consist column names variables passed mutatation function (instead OHLC functions).","code":""},{"path":"/reference/deprecated.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Deprecated functions — deprecated","text":"tq_transform() - use tq_transmute() tq_transform_xy() - use tq_transmute_xy() as_xts() - use timetk::tk_xts() as_tibble() - use timetk::tk_tbl() summarise_by_time() - Moved timetk package. Use timetk::summarise_by_time()","code":""},{"path":"/reference/excel_date_functions.html","id":null,"dir":"Reference","previous_headings":"","what":"Excel Date and Time Functions — excel_date_functions","title":"Excel Date and Time Functions — excel_date_functions","text":"50+ date time functions familiar users coming Excel Background. main benefits : Integration amazing lubridate package handling dates times Integration Holidays timeDate Business Calendars New Date Math Date Sequence Functions factor Business Calendars (e.g. EOMONTH(), NET_WORKDAYS()) functions designed help users coming Excel background. functions replicate behavior Excel: Names cases match Excel function names Functionality replicates Excel default, missing values ignored (Excel)","code":""},{"path":"/reference/excel_date_functions.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Excel Date and Time Functions — excel_date_functions","text":"","code":"AS_DATE(x, ...) AS_DATETIME(x, ...) DATE(year, month, day) DATEVALUE(x, ...) YMD(x, ...) MDY(x, ...) DMY(x, ...) YMD_HMS(x, ...) MDY_HMS(x, ...) DMY_HMS(x, ...) YMD_HM(x, ...) MDY_HM(x, ...) DMY_HM(x, ...) YMD_H(x, ...) MDY_H(x, ...) DMY_H(x, ...) WEEKDAY(x, ..., label = FALSE, abbr = TRUE) WDAY(x, ..., label = FALSE, abbr = TRUE) DOW(x, ..., label = FALSE, abbr = TRUE) MONTHDAY(x, ...) MDAY(x, ...) DOM(x, ...) QUARTERDAY(x, ...) QDAY(x, ...) DAY(x, ...) WEEKNUM(x, ...) WEEK(x, ...) WEEKNUM_ISO(x, ...) MONTH(x, ..., label = FALSE, abbr = TRUE) QUARTER(x, ..., include_year = FALSE, fiscal_start = 1) YEAR(x, ...) YEAR_ISO(x, ...) DATE_TO_NUMERIC(x, ...) DATE_TO_DECIMAL(x, ...) SECOND(x, ...) MINUTE(x, ...) HOUR(x, ...) NOW(...) TODAY(...) EOMONTH(start_date, months = 0) EDATE(start_date, months = 0) NET_WORKDAYS(start_date, end_date, remove_weekends = TRUE, holidays = NULL) COUNT_DAYS(start_date, end_date) YEARFRAC(start_date, end_date) DATE_SEQUENCE(start_date, end_date, by = \"day\") WORKDAY_SEQUENCE(start_date, end_date, remove_weekends = TRUE, holidays = NULL) HOLIDAY_SEQUENCE( start_date, end_date, calendar = c(\"NYSE\", \"LONDON\", \"NERC\", \"TSX\", \"ZURICH\") ) HOLIDAY_TABLE(years, pattern = \".\") FLOOR_DATE(x, ..., by = \"day\") FLOOR_DAY(x, ...) FLOOR_WEEK(x, ...) FLOOR_MONTH(x, ...) FLOOR_QUARTER(x, ...) FLOOR_YEAR(x, ...) CEILING_DATE(x, ..., by = \"day\") CEILING_DAY(x, ...) CEILING_WEEK(x, ...) CEILING_MONTH(x, ...) CEILING_QUARTER(x, ...) CEILING_YEAR(x, ...) ROUND_DATE(x, ..., by = \"day\") ROUND_DAY(x, ...) ROUND_WEEK(x, ...) ROUND_MONTH(x, ...) ROUND_QUARTER(x, ...) ROUND_YEAR(x, ...)"},{"path":"/reference/excel_date_functions.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Excel Date and Time Functions — excel_date_functions","text":"x vector date date-time objects ... Parameters passed underlying lubridate functions. year Used DATE() month Used DATE() day Used DATE() label logical used MONTH() WEEKDAY() Date Extractors decide whether return names (ordered factors) numeric values. abbr logical used MONTH() WEEKDAY(). label = TRUE, used determine full names (e.g. Wednesday) abbreviated names (e.g. Wed) returned. include_year logicial value used QUARTER(). Determines whether return 2020 Q3 3 2020.3. fiscal_start numeric value used QUARTER(). Determines fiscal-year starting quarter. start_date Used Date Math Date Sequence operations. starting date calculation. months Used offset months EOMONTH() EDATE() Date Math calculations end_date Used Date Math Date Sequence operations. ending date calculation. remove_weekends logical value used Date Sequence Date Math calculations. Indicates whether weekends removed calculation. holidays vector dates corresponding holidays removed calculation. Used determine gap Date Sequence calculations value round Date Collapsing operations. Acceptable values : character string, containing one \"day\", \"week\", \"month\", \"quarter\" \"year\". calendar calendar used Date Sequence calculations Holidays timeDate package. Acceptable values : \"NYSE\", \"LONDON\", \"NERC\", \"TSX\", \"ZURICH\" years numeric vector years return Holidays HOLIDAY_TABLE() pattern Used filter Holidays (e.g. pattern = \"Easter\"). \"regular expression\" filtering pattern.","code":""},{"path":"/reference/excel_date_functions.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Excel Date and Time Functions — excel_date_functions","text":"Converters - Date date-time object length x Extractors - Returns information time-stamp. Current Time - Returns current date/date-time based locale. Date Math - Numeric values Date Values depending calculation. Date Sequences - Return vector dates Holiday Table (tibble). Date Collapsers - Date date-time object length x","code":""},{"path":"/reference/excel_date_functions.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Excel Date and Time Functions — excel_date_functions","text":"Converters - Make date date-time text (character data) General String--Date Conversion: AS_DATE(), AS_DATETIME() Format-Specific String--Date Conversion: YMD() (YYYY-MM-DD), MDY() (MM-DD-YYYY), DMY() (DD-MM-YYYY) Hour-Minute-Second Conversion: YMD_HMS(), YMD_HM(), friends. Extractors - Returns information time-stamp. Extractors: SECOND(), MINUTE(), HOUR(), DAY(), WEEK(), MONTH(), QUARTER(), YEAR() Current Time - Returns current date/date-time based locale. NOW(), TODAY() Date Math - Perform popular Excel date calculations EOMONTH() - End Month NET_WORKDAYS(), COUNT_DAYS() - Return number days 2 dates factoring working days holidays YEARFRAC() - Return fractional period year completed 2 dates. Date Sequences - Return vector dates Holiday Table (tibble). DATE_SEQUENCE(), WORKDAY_SEQUENCE(), HOLIDAY_SEQUENCE - Return sequence dates 2 dates factor workdays timeDate holiday calendars popular business calendars including NYSE London stock exchange. Date Collapsers - Collapse date sequence (useful dplyr::group_by() pivot_table()) FLOOR_DATE(), FLOOR_DAY(), FLOOR_WEEK(), FLOOR_MONTH(), FLOOR_QUARTER(), FLOOR_YEAR() Similar functions exist CEILING ROUND. wrappers lubridate functions.","code":""},{"path":"/reference/excel_date_functions.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Excel Date and Time Functions — excel_date_functions","text":"","code":"# Libraries library(lubridate) # --- Basic Usage ---- # Converters --- AS_DATE(\"2011 Jan-01\") # General #> [1] \"2011-01-01\" YMD(\"2011 Jan-01\") # Year, Month-Day Format #> [1] \"2011-01-01\" MDY(\"01-02-20\") # Month-Day, Year Format (January 2nd, 2020) #> [1] \"2020-01-02\" DMY(\"01-02-20\") # Day-Month, Year Format (February 1st, 2020) #> [1] \"2020-02-01\" # Extractors --- WEEKDAY(\"2020-01-01\") # Labelled Day #> [1] 4 WEEKDAY(\"2020-01-01\", label = FALSE) # Numeric Day #> [1] 4 WEEKDAY(\"2020-01-01\", label = FALSE, week_start = 1) # Start at 1 (Monday) vs 7 (Sunday) #> [1] 3 MONTH(\"2020-01-01\") #> [1] 1 QUARTER(\"2020-01-01\") #> [1] 1 YEAR(\"2020-01-01\") #> [1] 2020 # Current Date-Time --- NOW() #> [1] \"2023-09-29 20:45:11 UTC\" TODAY() #> [1] \"2023-09-29\" # Date Math --- EOMONTH(\"2020-01-01\") #> [1] \"2020-01-31\" EOMONTH(\"2020-01-01\", months = 1) #> [1] \"2020-02-29\" NET_WORKDAYS(\"2020-01-01\", \"2020-07-01\") # 131 Skipping Weekends #> [1] 131 NET_WORKDAYS(\"2020-01-01\", \"2020-07-01\", holidays = HOLIDAY_SEQUENCE(\"2020-01-01\", \"2020-07-01\", calendar = \"NYSE\")) # 126 Skipping 5 NYSE Holidays #> [1] 126 # Date Sequences --- DATE_SEQUENCE(\"2020-01-01\", \"2020-07-01\") #> [1] \"2020-01-01\" \"2020-01-02\" \"2020-01-03\" \"2020-01-04\" \"2020-01-05\" #> [6] \"2020-01-06\" \"2020-01-07\" \"2020-01-08\" \"2020-01-09\" \"2020-01-10\" #> [11] \"2020-01-11\" \"2020-01-12\" \"2020-01-13\" \"2020-01-14\" \"2020-01-15\" #> [16] \"2020-01-16\" \"2020-01-17\" \"2020-01-18\" \"2020-01-19\" \"2020-01-20\" #> [21] \"2020-01-21\" \"2020-01-22\" \"2020-01-23\" \"2020-01-24\" \"2020-01-25\" #> [26] \"2020-01-26\" \"2020-01-27\" \"2020-01-28\" \"2020-01-29\" \"2020-01-30\" #> [31] \"2020-01-31\" \"2020-02-01\" \"2020-02-02\" \"2020-02-03\" \"2020-02-04\" #> [36] \"2020-02-05\" \"2020-02-06\" \"2020-02-07\" \"2020-02-08\" \"2020-02-09\" #> [41] \"2020-02-10\" \"2020-02-11\" \"2020-02-12\" \"2020-02-13\" \"2020-02-14\" #> [46] \"2020-02-15\" \"2020-02-16\" \"2020-02-17\" \"2020-02-18\" \"2020-02-19\" #> [51] \"2020-02-20\" \"2020-02-21\" \"2020-02-22\" \"2020-02-23\" \"2020-02-24\" #> [56] \"2020-02-25\" \"2020-02-26\" \"2020-02-27\" \"2020-02-28\" \"2020-02-29\" #> [61] \"2020-03-01\" \"2020-03-02\" \"2020-03-03\" \"2020-03-04\" \"2020-03-05\" #> [66] \"2020-03-06\" \"2020-03-07\" \"2020-03-08\" \"2020-03-09\" \"2020-03-10\" #> [71] \"2020-03-11\" \"2020-03-12\" \"2020-03-13\" \"2020-03-14\" \"2020-03-15\" #> [76] \"2020-03-16\" \"2020-03-17\" \"2020-03-18\" \"2020-03-19\" \"2020-03-20\" #> [81] \"2020-03-21\" \"2020-03-22\" \"2020-03-23\" \"2020-03-24\" \"2020-03-25\" #> [86] \"2020-03-26\" \"2020-03-27\" \"2020-03-28\" \"2020-03-29\" \"2020-03-30\" #> [91] \"2020-03-31\" \"2020-04-01\" \"2020-04-02\" \"2020-04-03\" \"2020-04-04\" #> [96] \"2020-04-05\" \"2020-04-06\" \"2020-04-07\" \"2020-04-08\" \"2020-04-09\" #> [101] \"2020-04-10\" \"2020-04-11\" \"2020-04-12\" \"2020-04-13\" \"2020-04-14\" #> [106] \"2020-04-15\" \"2020-04-16\" \"2020-04-17\" \"2020-04-18\" \"2020-04-19\" #> [111] \"2020-04-20\" \"2020-04-21\" \"2020-04-22\" \"2020-04-23\" \"2020-04-24\" #> [116] \"2020-04-25\" \"2020-04-26\" \"2020-04-27\" \"2020-04-28\" \"2020-04-29\" #> [121] \"2020-04-30\" \"2020-05-01\" \"2020-05-02\" \"2020-05-03\" \"2020-05-04\" #> [126] \"2020-05-05\" \"2020-05-06\" \"2020-05-07\" \"2020-05-08\" \"2020-05-09\" #> [131] \"2020-05-10\" \"2020-05-11\" \"2020-05-12\" \"2020-05-13\" \"2020-05-14\" #> [136] \"2020-05-15\" \"2020-05-16\" \"2020-05-17\" \"2020-05-18\" \"2020-05-19\" #> [141] \"2020-05-20\" \"2020-05-21\" \"2020-05-22\" \"2020-05-23\" \"2020-05-24\" #> [146] \"2020-05-25\" \"2020-05-26\" \"2020-05-27\" \"2020-05-28\" \"2020-05-29\" #> [151] \"2020-05-30\" \"2020-05-31\" \"2020-06-01\" \"2020-06-02\" \"2020-06-03\" #> [156] \"2020-06-04\" \"2020-06-05\" \"2020-06-06\" \"2020-06-07\" \"2020-06-08\" #> [161] \"2020-06-09\" \"2020-06-10\" \"2020-06-11\" \"2020-06-12\" \"2020-06-13\" #> [166] \"2020-06-14\" \"2020-06-15\" \"2020-06-16\" \"2020-06-17\" \"2020-06-18\" #> [171] \"2020-06-19\" \"2020-06-20\" \"2020-06-21\" \"2020-06-22\" \"2020-06-23\" #> [176] \"2020-06-24\" \"2020-06-25\" \"2020-06-26\" \"2020-06-27\" \"2020-06-28\" #> [181] \"2020-06-29\" \"2020-06-30\" \"2020-07-01\" WORKDAY_SEQUENCE(\"2020-01-01\", \"2020-07-01\") #> [1] \"2020-01-01\" \"2020-01-02\" \"2020-01-03\" \"2020-01-06\" \"2020-01-07\" #> [6] \"2020-01-08\" \"2020-01-09\" \"2020-01-10\" \"2020-01-13\" \"2020-01-14\" #> [11] \"2020-01-15\" \"2020-01-16\" \"2020-01-17\" \"2020-01-20\" \"2020-01-21\" #> [16] \"2020-01-22\" \"2020-01-23\" \"2020-01-24\" \"2020-01-27\" \"2020-01-28\" #> [21] \"2020-01-29\" \"2020-01-30\" \"2020-01-31\" \"2020-02-03\" \"2020-02-04\" #> [26] \"2020-02-05\" \"2020-02-06\" \"2020-02-07\" \"2020-02-10\" \"2020-02-11\" #> [31] \"2020-02-12\" \"2020-02-13\" \"2020-02-14\" \"2020-02-17\" \"2020-02-18\" #> [36] \"2020-02-19\" \"2020-02-20\" \"2020-02-21\" \"2020-02-24\" \"2020-02-25\" #> [41] \"2020-02-26\" \"2020-02-27\" \"2020-02-28\" \"2020-03-02\" \"2020-03-03\" #> [46] \"2020-03-04\" \"2020-03-05\" \"2020-03-06\" \"2020-03-09\" \"2020-03-10\" #> [51] \"2020-03-11\" \"2020-03-12\" \"2020-03-13\" \"2020-03-16\" \"2020-03-17\" #> [56] \"2020-03-18\" \"2020-03-19\" \"2020-03-20\" \"2020-03-23\" \"2020-03-24\" #> [61] \"2020-03-25\" \"2020-03-26\" \"2020-03-27\" \"2020-03-30\" \"2020-03-31\" #> [66] \"2020-04-01\" \"2020-04-02\" \"2020-04-03\" \"2020-04-06\" \"2020-04-07\" #> [71] \"2020-04-08\" \"2020-04-09\" \"2020-04-10\" \"2020-04-13\" \"2020-04-14\" #> [76] \"2020-04-15\" \"2020-04-16\" \"2020-04-17\" \"2020-04-20\" \"2020-04-21\" #> [81] \"2020-04-22\" \"2020-04-23\" \"2020-04-24\" \"2020-04-27\" \"2020-04-28\" #> [86] \"2020-04-29\" \"2020-04-30\" \"2020-05-01\" \"2020-05-04\" \"2020-05-05\" #> [91] \"2020-05-06\" \"2020-05-07\" \"2020-05-08\" \"2020-05-11\" \"2020-05-12\" #> [96] \"2020-05-13\" \"2020-05-14\" \"2020-05-15\" \"2020-05-18\" \"2020-05-19\" #> [101] \"2020-05-20\" \"2020-05-21\" \"2020-05-22\" \"2020-05-25\" \"2020-05-26\" #> [106] \"2020-05-27\" \"2020-05-28\" \"2020-05-29\" \"2020-06-01\" \"2020-06-02\" #> [111] \"2020-06-03\" \"2020-06-04\" \"2020-06-05\" \"2020-06-08\" \"2020-06-09\" #> [116] \"2020-06-10\" \"2020-06-11\" \"2020-06-12\" \"2020-06-15\" \"2020-06-16\" #> [121] \"2020-06-17\" \"2020-06-18\" \"2020-06-19\" \"2020-06-22\" \"2020-06-23\" #> [126] \"2020-06-24\" \"2020-06-25\" \"2020-06-26\" \"2020-06-29\" \"2020-06-30\" #> [131] \"2020-07-01\" HOLIDAY_SEQUENCE(\"2020-01-01\", \"2020-07-01\", calendar = \"NYSE\") #> [1] \"2020-01-01\" \"2020-01-20\" \"2020-02-17\" \"2020-04-10\" \"2020-05-25\" WORKDAY_SEQUENCE(\"2020-01-01\", \"2020-07-01\", holidays = HOLIDAY_SEQUENCE(\"2020-01-01\", \"2020-07-01\", calendar = \"NYSE\")) #> [1] \"2020-01-02\" \"2020-01-03\" \"2020-01-06\" \"2020-01-07\" \"2020-01-08\" #> [6] \"2020-01-09\" \"2020-01-10\" \"2020-01-13\" \"2020-01-14\" \"2020-01-15\" #> [11] \"2020-01-16\" \"2020-01-17\" \"2020-01-21\" \"2020-01-22\" \"2020-01-23\" #> [16] \"2020-01-24\" \"2020-01-27\" \"2020-01-28\" \"2020-01-29\" \"2020-01-30\" #> [21] \"2020-01-31\" \"2020-02-03\" \"2020-02-04\" \"2020-02-05\" \"2020-02-06\" #> [26] \"2020-02-07\" \"2020-02-10\" \"2020-02-11\" \"2020-02-12\" \"2020-02-13\" #> [31] \"2020-02-14\" \"2020-02-18\" \"2020-02-19\" \"2020-02-20\" \"2020-02-21\" #> [36] \"2020-02-24\" \"2020-02-25\" \"2020-02-26\" \"2020-02-27\" \"2020-02-28\" #> [41] \"2020-03-02\" \"2020-03-03\" \"2020-03-04\" \"2020-03-05\" \"2020-03-06\" #> [46] \"2020-03-09\" \"2020-03-10\" \"2020-03-11\" \"2020-03-12\" \"2020-03-13\" #> [51] \"2020-03-16\" \"2020-03-17\" \"2020-03-18\" \"2020-03-19\" \"2020-03-20\" #> [56] \"2020-03-23\" \"2020-03-24\" \"2020-03-25\" \"2020-03-26\" \"2020-03-27\" #> [61] \"2020-03-30\" \"2020-03-31\" \"2020-04-01\" \"2020-04-02\" \"2020-04-03\" #> [66] \"2020-04-06\" \"2020-04-07\" \"2020-04-08\" \"2020-04-09\" \"2020-04-13\" #> [71] \"2020-04-14\" \"2020-04-15\" \"2020-04-16\" \"2020-04-17\" \"2020-04-20\" #> [76] \"2020-04-21\" \"2020-04-22\" \"2020-04-23\" \"2020-04-24\" \"2020-04-27\" #> [81] \"2020-04-28\" \"2020-04-29\" \"2020-04-30\" \"2020-05-01\" \"2020-05-04\" #> [86] \"2020-05-05\" \"2020-05-06\" \"2020-05-07\" \"2020-05-08\" \"2020-05-11\" #> [91] \"2020-05-12\" \"2020-05-13\" \"2020-05-14\" \"2020-05-15\" \"2020-05-18\" #> [96] \"2020-05-19\" \"2020-05-20\" \"2020-05-21\" \"2020-05-22\" \"2020-05-26\" #> [101] \"2020-05-27\" \"2020-05-28\" \"2020-05-29\" \"2020-06-01\" \"2020-06-02\" #> [106] \"2020-06-03\" \"2020-06-04\" \"2020-06-05\" \"2020-06-08\" \"2020-06-09\" #> [111] \"2020-06-10\" \"2020-06-11\" \"2020-06-12\" \"2020-06-15\" \"2020-06-16\" #> [116] \"2020-06-17\" \"2020-06-18\" \"2020-06-19\" \"2020-06-22\" \"2020-06-23\" #> [121] \"2020-06-24\" \"2020-06-25\" \"2020-06-26\" \"2020-06-29\" \"2020-06-30\" #> [126] \"2020-07-01\" # Date Collapsers --- FLOOR_DATE(AS_DATE(\"2020-01-15\"), by = \"month\") #> [1] \"2020-01-01\" CEILING_DATE(AS_DATE(\"2020-01-15\"), by = \"month\") #> [1] \"2020-02-01\" CEILING_DATE(AS_DATE(\"2020-01-15\"), by = \"month\") - ddays(1) # EOMONTH using lubridate #> [1] \"2020-01-31\" # --- Usage with tidyverse --- # Calculate returns by symbol/year/quarter FANG %>% pivot_table( .rows = c(symbol, ~ QUARTER(date)), .columns = ~ YEAR(date), .values = ~ PCT_CHANGE_FIRSTLAST(adjusted) ) #> # A tibble: 16 × 6 #> symbol `QUARTER(date)` `2013` `2014` `2015` `2016` #> #> 1 AMZN 1 0.0357 -0.155 0.206 -0.0681 #> 2 AMZN 2 0.0615 -0.0531 0.172 0.196 #> 3 AMZN 3 0.108 -0.0299 0.170 0.154 #> 4 AMZN 4 0.243 -0.0224 0.298 -0.104 #> 5 GOOG 1 0.0981 0.00174 0.0442 0.00419 #> 6 GOOG 2 0.0988 0.0143 -0.0406 -0.0771 #> 7 GOOG 3 -0.0135 -0.00911 0.166 0.112 #> 8 GOOG 4 0.263 -0.0737 0.241 -0.000958 #> 9 META 1 -0.0864 0.101 0.0481 0.116 #> 10 META 2 -0.0255 0.0746 0.0502 -0.0153 #> 11 META 3 1.02 0.161 0.0344 0.123 #> 12 META 4 0.0839 0.0192 0.151 -0.107 #> 13 NFLX 1 1.06 -0.0297 0.194 -0.0703 #> 14 NFLX 2 0.157 0.208 0.590 -0.135 #> 15 NFLX 3 0.379 -0.0463 0.103 0.0194 #> 16 NFLX 4 0.134 -0.221 0.0793 0.206"},{"path":"/reference/excel_financial_math_functions.html","id":null,"dir":"Reference","previous_headings":"","what":"Excel Financial Math Functions — excel_financial_math_functions","title":"Excel Financial Math Functions — excel_financial_math_functions","text":"Excel financial math functions designed easily calculate Net Present Value (NPV()), Future Value cashflow (FV()), Present Value future cashflow (PV()), . functions designed help users coming Excel background. functions replicate behavior Excel: Names similar Excel function names default, missing values ignored (Excel)","code":""},{"path":"/reference/excel_financial_math_functions.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Excel Financial Math Functions — excel_financial_math_functions","text":"","code":"NPV(cashflow, rate, nper = NULL) IRR(cashflow) FV(rate, nper, pv = 0, pmt = 0, type = 0) PV(rate, nper, fv = 0, pmt = 0, type = 0) PMT(rate, nper, pv, fv = 0, type = 0) RATE(nper, pmt, pv, fv = 0, type = 0)"},{"path":"/reference/excel_financial_math_functions.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Excel Financial Math Functions — excel_financial_math_functions","text":"cashflow Cash flow values. one value provided, assumed constant cash flow. rate One rate. one rate provided assumed constant rate. nper Number periods. `nper`` provided, cashflow values rate assumed constant. pv Present value. Initial investments (cash inflows) typcially negative value. pmt Number payments per period. type payments (pmt) occur beginning (type = 0) end (type = 1) period. fv Future value. Cash outflows typically positive value.","code":""},{"path":"/reference/excel_financial_math_functions.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Excel Financial Math Functions — excel_financial_math_functions","text":"Summary functions return single value","code":""},{"path":"/reference/excel_financial_math_functions.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Excel Financial Math Functions — excel_financial_math_functions","text":"Net Present Value (NPV) Net present value (NPV) difference present value cash inflows present value cash outflows period time. NPV used capital budgeting investment planning analyze profitability projected investment project. information, see Investopedia NPV. Internal Rate Return (IRR) internal rate return (IRR) metric used capital budgeting estimate profitability potential investments. internal rate return discount rate makes net present value (NPV) cash flows particular project equal zero. IRR calculations rely formula NPV . information, see Investopedia IRR. Future Value (FV) Future value (FV) value current asset future date based assumed rate growth. future value (FV) important investors financial planners use estimate much investment made today worth future. Knowing future value enables investors make sound investment decisions based anticipated needs. However, external economic factors, inflation, can adversely affect future value asset eroding value. information, see Investopedia FV. Present Value (PV) Present value (PV) current value future sum money stream cash flows given specified rate return. Future cash flows discounted discount rate, higher discount rate, lower present value future cash flows. Determining appropriate discount rate key properly valuing future cash flows, whether earnings obligations. information, see Investopedia PV. Payment (PMT) Payment PMT() function calculates payment loan based constant payments constant interest rate. Rate (RATE) Returns interest rate per period loan investment. example, use 6%/4 quarterly payments 6% APR.","code":""},{"path":"/reference/excel_financial_math_functions.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Excel Financial Math Functions — excel_financial_math_functions","text":"","code":"NPV(c(-1000, 250, 350, 450, 450), rate = 0.05) #> [1] 314.4986 IRR(c(-1000, 250, 350, 450, 450)) #> [1] 0.1656206 FV(rate = 0.05, nper = 5, pv = -100, pmt = 0, type = 0) #> [1] 127.6282 PV(rate = 0.05, nper = 5, fv = -100, pmt = 0, type = 0) #> [1] 78.35262 PMT(nper = 20, rate = 0.05, pv = -100, fv = 0, type = 0) #> [1] 8.024259 RATE(nper = 20, pmt = 8, pv = -100, fv = 0, type = 0) #> [1] 0.04964019"},{"path":"/reference/excel_if_functions.html","id":null,"dir":"Reference","previous_headings":"","what":"Excel Summarising ","title":"Excel Summarising ","text":"\"IFS\" functions filtering versions summarization counterparts. Simply add \"cases\" filter condition true. Multiple cases evaluated \"\" filtering operations. single case | (\"\") bars can created accomplish \"\". See details . functions designed help users coming Excel background. functions replicate behavior Excel: Names similar Excel function names default, missing values ignored (Excel)","code":""},{"path":"/reference/excel_if_functions.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Excel Summarising ","text":"","code":"SUM_IFS(x, ...) COUNT_IFS(x, ...) AVERAGE_IFS(x, ...) MEDIAN_IFS(x, ...) MIN_IFS(x, ...) MAX_IFS(x, ...) CREATE_IFS(.f, ...)"},{"path":"/reference/excel_if_functions.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Excel Summarising ","text":"x vector. functions designed numeric data. functions like COUNT_IFS() handle multiple data types. ... Add cases evaluate. See Details. .f function convert \"IFS\" function. Use ... case provide parameters .f like na.rm = TRUE.","code":""},{"path":"/reference/excel_if_functions.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Excel Summarising ","text":"Summary functions return single value","code":""},{"path":"/reference/excel_if_functions.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Excel Summarising ","text":"\"\" Filtering: Multiple cases evaluated \"\" filtering operations. \"\" Filtering: Compound single cases | (\"\") bars can created accomplish \"\". Simply use statement like x > 10 | x < -10 perform \"\" -statement. Creating New \"Summarizing IFS\" Functions: Users can create new \"IFS\" functions using CREATE_IFS() function factory. requirement output function (.f) must single value (scalar). See examples .","code":""},{"path":"/reference/excel_if_functions.html","id":"useful-functions","dir":"Reference","previous_headings":"","what":"Useful Functions","title":"Excel Summarising ","text":"Summary Functions - Return single value vector Sum: SUM_IFS() Center: AVERAGE_IFS(), MEDIAN_IFS() Count: COUNT_IFS() Range: MIN_IFS(), MAX_IFS() Create summary \"IFS\" function CREATE_IFS(): function factory generates summary \"_IFS\" functions.","code":""},{"path":"/reference/excel_if_functions.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Excel Summarising ","text":"","code":"library(dplyr) library(timetk) #> #> Attaching package: ‘timetk’ #> The following object is masked from ‘package:tidyquant’: #> #> FANG library(stringr) library(lubridate) # --- Basic Usage --- SUM_IFS(x = 1:10, x > 5) #> [1] 40 COUNT_IFS(x = letters, str_detect(x, \"a|b|c\")) #> [1] 3 SUM_IFS(-10:10, x > 8 | x < -5) #> [1] -21 # Create your own IFS function (Mind blowingly simple)! Q75_IFS <- CREATE_IFS(.f = quantile, probs = 0.75, na.rm = TRUE) Q75_IFS(1:10, x > 5) #> 75% #> 9 # --- Usage with tidyverse --- # Using multiple cases IFS cases to count the frequency of days with # high trade volume in a given year FANG %>% group_by(symbol) %>% summarise( high_volume_in_2015 = COUNT_IFS(volume, year(date) == 2015, volume > quantile(volume, 0.75)) ) #> # A tibble: 4 × 2 #> symbol high_volume_in_2015 #> #> 1 AMZN 62 #> 2 FB 15 #> 3 GOOG 19 #> 4 NFLX 54 # Count negative returns by month FANG %>% mutate(symbol = forcats::as_factor(symbol)) %>% group_by(symbol) %>% # Collapse from daily to FIRST value by month summarise_by_time( .date_var = date, .by = \"month\", adjusted = FIRST(adjusted) ) %>% # Calculate monthly returns group_by(symbol) %>% mutate( returns = PCT_CHANGE(adjusted, fill_na = 0) ) %>% # Find returns less than zero and count the frequency summarise( negative_monthly_returns = COUNT_IFS(returns, returns < 0) ) #> # A tibble: 4 × 2 #> symbol negative_monthly_returns #> #> 1 FB 16 #> 2 AMZN 16 #> 3 NFLX 16 #> 4 GOOG 20"},{"path":"/reference/excel_pivot_table.html","id":null,"dir":"Reference","previous_headings":"","what":"Excel Pivot Table — excel_pivot_table","title":"Excel Pivot Table — excel_pivot_table","text":"Pivot Table one Excel's powerful features, now available R! pivot table table statistics summarizes data extensive table (database, spreadsheet, business intelligence program). functions designed help users coming Excel background. functions replicate behavior Excel: Names similar Excel function names Functionality replicates Excel","code":""},{"path":"/reference/excel_pivot_table.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Excel Pivot Table — excel_pivot_table","text":"","code":"pivot_table( .data, .rows, .columns, .values, .filters = NULL, .sort = NULL, fill_na = NA )"},{"path":"/reference/excel_pivot_table.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Excel Pivot Table — excel_pivot_table","text":".data data.frame tibble contains data summarize pivot table .rows Enter one groups assess expressions (e.g. ~ MONTH(date_column)) .columns Enter one groups assess expressions (e.g. ~ YEAR(date_column)) .values Numeric . Enter one summarization expression(s) (e.g. ~ SUM(value_column)) .filters argument yet use .sort argument yet use fill_na value replace missing values . Default NA","code":""},{"path":"/reference/excel_pivot_table.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Excel Pivot Table — excel_pivot_table","text":"Returns tibble pivoted summarize information column row groupings","code":""},{"path":"/reference/excel_pivot_table.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Excel Pivot Table — excel_pivot_table","text":"summary might include sums, averages, statistics, pivot table groups together meaningful way. key parameters : .rows - groups appear row-wise headings summarization, can modify groups applying collapsing functions (e.g. (YEAR()). .columns - groups appear column headings summarization. can modify groups applying collapsing functions (e.g. (YEAR()). .values - numeric data summarized using summary function (e.g. SUM(), AVERAGE(), COUNT(), FIRST(), LAST(), SUM_IFS(), AVERAGE_IFS(), COUNT_IFS()) R implementation details. pivot_table() function powered tidyverse, ecosystem packages designed manipulate data. key parameters can expressed using functional form: Rows Column Groupings can collapsed. Example: .columns = ~ YEAR(order_date) Values can summarized provided single value returned. Example: .values = ~ SUM_IFS(order_volume >= quantile(order_volume, probs = 0.75)) Summarizations Row/Column Groupings can stacked (combined) c(). Example: .rows = c(~ YEAR(order_date), company) Bare columns (e.g. company) don need prefixed ~. grouping summarizing functions MUST prefixed ~. Example: .rows = ~ YEAR(order_date)","code":""},{"path":"/reference/excel_pivot_table.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Excel Pivot Table — excel_pivot_table","text":"","code":"# PIVOT TABLE ---- # Calculate returns by year/quarter FANG %>% pivot_table( .rows = c(symbol, ~ QUARTER(date)), .columns = ~ YEAR(date), .values = ~ PCT_CHANGE_FIRSTLAST(adjusted) ) #> # A tibble: 16 × 6 #> symbol `QUARTER(date)` `2013` `2014` `2015` `2016` #> #> 1 AMZN 1 0.0357 -0.155 0.206 -0.0681 #> 2 AMZN 2 0.0615 -0.0531 0.172 0.196 #> 3 AMZN 3 0.108 -0.0299 0.170 0.154 #> 4 AMZN 4 0.243 -0.0224 0.298 -0.104 #> 5 FB 1 -0.0864 0.101 0.0481 0.116 #> 6 FB 2 -0.0255 0.0746 0.0502 -0.0153 #> 7 FB 3 1.02 0.161 0.0344 0.123 #> 8 FB 4 0.0839 0.0192 0.151 -0.107 #> 9 GOOG 1 0.0981 0.00174 0.0442 0.00419 #> 10 GOOG 2 0.0988 0.0143 -0.0406 -0.0771 #> 11 GOOG 3 -0.0135 -0.00911 0.166 0.112 #> 12 GOOG 4 0.263 -0.0737 0.241 -0.000958 #> 13 NFLX 1 1.06 -0.0297 0.194 -0.0703 #> 14 NFLX 2 0.157 0.208 0.590 -0.135 #> 15 NFLX 3 0.379 -0.0463 0.103 0.0194 #> 16 NFLX 4 0.134 -0.221 0.0793 0.206"},{"path":"/reference/excel_ref_functions.html","id":null,"dir":"Reference","previous_headings":"","what":"Excel Reference Functions — excel_ref_functions","title":"Excel Reference Functions — excel_ref_functions","text":"Excel reference functions used efficiently lookup values data source. popular lookup function \"VLOOKUP\", implemented R. functions designed help users coming Excel background. functions replicate behavior Excel: Names similar Excel function names Functionality replicates Excel","code":""},{"path":"/reference/excel_ref_functions.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Excel Reference Functions — excel_ref_functions","text":"","code":"VLOOKUP(.lookup_values, .data, .lookup_column, .return_column)"},{"path":"/reference/excel_ref_functions.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Excel Reference Functions — excel_ref_functions","text":".lookup_values One lookup values. .data data.frame tibble contains values evaluate return .lookup_column column .data containing exact matching values .lookup_values .return_column column .data containing values return match found","code":""},{"path":"/reference/excel_ref_functions.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Excel Reference Functions — excel_ref_functions","text":"Returns vector length input lookup values","code":""},{"path":"/reference/excel_ref_functions.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Excel Reference Functions — excel_ref_functions","text":"VLOOKUP() Details Performs exact matching . Fuzzy matching implemented. Can return values one column . Use dplyr::left_join() perform table joining.","code":""},{"path":"/reference/excel_ref_functions.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Excel Reference Functions — excel_ref_functions","text":"","code":"library(dplyr) lookup_table <- tibble( stock = c(\"META\", \"AMZN\", \"NFLX\", \"GOOG\"), company = c(\"Facebook\", \"Amazon\", \"Netflix\", \"Google\") ) # --- Basic Usage --- VLOOKUP(\"NFLX\", .data = lookup_table, .lookup_column = stock, .return_column = company) #> [1] \"Netflix\" # --- Usage with tidyverse --- # Add company names to the stock data FANG %>% mutate(company = VLOOKUP(symbol, lookup_table, stock, company)) #> # A tibble: 4,032 × 9 #> symbol date open high low close volume adjusted company #> #> 1 FB 2013-01-02 27.4 28.2 27.4 28 69846400 28 NA #> 2 FB 2013-01-03 27.9 28.5 27.6 27.8 63140600 27.8 NA #> 3 FB 2013-01-04 28.0 28.9 27.8 28.8 72715400 28.8 NA #> 4 FB 2013-01-07 28.7 29.8 28.6 29.4 83781800 29.4 NA #> 5 FB 2013-01-08 29.5 29.6 28.9 29.1 45871300 29.1 NA #> 6 FB 2013-01-09 29.7 30.6 29.5 30.6 104787700 30.6 NA #> 7 FB 2013-01-10 30.6 31.5 30.3 31.3 95316400 31.3 NA #> 8 FB 2013-01-11 31.3 32.0 31.1 31.7 89598000 31.7 NA #> 9 FB 2013-01-14 32.1 32.2 30.6 31.0 98892800 31.0 NA #> 10 FB 2013-01-15 30.6 31.7 29.9 30.1 173242600 30.1 NA #> # ℹ 4,022 more rows"},{"path":"/reference/excel_stat_mutation_functions.html","id":null,"dir":"Reference","previous_headings":"","what":"Excel Statistical Mutation Functions — excel_stat_mutation_functions","title":"Excel Statistical Mutation Functions — excel_stat_mutation_functions","text":"15+ common statistical functions familiar users Excel (e.g. ABS(), SQRT()) modify / transform series values (.e. vector length input returned). functions designed help users coming Excel background. functions replicate behavior Excel: Names cases match Excel function names Functionality replicates Excel default, missing values ignored (Excel)","code":""},{"path":"/reference/excel_stat_mutation_functions.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Excel Statistical Mutation Functions — excel_stat_mutation_functions","text":"","code":"ABS(x) SQRT(x) LOG(x) EXP(x) RETURN(x, n = 1, fill_na = NA) PCT_CHANGE(x, n = 1, fill_na = NA) CHANGE(x, n = 1, fill_na = NA) LAG(x, n = 1, fill_na = NA) LEAD(x, n = 1, fill_na = NA) CUMULATIVE_SUM(x) CUMULATIVE_PRODUCT(x) CUMULATIVE_MAX(x) CUMULATIVE_MIN(x) CUMULATIVE_MEAN(x) CUMULATIVE_MEDIAN(x)"},{"path":"/reference/excel_stat_mutation_functions.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Excel Statistical Mutation Functions — excel_stat_mutation_functions","text":"x vector. functions designed numeric data. n Values offset. Used functions like LAG(), LEAD(), PCT_CHANGE() fill_na Fill missing (NA) values different value. Used offsetting functions.","code":""},{"path":"/reference/excel_stat_mutation_functions.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Excel Statistical Mutation Functions — excel_stat_mutation_functions","text":"Mutation functions return mutated / transformed version vector","code":""},{"path":"/reference/excel_stat_mutation_functions.html","id":"useful-functions","dir":"Reference","previous_headings":"","what":"Useful functions","title":"Excel Statistical Mutation Functions — excel_stat_mutation_functions","text":"Mutation Functions - Transforms vector Transformation: ABS(), SQRT(), LOG(), EXP() Lags & Change (Offsetting Functions): CHANGE(), PCT_CHANGE(), LAG(), LEAD() Cumulative Totals: CUMULATIVE_SUM(), CUMULATIVE_PRODUCT()","code":""},{"path":"/reference/excel_stat_mutation_functions.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Excel Statistical Mutation Functions — excel_stat_mutation_functions","text":"","code":"# Libraries library(timetk) library(dplyr) # --- Basic Usage ---- CUMULATIVE_SUM(1:10) #> [1] 1 3 6 10 15 21 28 36 45 55 PCT_CHANGE(c(21, 24, 22, 25), fill_na = 0) #> [1] 0.00000000 0.14285714 -0.08333333 0.13636364 # --- Usage with tidyverse --- # Go from daily to monthly periodicity, # then calculate returns and growth of $1 USD FANG %>% mutate(symbol = forcats::as_factor(symbol)) %>% group_by(symbol) %>% # Summarization - Collapse from daily to FIRST value by month summarise_by_time( .date_var = date, .by = \"month\", adjusted = FIRST(adjusted) ) %>% # Mutation - Calculate monthly returns and cumulative growth of $1 USD group_by(symbol) %>% mutate( returns = PCT_CHANGE(adjusted, fill_na = 0), growth = CUMULATIVE_SUM(returns) + 1 ) #> # A tibble: 192 × 5 #> # Groups: symbol [4] #> symbol date adjusted returns growth #> #> 1 FB 2013-01-01 28 0 1 #> 2 FB 2013-02-01 29.7 0.0618 1.06 #> 3 FB 2013-03-01 27.8 -0.0656 0.996 #> 4 FB 2013-04-01 25.5 -0.0810 0.915 #> 5 FB 2013-05-01 27.4 0.0744 0.990 #> 6 FB 2013-06-01 23.8 -0.131 0.859 #> 7 FB 2013-07-01 24.8 0.0403 0.899 #> 8 FB 2013-08-01 37.5 0.511 1.41 #> 9 FB 2013-09-01 41.9 0.117 1.53 #> 10 FB 2013-10-01 50.4 0.204 1.73 #> # ℹ 182 more rows"},{"path":"/reference/excel_stat_summary_functions.html","id":null,"dir":"Reference","previous_headings":"","what":"Excel Statistical Summary Functions — excel_stat_summary_functions","title":"Excel Statistical Summary Functions — excel_stat_summary_functions","text":"15+ common statistical functions familiar users Excel (e.g. SUM(), AVERAGE()). functions return single value (.e. vector length 1). functions designed help users coming Excel background. functions replicate behavior Excel: Names cases match Excel function names Functionality replicates Excel default, missing values ignored (Excel)","code":""},{"path":"/reference/excel_stat_summary_functions.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Excel Statistical Summary Functions — excel_stat_summary_functions","text":"","code":"SUM(x) AVERAGE(x) MEDIAN(x) MIN(x) MAX(x) COUNT(x) COUNT_UNIQUE(x) STDEV(x) VAR(x) COR(x, y) COV(x, y) FIRST(x) LAST(x) NTH(x, n = 1) CHANGE_FIRSTLAST(x) PCT_CHANGE_FIRSTLAST(x)"},{"path":"/reference/excel_stat_summary_functions.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Excel Statistical Summary Functions — excel_stat_summary_functions","text":"x vector. functions designed numeric data. functions like COUNT() handle multiple data types. y vector. Used functions requiring 2 inputs. n single value used NTH() select specific element location return.","code":""},{"path":"/reference/excel_stat_summary_functions.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Excel Statistical Summary Functions — excel_stat_summary_functions","text":"Summary functions return single value","code":""},{"path":"/reference/excel_stat_summary_functions.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Excel Statistical Summary Functions — excel_stat_summary_functions","text":"Summary Functions functions remove missing values (NA). behavior Excel commonly desired.","code":""},{"path":"/reference/excel_stat_summary_functions.html","id":"useful-functions","dir":"Reference","previous_headings":"","what":"Useful functions","title":"Excel Statistical Summary Functions — excel_stat_summary_functions","text":"Summary Functions - Return single value vector Sum: SUM() Center: AVERAGE(), MEDIAN() Spread: STDEV(), VAR() Range: MIN(), MAX() Count: COUNT(), COUNT_UNIQUE() Position: FIRST(), LAST(), NTH() Change (Summary): CHANGE_FIRSTLAST(), PCT_CHANGE_FIRSTLAST() Correlation: COR(), COV()","code":""},{"path":"/reference/excel_stat_summary_functions.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Excel Statistical Summary Functions — excel_stat_summary_functions","text":"","code":"# Libraries library(timetk) library(forcats) library(dplyr) # --- Basic Usage ---- SUM(1:10) #> [1] 55 PCT_CHANGE_FIRSTLAST(c(21, 24, 22, 25)) #> [1] 0.1904762 # --- Usage with tidyverse --- # Go from daily to monthly periodicity, # then calculate returns and growth of $1 USD FANG %>% mutate(symbol = forcats::as_factor(symbol)) %>% group_by(symbol) %>% # Summarization - Collapse from daily to FIRST value by month summarise_by_time( .date_var = date, .by = \"month\", adjusted = FIRST(adjusted) ) #> # A tibble: 192 × 3 #> # Groups: symbol [4] #> symbol date adjusted #> #> 1 FB 2013-01-01 28 #> 2 FB 2013-02-01 29.7 #> 3 FB 2013-03-01 27.8 #> 4 FB 2013-04-01 25.5 #> 5 FB 2013-05-01 27.4 #> 6 FB 2013-06-01 23.8 #> 7 FB 2013-07-01 24.8 #> 8 FB 2013-08-01 37.5 #> 9 FB 2013-09-01 41.9 #> 10 FB 2013-10-01 50.4 #> # ℹ 182 more rows"},{"path":"/reference/geom_bbands.html","id":null,"dir":"Reference","previous_headings":"","what":"Plot Bollinger Bands using Moving Averages — geom_bbands","title":"Plot Bollinger Bands using Moving Averages — geom_bbands","text":"Bollinger Bands plot range around moving average typically two standard deviations . geom_bbands() function enables plotting Bollinger Bands quickly using various moving average functions. moving average functions used specified TTR::SMA() TTR package. Use coord_x_date() zoom specific plot regions. following moving averages available: Simple moving averages (SMA): Rolling mean period defined n. Exponential moving averages (EMA): Includes exponentially-weighted mean gives weight recent observations. Uses wilder ratio args. Weighted moving averages (WMA): Uses set weights, wts, weight observations moving average. Double exponential moving averages (DEMA): Uses v volume factor, wilder ratio args. Zero-lag exponential moving averages (ZLEMA): Uses wilder ratio args. Volume-weighted moving averages (VWMA): Requires volume aesthetic. Elastic, volume-weighted moving averages (EVWMA): Requires volume aesthetic.","code":""},{"path":"/reference/geom_bbands.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Plot Bollinger Bands using Moving Averages — geom_bbands","text":"","code":"geom_bbands( mapping = NULL, data = NULL, position = \"identity\", na.rm = TRUE, show.legend = NA, inherit.aes = TRUE, ma_fun = SMA, n = 20, sd = 2, wilder = FALSE, ratio = NULL, v = 1, wts = 1:n, color_ma = \"darkblue\", color_bands = \"red\", alpha = 0.15, fill = \"grey20\", ... ) geom_bbands_( mapping = NULL, data = NULL, position = \"identity\", na.rm = TRUE, show.legend = NA, inherit.aes = TRUE, ma_fun = \"SMA\", n = 10, sd = 2, wilder = FALSE, ratio = NULL, v = 1, wts = 1:n, color_ma = \"darkblue\", color_bands = \"red\", alpha = 0.15, fill = \"grey20\", ... )"},{"path":"/reference/geom_bbands.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Plot Bollinger Bands using Moving Averages — geom_bbands","text":"mapping Set aesthetic mappings created ggplot2::aes() ggplot2::aes_(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot2::ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See ggplot2::fortify() variables created. function called single argument, plot data. return value must data.frame., used layer data. position Position adjustment, either string naming adjustment (e.g. \"jitter\" use position_jitter), result call position adjustment function. Use latter need change settings adjustment. na.rm TRUE, silently removes NA values, typically desired moving averages. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. ggplot2::borders(). ma_fun function used calculate moving average. Seven options available including: SMA, EMA, WMA, DEMA, ZLEMA, VWMA, EVWMA. default SMA. See TTR::SMA() underlying functions. n Number periods average . Must 1 nrow(x), inclusive. sd number standard deviations use. wilder logical; TRUE, Welles Wilder type EMA calculated; see notes. ratio smoothing/decay ratio. ratio overrides wilder EMA, provides additional smoothing VMA. v 'volume factor' (number [0,1]). See Notes. wts Vector weights. Length wts vector must equal length x, n (default). color_ma, color_bands Select line color applied moving average line Bollinger band line. alpha Used adjust alpha transparency BBand ribbon. fill Used adjust fill color BBand ribbon. ... arguments passed ggplot2::layer(). often aesthetics, used set aesthetic fixed value, like color = \"red\" size = 3. may also parameters paired geom/stat.","code":""},{"path":"/reference/geom_bbands.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Plot Bollinger Bands using Moving Averages — geom_bbands","text":"following aesthetics understood (required bold): x, Typically date high, Required high price low, Required low price close, Required close price volume, Required VWMA EVWMA colour, Affects line colors fill, Affects ribbon fill color alpha, Affects ribbon alpha value group linetype size","code":""},{"path":[]},{"path":"/reference/geom_bbands.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Plot Bollinger Bands using Moving Averages — geom_bbands","text":"","code":"library(dplyr) library(ggplot2) AAPL <- tq_get(\"AAPL\", from = \"2013-01-01\", to = \"2016-12-31\") # SMA AAPL %>% ggplot(aes(x = date, y = close)) + geom_line() + # Plot stock price geom_bbands(aes(high = high, low = low, close = close), ma_fun = SMA, n = 50) + coord_x_date(xlim = c(as_date(\"2016-12-31\") - dyears(1), as_date(\"2016-12-31\")), ylim = c(75, 125)) #> Warning: The following aesthetics were dropped during statistical transformation: high, #> low, close, y #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor? #> Warning: The following aesthetics were dropped during statistical transformation: high, #> low, close #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor? # EMA AAPL %>% ggplot(aes(x = date, y = close)) + geom_line() + # Plot stock price geom_bbands(aes(high = high, low = low, close = close), ma_fun = EMA, wilder = TRUE, ratio = NULL, n = 50) + coord_x_date(xlim = c(as_date(\"2016-12-31\") - dyears(1), as_date(\"2016-12-31\")), ylim = c(75, 125)) #> Warning: The following aesthetics were dropped during statistical transformation: high, #> low, close, y #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor? #> Warning: The following aesthetics were dropped during statistical transformation: high, #> low, close #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor? # VWMA AAPL %>% ggplot(aes(x = date, y = close)) + geom_line() + # Plot stock price geom_bbands(aes(high = high, low = low, close = close, volume = volume), ma_fun = VWMA, n = 50) + coord_x_date(xlim = c(as_date(\"2016-12-31\") - dyears(1), as_date(\"2016-12-31\")), ylim = c(75, 125)) #> Warning: The following aesthetics were dropped during statistical transformation: high, #> low, close, volume, y #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor? #> Warning: The following aesthetics were dropped during statistical transformation: high, #> low, close, volume #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor?"},{"path":"/reference/geom_chart.html","id":null,"dir":"Reference","previous_headings":"","what":"Plot Financial Charts in ggplot2 — geom_chart","title":"Plot Financial Charts in ggplot2 — geom_chart","text":"Financial charts provide visual cues open, high, low, close prices. Use coord_x_date() zoom specific plot regions. following financial chart geoms available: Bar Chart Candlestick Chart","code":""},{"path":"/reference/geom_chart.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Plot Financial Charts in ggplot2 — geom_chart","text":"","code":"geom_barchart( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", na.rm = TRUE, show.legend = NA, inherit.aes = TRUE, colour_up = \"darkblue\", colour_down = \"red\", fill_up = \"darkblue\", fill_down = \"red\", ... ) geom_candlestick( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", na.rm = TRUE, show.legend = NA, inherit.aes = TRUE, colour_up = \"darkblue\", colour_down = \"red\", fill_up = \"darkblue\", fill_down = \"red\", ... )"},{"path":"/reference/geom_chart.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Plot Financial Charts in ggplot2 — geom_chart","text":"mapping Set aesthetic mappings created ggplot2::aes() ggplot2::aes_(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot2::ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See ggplot2::fortify() variables created. function called single argument, plot data. return value must data.frame., used layer data. stat statistical transformation use data layer, either ggproto Geom subclass string naming stat stripped stat_ prefix (e.g. \"count\" rather \"stat_count\") position Position adjustment, either string naming adjustment (e.g. \"jitter\" use position_jitter), result call position adjustment function. Use latter need change settings adjustment. na.rm TRUE, silently removes NA values, typically desired moving averages. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. ggplot2::borders(). colour_up, colour_down Select colors applied based price movement open close. close >= open, colour_up used. Otherwise, colour_down used. default \"darkblue\" \"red\", respectively. fill_up, fill_down Select fills applied based price movement open close. close >= open, fill_up used. Otherwise, fill_down used. default \"darkblue\" \"red\", respectively. affects geom_candlestick. ... arguments passed ggplot2::layer(). often aesthetics, used set aesthetic fixed value, like color = \"red\" size = 3. may also parameters paired geom/stat.","code":""},{"path":"/reference/geom_chart.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Plot Financial Charts in ggplot2 — geom_chart","text":"following aesthetics understood (required bold): x, Typically date open, Required open price high, Required high price low, Required low price close, Required close price alpha group linetype size","code":""},{"path":[]},{"path":"/reference/geom_chart.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Plot Financial Charts in ggplot2 — geom_chart","text":"","code":"library(dplyr) library(ggplot2) AAPL <- tq_get(\"AAPL\", from = \"2013-01-01\", to = \"2016-12-31\") # Bar Chart AAPL %>% ggplot(aes(x = date, y = close)) + geom_barchart(aes(open = open, high = high, low = low, close = close)) + geom_ma(color = \"darkgreen\") + coord_x_date(xlim = c(\"2016-01-01\", \"2016-12-31\"), ylim = c(75, 125)) #> Warning: The following aesthetics were dropped during statistical transformation: open, #> high, low, close, y #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor? #> Warning: The following aesthetics were dropped during statistical transformation: open, #> high, low, close #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor? #> Warning: The following aesthetics were dropped during statistical transformation: open, #> high, low, close #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor? # Candlestick Chart AAPL %>% ggplot(aes(x = date, y = close)) + geom_candlestick(aes(open = open, high = high, low = low, close = close)) + geom_ma(color = \"darkgreen\") + coord_x_date(xlim = c(\"2016-01-01\", \"2016-12-31\"), ylim = c(75, 125)) #> Warning: The following aesthetics were dropped during statistical transformation: open, #> high, low, close, y #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor? #> Warning: The following aesthetics were dropped during statistical transformation: x, #> open, high, low, close, y #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor?"},{"path":"/reference/geom_ma.html","id":null,"dir":"Reference","previous_headings":"","what":"Plot moving averages — geom_ma","title":"Plot moving averages — geom_ma","text":"underlying moving average functions used specified TTR::SMA() TTR package. Use coord_x_date() zoom specific plot regions. following moving averages available: Simple moving averages (SMA): Rolling mean period defined n. Exponential moving averages (EMA): Includes exponentially-weighted mean gives weight recent observations. Uses wilder ratio args. Weighted moving averages (WMA): Uses set weights, wts, weight observations moving average. Double exponential moving averages (DEMA): Uses v volume factor, wilder ratio args. Zero-lag exponential moving averages (ZLEMA): Uses wilder ratio args. Volume-weighted moving averages (VWMA): Requires volume aesthetic. Elastic, volume-weighted moving averages (EVWMA): Requires volume aesthetic.","code":""},{"path":"/reference/geom_ma.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Plot moving averages — geom_ma","text":"","code":"geom_ma( mapping = NULL, data = NULL, position = \"identity\", na.rm = TRUE, show.legend = NA, inherit.aes = TRUE, ma_fun = SMA, n = 20, wilder = FALSE, ratio = NULL, v = 1, wts = 1:n, ... ) geom_ma_( mapping = NULL, data = NULL, position = \"identity\", na.rm = TRUE, show.legend = NA, inherit.aes = TRUE, ma_fun = \"SMA\", n = 20, wilder = FALSE, ratio = NULL, v = 1, wts = 1:n, ... )"},{"path":"/reference/geom_ma.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Plot moving averages — geom_ma","text":"mapping Set aesthetic mappings created ggplot2::aes() ggplot2::aes_(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot2::ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See ggplot2::fortify() variables created. function called single argument, plot data. return value must data.frame., used layer data. position Position adjustment, either string naming adjustment (e.g. \"jitter\" use position_jitter), result call position adjustment function. Use latter need change settings adjustment. na.rm TRUE, silently removes NA values, typically desired moving averages. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. ggplot2::borders(). ma_fun function used calculate moving average. Seven options available including: SMA, EMA, WMA, DEMA, ZLEMA, VWMA, EVWMA. default SMA. See TTR::SMA() underlying functions. n Number periods average . Must 1 nrow(x), inclusive. wilder logical; TRUE, Welles Wilder type EMA calculated; see notes. ratio smoothing/decay ratio. ratio overrides wilder EMA, provides additional smoothing VMA. v 'volume factor' (number [0,1]). See Notes. wts Vector weights. Length wts vector must equal length x, n (default). ... arguments passed ggplot2::layer(). often aesthetics, used set aesthetic fixed value, like color = \"red\" size = 3. may also parameters paired geom/stat.","code":""},{"path":"/reference/geom_ma.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Plot moving averages — geom_ma","text":"following aesthetics understood (required bold): x y volume, Required VWMA EVWMA alpha colour group linetype linewidth size","code":""},{"path":[]},{"path":"/reference/geom_ma.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Plot moving averages — geom_ma","text":"","code":"library(dplyr) library(ggplot2) AAPL <- tq_get(\"AAPL\", from = \"2013-01-01\", to = \"2016-12-31\") # SMA AAPL %>% ggplot(aes(x = date, y = adjusted)) + geom_line() + # Plot stock price geom_ma(ma_fun = SMA, n = 50) + # Plot 50-day SMA geom_ma(ma_fun = SMA, n = 200, color = \"red\") + # Plot 200-day SMA coord_x_date(xlim = c(\"2016-01-01\", \"2016-12-31\"), ylim = c(75, 125)) # Zoom in # EVWMA AAPL %>% ggplot(aes(x = date, y = adjusted)) + geom_line() + # Plot stock price geom_ma(aes(volume = volume), ma_fun = EVWMA, n = 50) + # Plot 50-day EVWMA coord_x_date(xlim = c(\"2016-01-01\", \"2016-12-31\"), ylim = c(75, 125)) # Zoom in #> Warning: The following aesthetics were dropped during statistical transformation: volume #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor?"},{"path":"/reference/palette_tq.html","id":null,"dir":"Reference","previous_headings":"","what":"tidyquant palettes for use with scales — palette_tq","title":"tidyquant palettes for use with scales — palette_tq","text":"palettes mainly called internally tidyquant scale_*_tq() functions.","code":""},{"path":"/reference/palette_tq.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"tidyquant palettes for use with scales — palette_tq","text":"","code":"palette_light() palette_dark() palette_green()"},{"path":"/reference/palette_tq.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"tidyquant palettes for use with scales — palette_tq","text":"","code":"library(scales) scales::show_col(palette_light())"},{"path":"/reference/pipe.html","id":null,"dir":"Reference","previous_headings":"","what":"Pipe operator — %>%","title":"Pipe operator — %>%","text":"See magrittr::%>% details.","code":""},{"path":"/reference/pipe.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Pipe operator — %>%","text":"","code":"lhs %>% rhs"},{"path":"/reference/quandl_api_key.html","id":null,"dir":"Reference","previous_headings":"","what":"Query or set Quandl API Key — quandl_api_key","title":"Query or set Quandl API Key — quandl_api_key","text":"Query set Quandl API Key","code":""},{"path":"/reference/quandl_api_key.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Query or set Quandl API Key — quandl_api_key","text":"","code":"quandl_api_key(api_key)"},{"path":"/reference/quandl_api_key.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Query or set Quandl API Key — quandl_api_key","text":"api_key Optionally passed parameter set Quandl api_key.","code":""},{"path":"/reference/quandl_api_key.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Query or set Quandl API Key — quandl_api_key","text":"Returns invisibly currently set api_key","code":""},{"path":"/reference/quandl_api_key.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Query or set Quandl API Key — quandl_api_key","text":"wrapper Quandl::Quandl.api_key()","code":""},{"path":[]},{"path":"/reference/quandl_api_key.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Query or set Quandl API Key — quandl_api_key","text":"","code":"if (FALSE) { if (rlang::is_installed(\"Quandl\")) { quandl_api_key(api_key = \"foobar\") } }"},{"path":"/reference/quandl_search.html","id":null,"dir":"Reference","previous_headings":"","what":"Search the Quandl database — quandl_search","title":"Search the Quandl database — quandl_search","text":"Search Quandl database","code":""},{"path":"/reference/quandl_search.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Search the Quandl database — quandl_search","text":"","code":"quandl_search(query, silent = FALSE, per_page = 10, ...)"},{"path":"/reference/quandl_search.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Search the Quandl database — quandl_search","text":"query Search terms silent Prints results FALSE. per_page Number results returned per page. ... Additional named values interpretted Quandl API parameters.","code":""},{"path":"/reference/quandl_search.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Search the Quandl database — quandl_search","text":"Returns tibble search results.","code":""},{"path":"/reference/quandl_search.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Search the Quandl database — quandl_search","text":"wrapper Quandl::Quandl.search()","code":""},{"path":[]},{"path":"/reference/quandl_search.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Search the Quandl database — quandl_search","text":"","code":"if (FALSE) { quandl_search(query = \"oil\") }"},{"path":"/reference/scale_manual.html","id":null,"dir":"Reference","previous_headings":"","what":"tidyquant colors and fills for ggplot2. — scale_manual","title":"tidyquant colors and fills for ggplot2. — scale_manual","text":"tidyquant scales add colors work nicely theme_tq().","code":""},{"path":"/reference/scale_manual.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"tidyquant colors and fills for ggplot2. — scale_manual","text":"","code":"scale_color_tq(..., theme = \"light\") scale_colour_tq(..., theme = \"light\") scale_fill_tq(..., theme = \"light\")"},{"path":"/reference/scale_manual.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"tidyquant colors and fills for ggplot2. — scale_manual","text":"... common discrete scale parameters: name, breaks, labels, na.value, limits guide. See discrete_scale() details theme one \"light\", \"dark\", \"green\". match theme_tq() used .","code":""},{"path":"/reference/scale_manual.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"tidyquant colors and fills for ggplot2. — scale_manual","text":"scale_color_tq use color specified aes() ggplot. scale_fill_tq use fill specified aes() ggplot.","code":""},{"path":[]},{"path":"/reference/scale_manual.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"tidyquant colors and fills for ggplot2. — scale_manual","text":"","code":"# Load libraries library(dplyr) library(ggplot2) # Get stock prices stocks <- c(\"AAPL\", \"META\", \"NFLX\") %>% tq_get(from = \"2013-01-01\", to = \"2017-01-01\") # Plot for stocks g <- stocks %>% ggplot(aes(date, adjusted, color = symbol)) + geom_line() + labs(title = \"Multi stock example\", xlab = \"Date\", ylab = \"Adjusted Close\") # Plot with tidyquant theme and colors g + theme_tq() + scale_color_tq()"},{"path":"/reference/theme_tq.html","id":null,"dir":"Reference","previous_headings":"","what":"tidyquant themes for ggplot2. — theme_tq","title":"tidyquant themes for ggplot2. — theme_tq","text":"theme_tq() function creates custom theme using tidyquant colors.","code":""},{"path":"/reference/theme_tq.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"tidyquant themes for ggplot2. — theme_tq","text":"","code":"theme_tq(base_size = 11, base_family = \"\") theme_tq_dark(base_size = 11, base_family = \"\") theme_tq_green(base_size = 11, base_family = \"\")"},{"path":"/reference/theme_tq.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"tidyquant themes for ggplot2. — theme_tq","text":"base_size base font size, given pts. base_family base font family","code":""},{"path":[]},{"path":"/reference/theme_tq.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"tidyquant themes for ggplot2. — theme_tq","text":"","code":"# Load libraries library(dplyr) library(ggplot2) # Get stock prices AAPL <- tq_get(\"AAPL\", from = \"2013-01-01\", to = \"2016-12-31\") # Plot using ggplot with theme_tq AAPL %>% ggplot(aes(x = date, y = close)) + geom_line() + geom_bbands(aes(high = high, low = low, close = close), ma_fun = EMA, wilder = TRUE, ratio = NULL, n = 50) + coord_x_date(xlim = c(\"2016-01-01\", \"2016-12-31\"), ylim = c(75, 125)) + labs(title = \"Apple BBands\", x = \"Date\", y = \"Price\") + theme_tq() #> Warning: The following aesthetics were dropped during statistical transformation: high, #> low, close, y #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor? #> Warning: The following aesthetics were dropped during statistical transformation: high, #> low, close #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor?"},{"path":"/reference/tidyquant-package.html","id":null,"dir":"Reference","previous_headings":"","what":"tidyquant: Integrating quantitative financial analysis tools with the tidyverse — tidyquant-package","title":"tidyquant: Integrating quantitative financial analysis tools with the tidyverse — tidyquant-package","text":"main advantage tidyquant bridge gap best quantitative resources collecting manipulating quantitative data, xts, quantmod TTR, data modeling workflow infrastructure tidyverse.","code":""},{"path":"/reference/tidyquant-package.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"tidyquant: Integrating quantitative financial analysis tools with the tidyverse — tidyquant-package","text":"package, tidyquant functions supporting data sets provided seamlessly combine tidy tools existing quantitative analytics packages. main advantage able use tidy functions purrr mapping tidyr nesting extend modeling many stocks. See tidyquant website information, documentation examples. Users probably interested following: Getting Data Web: tq_get() Manipulating Data: tq_transmute() tq_mutate() Performance Analysis Portfolio Aggregation: tq_performance() tq_portfolio() learn tidyquant, start vignettes: browseVignettes(package = \"tidyquant\")","code":""},{"path":[]},{"path":"/reference/tidyquant-package.html","id":"author","dir":"Reference","previous_headings":"","what":"Author","title":"tidyquant: Integrating quantitative financial analysis tools with the tidyverse — tidyquant-package","text":"Maintainer: Matt Dancho mdancho@business-science.io Authors: Davis Vaughan dvaughan@business-science.io","code":""},{"path":"/reference/tiingo_api_key.html","id":null,"dir":"Reference","previous_headings":"","what":"Set Tiingo API Key — tiingo_api_key","title":"Set Tiingo API Key — tiingo_api_key","text":"Requires riingo package installled.","code":""},{"path":"/reference/tiingo_api_key.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Set Tiingo API Key — tiingo_api_key","text":"","code":"tiingo_api_key(api_key)"},{"path":"/reference/tiingo_api_key.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Set Tiingo API Key — tiingo_api_key","text":"api_key Optionally passed parameter set Tiingo api_key.","code":""},{"path":"/reference/tiingo_api_key.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Set Tiingo API Key — tiingo_api_key","text":"Returns invisibly currently set api_key","code":""},{"path":"/reference/tiingo_api_key.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Set Tiingo API Key — tiingo_api_key","text":"wrapper riingo::ringo_set_token()","code":""},{"path":[]},{"path":"/reference/tiingo_api_key.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Set Tiingo API Key — tiingo_api_key","text":"","code":"if (FALSE) { tiingo_api_key(api_key = \"foobar\") }"},{"path":"/reference/tq_get.html","id":null,"dir":"Reference","previous_headings":"","what":"Get quantitative data in tibble format — tq_get","title":"Get quantitative data in tibble format — tq_get","text":"Get quantitative data tibble format","code":""},{"path":"/reference/tq_get.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get quantitative data in tibble format — tq_get","text":"","code":"tq_get(x, get = \"stock.prices\", complete_cases = TRUE, ...) tq_get_options()"},{"path":"/reference/tq_get.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get quantitative data in tibble format — tq_get","text":"x single character string, character vector tibble representing single (multiple) stock symbol, metal symbol, currency combination, FRED code, etc. get character string representing type data get x. Options include: \"stock.prices\": Get open, high, low, close, volume adjusted stock prices stock symbol Yahoo Finance (https://finance.yahoo.com/). Wrapper quantmod::getSymbols(). \"dividends\": Get dividends stock symbol Yahoo Finance (https://finance.yahoo.com/). Wrapper quantmod::getDividends(). \"splits\": Get split ratio stock symbol Yahoo Finance (https://finance.yahoo.com/). Wrapper quantmod::getSplits(). \"stock.prices.japan\": Get open, high, low, close, volume adjusted stock prices stock symbol Yahoo Finance Japan (https://finance.yahoo.co.jp/). Wrapper quantmod::getSymbols.yahooj(). \"economic.data\": Get economic data FRED. rapper quantmod::getSymbols.FRED(). \"quandl\": Get data sets Quandl. Wrapper Quandl::Quandl(). See also quandl_api_key(). \"quandl.datatable\": Get data tables Quandl. Wrapper Quandl::Quandl.datatable(). See also quandl_api_key(). \"tiingo\": Get data sets Tiingo. Wrapper riingo::riingo_prices(). See also tiingo_api_key(). \"tiingo.iex\": Get data sets Tiingo. Wrapper riingo::riingo_iex_prices(). See also tiingo_api_key(). \"tiingo.crypto\": Get data sets Tiingo. Wrapper riingo::riingo_crypto_prices(). See also tiingo_api_key(). \"alphavantager\": Get data sets Alpha Vantage. Wrapper alphavantager::av_get(). See also av_api_key(). \"rblpapi\": Get data sets Bloomberg. Wrapper Rblpapi. See also Rblpapi::blpConnect() connect Bloomberg terminal (required). Use argument rblpapi_fun set function \"bdh\" (default), \"bds\", \"bdp\". complete_cases Removes symbols return NA value due error get call sending incorrect symbol \"XYZ\" get = \"stock.prices\". useful scaling user need add extra step remove rows. TRUE default, warning message generated rows removed. ... Additional parameters passed \"wrapped\" function. Investigate underlying functions see full list arguments. Common optional parameters include: : Standardized time series functions quantmod, quandl, tiingo, alphavantager packages. character string representing start date YYYY-MM-DD format. : Standardized time series functions quantmod, quandl, tiingo, alphavantager packages. character string representing end date YYYY-MM-DD format.","code":""},{"path":"/reference/tq_get.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Get quantitative data in tibble format — tq_get","text":"Returns data form tibble object.","code":""},{"path":"/reference/tq_get.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Get quantitative data in tibble format — tq_get","text":"tq_get() consolidated function gets data various web sources. function wrapper several quantmod functions, Quandl functions, also gets data websources unavailable packages. results always returned tibble. advantages (1) one function needed data sources (2) function can seemlessly used tidyverse: purrr, tidyr, dplyr verbs. tq_get_options() returns list valid get options can choose . tq_get_stock_index_options() deprecated removed next version. Please use tq_index_options() instead.","code":""},{"path":[]},{"path":"/reference/tq_get.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Get quantitative data in tibble format — tq_get","text":"","code":"# Load libraries # Get the list of `get` options tq_get_options() #> [1] \"stock.prices\" \"stock.prices.japan\" \"dividends\" #> [4] \"splits\" \"economic.data\" \"quandl\" #> [7] \"quandl.datatable\" \"tiingo\" \"tiingo.iex\" #> [10] \"tiingo.crypto\" \"alphavantager\" \"alphavantage\" #> [13] \"rblpapi\" # Get stock prices for a stock from Yahoo aapl_stock_prices <- tq_get(\"AAPL\") # Get stock prices for multiple stocks mult_stocks <- tq_get(c(\"META\", \"AMZN\"), get = \"stock.prices\", from = \"2016-01-01\", to = \"2017-01-01\") if (FALSE) { # --- Quandl --- if (rlang::is_installed(\"quandl\")) { quandl_api_key('') tq_get(\"EIA/PET_MTTIMUS1_M\", get = \"quandl\", from = \"2010-01-01\") } # Energy data from EIA # --- Tiingo --- if (rlang::is_installed(\"riingo\")) { tiingo_api_key('') # Tiingo Prices (Free alternative to Yahoo Finance!) tq_get(c(\"AAPL\", \"GOOG\"), get = \"tiingo\", from = \"2010-01-01\") # Sub-daily prices from IEX ---- tq_get(c(\"AAPL\", \"GOOG\"), get = \"tiingo.iex\", from = \"2020-01-01\", to = \"2020-01-15\", resample_frequency = \"5min\") # Tiingo Bitcoin Prices ---- tq_get(c(\"btcusd\", \"btceur\"), get = \"tiingo.crypto\", from = \"2020-01-01\", to = \"2020-01-15\", resample_frequency = \"5min\") } # --- Alpha Vantage --- if (rlang::is_installed(\"alphavantager\")) { av_api_key('') # Daily Time Series tq_get(\"AAPL\", get = \"alphavantager\", av_fun = \"TIME_SERIES_DAILY_ADJUSTED\", outputsize = \"full\") # Intraday 15 Min Interval tq_get(\"AAPL\", get = \"alphavantage\", av_fun = \"TIME_SERIES_INTRADAY\", interval = \"15min\", outputsize = \"full\") # FX DAILY tq_get(\"USD/EUR\", get = \"alphavantage\", av_fun = \"FX_DAILY\", outputsize = \"full\") # FX REAL-TIME QUOTE tq_get(\"USD/EUR\", get = \"alphavantage\", av_fun = \"CURRENCY_EXCHANGE_RATE\") } }"},{"path":"/reference/tq_index.html","id":null,"dir":"Reference","previous_headings":"","what":"Get all stocks in a stock index or stock exchange in tibble format — tq_index","title":"Get all stocks in a stock index or stock exchange in tibble format — tq_index","text":"Get stocks stock index stock exchange tibble format","code":""},{"path":"/reference/tq_index.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get all stocks in a stock index or stock exchange in tibble format — tq_index","text":"","code":"tq_index(x, use_fallback = FALSE) tq_exchange(x) tq_index_options() tq_exchange_options()"},{"path":"/reference/tq_index.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get all stocks in a stock index or stock exchange in tibble format — tq_index","text":"x single character string, character vector tibble representing single stock index multiple stock indexes. use_fallback boolean can used return fallback data set last downloaded package updated. Useful website . Set FALSE default.","code":""},{"path":"/reference/tq_index.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Get all stocks in a stock index or stock exchange in tibble format — tq_index","text":"Returns data form tibble object.","code":""},{"path":"/reference/tq_index.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Get all stocks in a stock index or stock exchange in tibble format — tq_index","text":"tq_index() returns stock symbol, company name, weight, sector every stock index. source www.ssga.com. tq_index_options() returns list stock indexes can choose . tq_exchange() returns stock symbol, company, last sale price, market capitalization, sector industry every stock exchange. Three stock exchanges available (AMEX, NASDAQ, NYSE). tq_exchange_options() returns list stock exchanges can choose . options AMEX, NASDAQ NYSE.","code":""},{"path":[]},{"path":"/reference/tq_index.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Get all stocks in a stock index or stock exchange in tibble format — tq_index","text":"","code":"# Get the list of stock index options tq_index_options() #> [1] \"DOW\" \"DOWGLOBAL\" \"SP400\" \"SP500\" \"SP600\" # Get all stock symbols in a stock index if (FALSE) { tq_index(\"DOW\") } # Get the list of stock exchange options tq_exchange_options() #> [1] \"AMEX\" \"NASDAQ\" \"NYSE\" # Get all stocks in a stock exchange if (FALSE) { tq_exchange(\"NYSE\") }"},{"path":"/reference/tq_mutate.html","id":null,"dir":"Reference","previous_headings":"","what":"Mutates quantitative data — tq_mutate","title":"Mutates quantitative data — tq_mutate","text":"tq_mutate() adds new variables existing tibble; tq_transmute() returns newly created columns typically used periodicity changes","code":""},{"path":"/reference/tq_mutate.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Mutates quantitative data — tq_mutate","text":"","code":"tq_mutate( data, select = NULL, mutate_fun, col_rename = NULL, ohlc_fun = NULL, ... ) tq_mutate_(data, select = NULL, mutate_fun, col_rename = NULL, ...) tq_mutate_xy(data, x, y = NULL, mutate_fun, col_rename = NULL, ...) tq_mutate_xy_(data, x, y = NULL, mutate_fun, col_rename = NULL, ...) tq_mutate_fun_options() tq_transmute( data, select = NULL, mutate_fun, col_rename = NULL, ohlc_fun = NULL, ... ) tq_transmute_(data, select = NULL, mutate_fun, col_rename = NULL, ...) tq_transmute_xy(data, x, y = NULL, mutate_fun, col_rename = NULL, ...) tq_transmute_xy_(data, x, y = NULL, mutate_fun, col_rename = NULL, ...) tq_transmute_fun_options()"},{"path":"/reference/tq_mutate.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Mutates quantitative data — tq_mutate","text":"data tibble (tidy data frame) data typically tq_get(). select columns send mutation function. mutate_fun mutation function either xts, quantmod, TTR package. Execute tq_mutate_fun_options() see full list options package. col_rename string character vector containing names can used quickly rename columns. ohlc_fun Deprecated. Use select. ... Additional parameters passed appropriate mutatation function. x, y Parameters used _xy consist column names variables passed mutatation function (instead OHLC functions).","code":""},{"path":"/reference/tq_mutate.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Mutates quantitative data — tq_mutate","text":"Returns mutated data form tibble object.","code":""},{"path":"/reference/tq_mutate.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Mutates quantitative data — tq_mutate","text":"tq_mutate tq_transmute flexible wrappers various xts, quantmod TTR functions. main advantage results returned tibble function can used tidyverse. tq_mutate used additional columns added return data frame. tq_transmute works exactly like tq_mutate except returns newly created columns. helpful changing periodicity new columns number rows original tibble. select specifies columns get passed mutation function. Select works flexible version OHLC extractor functions quantmod non-OHLC data works well. select NULL, columns selected. Example 1 , close returns \"close\" price sends mutate function, periodReturn. mutate_fun function performs work. Example 1, periodReturn, calculates period returns. ... additional arguments passed mutate_fun. Think whole operation Example 1 close price, obtained select = close, sent periodReturn function along additional arguments defining perform period return, includes period = \"daily\" type = \"log\". Example 4 shows apply rolling regression. tq_mutate_xy tq_transmute_xy designed enable working mutatation functions require two primary inputs (e.g. EVWMA, VWAP, etc). Example 2 shows benefit action: using EVWMA function uses volume define moving average period. tq_mutate_, tq_mutate_xy_, tq_transmute_, tq_transmute_xy_ setup Non-Standard Evaluation (NSE). enables programatically changing column names modifying text representations. Example 5 shows difference implementation. Note character strings passed variables instead unquoted variable names. See vignette(\"nse\") information. tq_mutate_fun_options tq_transmute_fun_options return list various financial functions compatible tq_mutate tq_transmute, respectively.","code":""},{"path":[]},{"path":"/reference/tq_mutate.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Mutates quantitative data — tq_mutate","text":"","code":"# Load libraries library(dplyr) ##### Basic Functionality fb_stock_prices <- FANG %>% filter(symbol == \"META\") %>% filter( date >= \"2016-01-01\", date <= \"2016-12-31\" ) goog_stock_prices <- FANG %>% filter(symbol == \"GOOG\") %>% filter( date >= \"2016-01-01\", date <= \"2016-12-31\" ) # Example 1: Return logarithmic daily returns using periodReturn() fb_stock_prices %>% tq_mutate(select = close, mutate_fun = periodReturn, period = \"daily\", type = \"log\") #> Error in to_period(xx, period = on.opts[[period]], ...): ‘x’ contains no data # Example 2: Use tq_mutate_xy to use functions with two columns required fb_stock_prices %>% tq_mutate_xy(x = close, y = volume, mutate_fun = EVWMA, col_rename = \"EVWMA\") #> Error in fun_transmute(eval(parse(text = x)), eval(parse(text = y)), ...): n = 10 is outside valid range: [1, 0] # Example 3: Using tq_mutate to work with non-OHLC data tq_get(\"DCOILWTICO\", get = \"economic.data\") %>% tq_mutate(select = price, mutate_fun = lag.xts, k = 1, na.pad = TRUE) #> # A tibble: 2,800 × 4 #> symbol date price lag.xts #> #> 1 DCOILWTICO 2013-01-01 NA NA #> 2 DCOILWTICO 2013-01-02 93.1 NA #> 3 DCOILWTICO 2013-01-03 93.0 93.1 #> 4 DCOILWTICO 2013-01-04 93.1 93.0 #> 5 DCOILWTICO 2013-01-07 93.2 93.1 #> 6 DCOILWTICO 2013-01-08 93.2 93.2 #> 7 DCOILWTICO 2013-01-09 93.1 93.2 #> 8 DCOILWTICO 2013-01-10 93.8 93.1 #> 9 DCOILWTICO 2013-01-11 93.6 93.8 #> 10 DCOILWTICO 2013-01-14 94.3 93.6 #> # ℹ 2,790 more rows # Example 4: Using tq_mutate to apply a rolling regression fb_returns <- fb_stock_prices %>% tq_transmute(adjusted, periodReturn, period = \"monthly\", col_rename = \"fb.returns\") #> Error in to_period(xx, period = on.opts[[period]], ...): ‘x’ contains no data goog_returns <- goog_stock_prices %>% tq_transmute(adjusted, periodReturn, period = \"monthly\", col_rename = \"goog.returns\") returns_combined <- left_join(fb_returns, goog_returns, by = \"date\") #> Error in eval(expr, envir, enclos): object 'fb_returns' not found regr_fun <- function(data) { coef(lm(fb.returns ~ goog.returns, data = as_tibble(data))) } returns_combined %>% tq_mutate(mutate_fun = rollapply, width = 6, FUN = regr_fun, by.column = FALSE, col_rename = c(\"coef.0\", \"coef.1\")) #> Error in eval(expr, envir, enclos): object 'returns_combined' not found # Example 5: Non-standard evaluation: # Programming with tq_mutate_() and tq_mutate_xy_() col_name <- \"adjusted\" mutate <- c(\"MACD\", \"SMA\") tq_mutate_xy_(fb_stock_prices, x = col_name, mutate_fun = mutate[[1]]) #> Error in EMA(structure(logical(0), index = structure(numeric(0), tzone = \"UTC\", tclass = \"Date\"), class = c(\"xts\", \"zoo\"), dim = 0:1, dimnames = list(NULL, \"adjusted\")), n = 12): n = 12 is outside valid range: [1, 0]"},{"path":"/reference/tq_performance.html","id":null,"dir":"Reference","previous_headings":"","what":"Computes a wide variety of summary performance metrics from stock or portfolio returns — tq_performance","title":"Computes a wide variety of summary performance metrics from stock or portfolio returns — tq_performance","text":"Asset portfolio performance analysis deep field wide range theories methods analyzing risk versus reward. PerformanceAnalytics package consolidates many widely used performance metrics functions can applied stock portfolio returns. tq_performance implements performance analysis functions tidy way, enabling scaling analysis using split, apply, combine framework.","code":""},{"path":"/reference/tq_performance.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Computes a wide variety of summary performance metrics from stock or portfolio returns — tq_performance","text":"","code":"tq_performance(data, Ra, Rb = NULL, performance_fun, ...) tq_performance_(data, Ra, Rb = NULL, performance_fun, ...) tq_performance_fun_options()"},{"path":"/reference/tq_performance.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Computes a wide variety of summary performance metrics from stock or portfolio returns — tq_performance","text":"data tibble (tidy data frame) returns tidy format (.e long format). Ra column asset returns Rb column baseline returns (functions require comparison baseline) performance_fun performance function PerformanceAnalytics. See tq_performance_fun_options() complete list integrated functions. ... Additional parameters passed PerformanceAnalytics function.","code":""},{"path":"/reference/tq_performance.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Computes a wide variety of summary performance metrics from stock or portfolio returns — tq_performance","text":"Returns data form tibble object.","code":""},{"path":"/reference/tq_performance.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Computes a wide variety of summary performance metrics from stock or portfolio returns — tq_performance","text":"Important concept: Performance based statistical properties returns, result function uses stock portfolio returns opposed stock prices. tq_performance wrapper various PerformanceAnalytics functions return portfolio statistics. main advantage ability scale tidyverse. Ra Rb columns containing asset baseline returns, respectively. columns mapped PerformanceAnalytics functions. Note Rb always required, instances argument defaults Rb = NULL. user can tell Rb required researching underlying performance function. ... additional arguments passed PerformanceAnalytics function. Search underlying function see arguments can passed . tq_performance_fun_options returns list compatible PerformanceAnalytics functions can supplied performance_fun argument.","code":""},{"path":[]},{"path":"/reference/tq_performance.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Computes a wide variety of summary performance metrics from stock or portfolio returns — tq_performance","text":"","code":"# Load libraries library(dplyr) # Use FANG data set # Get returns for individual stock components grouped by symbol Ra <- FANG %>% group_by(symbol) %>% tq_transmute(adjusted, periodReturn, period = \"monthly\", col_rename = \"Ra\") # Get returns for SP500 as baseline Rb <- \"^GSPC\" %>% tq_get(get = \"stock.prices\", from = \"2010-01-01\", to = \"2015-12-31\") %>% tq_transmute(adjusted, periodReturn, period = \"monthly\", col_rename = \"Rb\") # Merge stock returns with baseline RaRb <- left_join(Ra, Rb, by = c(\"date\" = \"date\")) ##### Performance Metrics ##### # View options tq_performance_fun_options() #> $table.funs #> [1] \"table.AnnualizedReturns\" \"table.Arbitrary\" #> [3] \"table.Autocorrelation\" \"table.CAPM\" #> [5] \"table.CaptureRatios\" \"table.Correlation\" #> [7] \"table.Distributions\" \"table.DownsideRisk\" #> [9] \"table.DownsideRiskRatio\" \"table.DrawdownsRatio\" #> [11] \"table.HigherMoments\" \"table.InformationRatio\" #> [13] \"table.RollingPeriods\" \"table.SFM\" #> [15] \"table.SpecificRisk\" \"table.Stats\" #> [17] \"table.TrailingPeriods\" \"table.UpDownRatios\" #> [19] \"table.Variability\" #> #> $CAPM.funs #> [1] \"CAPM.CML\" \"CAPM.CML.slope\" \"CAPM.RiskPremium\" \"CAPM.SML.slope\" #> [5] \"CAPM.alpha\" \"CAPM.beta\" \"CAPM.beta.bear\" \"CAPM.beta.bull\" #> [9] \"CAPM.dynamic\" \"CAPM.epsilon\" \"CAPM.jensenAlpha\" \"TimingRatio\" #> [13] \"MarketTiming\" #> #> $SFM.funs #> [1] \"SFM.CML\" \"SFM.CML.slope\" \"SFM.alpha\" \"SFM.beta\" #> [5] \"SFM.dynamic\" \"SFM.epsilon\" \"SFM.jensenAlpha\" #> #> $descriptive.funs #> [1] \"mean\" \"sd\" \"min\" \"max\" #> [5] \"cor\" \"mean.geometric\" \"mean.stderr\" \"mean.LCL\" #> [9] \"mean.UCL\" #> #> $annualized.funs #> [1] \"Return.annualized\" \"Return.annualized.excess\" #> [3] \"sd.annualized\" \"SharpeRatio.annualized\" #> #> $VaR.funs #> [1] \"VaR\" \"ES\" \"ETL\" \"CDD\" \"CVaR\" #> #> $moment.funs #> [1] \"var\" \"cov\" \"skewness\" \"kurtosis\" #> [5] \"CoVariance\" \"CoSkewness\" \"CoSkewnessMatrix\" \"CoKurtosis\" #> [9] \"CoKurtosisMatrix\" \"M3.MM\" \"M4.MM\" \"BetaCoVariance\" #> [13] \"BetaCoSkewness\" \"BetaCoKurtosis\" #> #> $drawdown.funs #> [1] \"AverageDrawdown\" \"AverageLength\" \"AverageRecovery\" #> [4] \"DrawdownDeviation\" \"DrawdownPeak\" \"maxDrawdown\" #> #> $Bacon.risk.funs #> [1] \"MeanAbsoluteDeviation\" \"Frequency\" \"SharpeRatio\" #> [4] \"MSquared\" \"MSquaredExcess\" \"HurstIndex\" #> #> $Bacon.regression.funs #> [1] \"CAPM.alpha\" \"CAPM.beta\" \"CAPM.epsilon\" \"CAPM.jensenAlpha\" #> [5] \"SystematicRisk\" \"SpecificRisk\" \"TotalRisk\" \"TreynorRatio\" #> [9] \"AppraisalRatio\" \"FamaBeta\" \"Selectivity\" \"NetSelectivity\" #> #> $Bacon.relative.risk.funs #> [1] \"ActivePremium\" \"ActiveReturn\" \"TrackingError\" \"InformationRatio\" #> #> $Bacon.drawdown.funs #> [1] \"PainIndex\" \"PainRatio\" \"CalmarRatio\" \"SterlingRatio\" #> [5] \"BurkeRatio\" \"MartinRatio\" \"UlcerIndex\" #> #> $Bacon.downside.risk.funs #> [1] \"DownsideDeviation\" \"DownsidePotential\" \"DownsideFrequency\" #> [4] \"SemiDeviation\" \"SemiVariance\" \"UpsideRisk\" #> [7] \"UpsidePotentialRatio\" \"UpsideFrequency\" \"BernardoLedoitRatio\" #> [10] \"DRatio\" \"Omega\" \"OmegaSharpeRatio\" #> [13] \"OmegaExcessReturn\" \"SortinoRatio\" \"M2Sortino\" #> [16] \"Kappa\" \"VolatilitySkewness\" \"AdjustedSharpeRatio\" #> [19] \"SkewnessKurtosisRatio\" \"ProspectRatio\" #> #> $misc.funs #> [1] \"KellyRatio\" \"Modigliani\" \"UpDownRatios\" #> # Get performance metrics RaRb %>% tq_performance(Ra = Ra, performance_fun = SharpeRatio, p = 0.95) #> # A tibble: 4 × 4 #> # Groups: symbol [4] #> symbol `ESSharpe(Rf=0%,p=95%)` StdDevSharpe(Rf=0%,p=9…¹ VaRSharpe(Rf=0%,p=95…² #> #> 1 FB 0.193 0.345 0.605 #> 2 AMZN 0.215 0.314 0.265 #> 3 NFLX 0.199 0.355 0.606 #> 4 GOOG 0.213 0.296 0.310 #> # ℹ abbreviated names: ¹​`StdDevSharpe(Rf=0%,p=95%)`, ²​`VaRSharpe(Rf=0%,p=95%)` RaRb %>% tq_performance(Ra = Ra, Rb = Rb, performance_fun = table.CAPM) #> # A tibble: 4 × 13 #> # Groups: symbol [4] #> symbol ActivePremium Alpha AnnualizedAlpha Beta `Beta+` `Beta-` Correlation #> #> 1 FB 0.431 0.034 0.493 0.846 3.00 0.819 0.234 #> 2 AMZN 0.246 0.0144 0.187 1.46 2.04 -0.0442 0.524 #> 3 NFLX 1.02 0.0632 1.09 1.35 1.90 -2.78 0.234 #> 4 GOOG 0.142 0.0123 0.158 0.901 1.56 -0.247 0.451 #> # ℹ 5 more variables: `Correlationp-value` , InformationRatio , #> # `R-squared` , TrackingError , TreynorRatio "},{"path":"/reference/tq_portfolio.html","id":null,"dir":"Reference","previous_headings":"","what":"Aggregates a group of returns by asset into portfolio returns — tq_portfolio","title":"Aggregates a group of returns by asset into portfolio returns — tq_portfolio","text":"Aggregates group returns asset portfolio returns","code":""},{"path":"/reference/tq_portfolio.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Aggregates a group of returns by asset into portfolio returns — tq_portfolio","text":"","code":"tq_portfolio( data, assets_col, returns_col, weights = NULL, col_rename = NULL, ... ) tq_portfolio_( data, assets_col, returns_col, weights = NULL, col_rename = NULL, ... ) tq_repeat_df(data, n, index_col_name = \"portfolio\")"},{"path":"/reference/tq_portfolio.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Aggregates a group of returns by asset into portfolio returns — tq_portfolio","text":"data tibble (tidy data frame) returns tidy format (.e long format). assets_col column assets (securities) returns_col column returns weights Optional parameter asset weights, can passed numeric vector length number assets two column tibble asset names first column weights second column. col_rename string character vector containing names can used quickly rename columns. ... Additional parameters passed PerformanceAnalytics::Return.portfolio n Number times repeat data frame row-wise. index_col_name renaming function \"index\" column, used repeating data frames.","code":""},{"path":"/reference/tq_portfolio.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Aggregates a group of returns by asset into portfolio returns — tq_portfolio","text":"Returns data form tibble object.","code":""},{"path":"/reference/tq_portfolio.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Aggregates a group of returns by asset into portfolio returns — tq_portfolio","text":"tq_portfolio wrapper PerformanceAnalytics::Return.portfolio. main advantage results returned tibble function can used tidyverse. assets_col returns_col columns within data used compute returns portfolio. columns \"long\" format (\"tidy\" format) meaning one column containing assets one column containing return values (.e. \"wide\" format returns spread asset). weights weights applied asset returns. Weights can input one three options: Single Portfolio: numeric vector weights length unique number assets. weights applied order assets. Single Portfolio: two column tibble assets first column weights second column. advantage method weights mapped assets unlisted assets default weight zero. Multiple Portfolios: three column tibble portfolio index first column, assets second column, weights third column. tibble must grouped portfolio index. tq_repeat_df simple function repeats data frame n times row-wise (long-wise), adds new column portfolio index. function used assist Multiple Portfolio analyses, useful precursor tq_portfolio.","code":""},{"path":[]},{"path":"/reference/tq_portfolio.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Aggregates a group of returns by asset into portfolio returns — tq_portfolio","text":"","code":"# Load libraries library(dplyr) # Use FANG data set # Get returns for individual stock components monthly_returns_stocks <- FANG %>% group_by(symbol) %>% tq_transmute(adjusted, periodReturn, period = \"monthly\") ##### Portfolio Aggregation Methods ##### # Method 1: Use tq_portfolio with numeric vector of weights weights <- c(0.50, 0.25, 0.25, 0) tq_portfolio(data = monthly_returns_stocks, assets_col = symbol, returns_col = monthly.returns, weights = weights, col_rename = NULL, wealth.index = FALSE) #> # A tibble: 48 × 2 #> date portfolio.returns #> #> 1 2013-01-31 0.260 #> 2 2013-02-28 -0.00456 #> 3 2013-03-28 -0.0195 #> 4 2013-04-30 0.0810 #> 5 2013-05-31 -0.0139 #> 6 2013-06-28 -0.0179 #> 7 2013-07-31 0.254 #> 8 2013-08-30 0.104 #> 9 2013-09-30 0.145 #> 10 2013-10-31 0.0420 #> # ℹ 38 more rows # Method 2: Use tq_portfolio with two column tibble and map weights # Note that GOOG's weighting is zero in Method 1. In Method 2, # GOOG is not added and same result is achieved. weights_df <- tibble(symbol = c(\"META\", \"AMZN\", \"NFLX\"), weights = c(0.50, 0.25, 0.25)) tq_portfolio(data = monthly_returns_stocks, assets_col = symbol, returns_col = monthly.returns, weights = weights_df, col_rename = NULL, wealth.index = FALSE) #> Warning: The assets in weights does not match the assets in data. #> Warning: The weights for one or more periods do not sum up to 1: assuming a return of 0 for the residual weights #> # A tibble: 48 × 2 #> date portfolio.returns #> #> 1 2013-01-31 0.207 #> 2 2013-02-28 0.0504 #> 3 2013-03-28 0.00427 #> 4 2013-04-30 0.0475 #> 5 2013-05-31 0.0320 #> 6 2013-06-28 -0.0239 #> 7 2013-07-31 0.0846 #> 8 2013-08-30 0.0600 #> 9 2013-09-30 0.0644 #> 10 2013-10-31 0.0523 #> # ℹ 38 more rows # Method 3: Working with multiple portfolios # 3A: Duplicate monthly_returns_stocks multiple times mult_monthly_returns_stocks <- tq_repeat_df(monthly_returns_stocks, n = 4) #> Ungrouping data frame groups: symbol # 3B: Create weights table grouped by portfolio id weights <- c(0.50, 0.25, 0.25, 0.00, 0.00, 0.50, 0.25, 0.25, 0.25, 0.00, 0.50, 0.25, 0.25, 0.25, 0.00, 0.50) stocks <- c(\"META\", \"AMZN\", \"NFLX\", \"GOOG\") weights_table <- tibble(stocks) %>% tq_repeat_df(n = 4) %>% bind_cols(tibble(weights)) %>% group_by(portfolio) # 3C: Scale to multiple portfolios tq_portfolio(data = mult_monthly_returns_stocks, assets_col = symbol, returns_col = monthly.returns, weights = weights_table, col_rename = NULL, wealth.index = FALSE) #> Warning: There were 7 warnings in `dplyr::mutate()`. #> The first warning was: #> ℹ In argument: `portfolio.. = purrr::pmap(list(returns.., weights.., #> portfolio), custom_function)`. #> ℹ In group 1: `portfolio = 1`. #> Caused by warning in `check_weights()`: #> ! The assets in weights does not match the assets in data. #> ℹ Run `dplyr::last_dplyr_warnings()` to see the 6 remaining warnings. #> # A tibble: 192 × 3 #> # Groups: portfolio [4] #> portfolio date portfolio.returns #> #> 1 1 2013-01-31 0.207 #> 2 1 2013-02-28 0.0504 #> 3 1 2013-03-28 0.00427 #> 4 1 2013-04-30 0.0475 #> 5 1 2013-05-31 0.0320 #> 6 1 2013-06-28 -0.0239 #> 7 1 2013-07-31 0.0846 #> 8 1 2013-08-30 0.0600 #> 9 1 2013-09-30 0.0644 #> 10 1 2013-10-31 0.0523 #> # ℹ 182 more rows"},{"path":"/news/index.html","id":"tidyquant-development-version","dir":"Changelog","previous_headings":"","what":"tidyquant (development version)","title":"tidyquant (development version)","text":"Remove dependency tidyverse tidyquant longer loads lubridate tidyverse 2.0 now loads lubridate Changed size argument linewidth ggplot2 3.4.0 Removed last tidyr dplyr deprecated functions Add linewidth = geom_ma() Move Quandl, riingo, alphavantager Suggests. tidyquant explictly install , can install CRAN. Fixed CRAN alias FB META change FANG","code":""},{"path":"/news/index.html","id":"tidyquant-107","dir":"Changelog","previous_headings":"","what":"tidyquant 1.0.7","title":"tidyquant 1.0.7","text":"CRAN release: 2023-03-31 Moved tidyverse suggest imports pass cran tests","code":""},{"path":"/news/index.html","id":"tidyquant-106","dir":"Changelog","previous_headings":"","what":"tidyquant 1.0.6","title":"tidyquant 1.0.6","text":"CRAN release: 2022-11-16 Fix tq_performance test failure PerformanceAnalytics 2.0.6 #223 Fix failed r-devel test identified CRAN Remove deprecated spread_() function Move readxl imports. #222","code":""},{"path":"/news/index.html","id":"tidyquant-105","dir":"Changelog","previous_headings":"","what":"tidyquant 1.0.5","title":"tidyquant 1.0.5","text":"CRAN release: 2022-09-08 FIX: FB META name change IMPROVEMENT: sp_index() convert symbols “BRK.B” “BRK-B” work Yahoo Finance","code":""},{"path":"/news/index.html","id":"tidyquant-104","dir":"Changelog","previous_headings":"","what":"tidyquant 1.0.4","title":"tidyquant 1.0.4","text":"CRAN release: 2022-05-20 CRAN requested fixes: Moved janitor suggests Reduced file size removing vignettes CRAN version. changes: Removed package start-message","code":""},{"path":"/news/index.html","id":"tidyquant-103","dir":"Changelog","previous_headings":"","what":"tidyquant 1.0.3","title":"tidyquant 1.0.3","text":"CRAN release: 2021-03-05","code":""},{"path":"/news/index.html","id":"fixes-1-0-3","dir":"Changelog","previous_headings":"","what":"Fixes","title":"tidyquant 1.0.3","text":"tq_exchange(): Switch new NASDAQ website.","code":""},{"path":"/news/index.html","id":"tidyquant-102","dir":"Changelog","previous_headings":"","what":"tidyquant 1.0.2","title":"tidyquant 1.0.2","text":"CRAN release: 2020-10-21","code":""},{"path":"/news/index.html","id":"fixes-1-0-2","dir":"Changelog","previous_headings":"","what":"Fixes","title":"tidyquant 1.0.2","text":"tq_exchange(): Fix issue NASDAQ changes website. theme_tq(): Fix issues %+replace%, theme_gray, rel found.","code":""},{"path":"/news/index.html","id":"tidyquant-101","dir":"Changelog","previous_headings":"","what":"tidyquant 1.0.1","title":"tidyquant 1.0.1","text":"CRAN release: 2020-07-02","code":""},{"path":"/news/index.html","id":"improvements-1-0-1","dir":"Changelog","previous_headings":"","what":"Improvements","title":"tidyquant 1.0.1","text":"tq_get() - Add \"dividends\" \"splits\" get options, fixed quantmod 0.4-16. Issue 150.","code":""},{"path":"/news/index.html","id":"bug-fixes-1-0-1","dir":"Changelog","previous_headings":"","what":"Bug Fixes","title":"tidyquant 1.0.1","text":"Issue 157 - Error package load rstudioapi::getThemeInfo() returns NULL. pivot_table - Fix issues tidyverse functions found.","code":""},{"path":"/news/index.html","id":"deprecation-1-0-1","dir":"Changelog","previous_headings":"","what":"Deprecation","title":"tidyquant 1.0.1","text":"summarise_by_time() - function moved timetk::summarise_by_time()","code":""},{"path":"/news/index.html","id":"tidyquant-100","dir":"Changelog","previous_headings":"","what":"tidyquant 1.0.0","title":"tidyquant 1.0.0","text":"CRAN release: 2020-03-04 “R Excel Users” release. aim build functionality helps users coming Excel Background (background came ). ’s important users feel home. full suite functionality accomplish Excel--R transition. -Matt Excel Functions Excel functions? Designed help users coming Excel Background easily transition tidyverse “tidy- finance / business analysis” R. pivot_table() - tidyverse-style function perform data summarizations just like popular Excel Pivot Table. Enables stacking calculations using tidy-esque syntax: .rows = ~ YEAR(order_date). VLOOKUP() - Performs classic Excel VLOOKUP. Excel user’s: rejoice. Summarising “IFS” Functions - Filtering versions Excel summarization counterparts. Simply add “cases” filter condition true. SUM_IFS(), COUNT_IFS(), AVERAGE_IFS() Create “IFS” functions - idea new “IFS” function hasn’t made yet? Use CREATE_IFS() make supplying summarization function. 100+ Excel-based statistical, date, financial math functions. Names similar Excel function names. default, missing values ignored (Excel). Summarizations Functions - SUM(), AVERAGE(), COUNT(), friends. Transformation Functions - CHANGE(), PCT_CHANGE(), LAG(), CUMULATIVE_SUM(), friends. Integrated date calculations lubridate() (e.g. AS_DATE(), YEAR()) Holidays business calendars timeDate (e.g. HOLIDAY_SEQUENCE(), HOLIDAY_LIST()) Excel Date Math functions: NET_WORKDAYS(), EOMONTH() Financial Math Functions - NPV(), IRR(), FV(), PV(), PMT(), RATE() NEW Tidyverse Functionality summarise_by_time() - new time-based variant summarise() allows collapsing time-series “day”, “week”, “month”, “quarter”, “year”, . Note: evaluate need summarise_at_by_time(), summarise_all_by_time(), summarise_if_by_time() release dplyr v1.0.0. NEW API Integrations Tiingo API - popular Open-Source stock prices, cryptocurrencies, intraday feeds IEX (Investors Exchange). can serve alternate source data Yahoo Finance. Integrated via riingo package. Bug Fixes & Improvements theme_tq() - Fix issues collisions dials::margin() ggplot2::margin(). Similar potential ggplot2 collisions fixed. theme_tq() - Increased default top/bottom text margin facet strips Deprecation & Breaking Changes Potential Breaking Change - Single values now return symbol column (.e. tq_get(\"AAPL\") returns symbol = “AAPL” 1st column). Google Finance Morningstar Key Ratios & Financials (Fundamentals) Data Yahoo Dividends Splits Oanda FX Metal Prices Deprecated Compound Getters - Stacking multiple get options (tq_get(\"AAPL\", get = c(\"stock.prices\", \"stock.prices.japan\"))) longer available. Solution: Split two calls tq_get().","code":""},{"path":"/news/index.html","id":"tidyquant-0510","dir":"Changelog","previous_headings":"","what":"tidyquant 0.5.10","title":"tidyquant 0.5.10","text":"CRAN release: 2020-01-27 tq_get() - Temporarily adjust tests tq_get(get = \"dividends\") tq_get(get = \"splits\") API stabilizes. Yahoo! Dividends Splits intermitently returns errors. Fix documentation warnings package build checks. Documentation moved tq_stocklist ?tq_index.","code":""},{"path":"/news/index.html","id":"tidyquant-059","dir":"Changelog","previous_headings":"","what":"tidyquant 0.5.9","title":"tidyquant 0.5.9","text":"CRAN release: 2019-12-15 Fix issue #144 - tq_index() download issue. Note “RUSSEL1000”, “RUSSELL2000”, “RUSSELL3000”, “SP1000” longer available due changes www.us.spdrs.com. Update Stock Index Fallback.","code":""},{"path":"/news/index.html","id":"tidyquant-058","dir":"Changelog","previous_headings":"","what":"tidyquant 0.5.8","title":"tidyquant 0.5.8","text":"CRAN release: 2019-10-11 tq_index() - Fix naming issue stock index data downloaded www.us.spdrs.com.","code":""},{"path":"/news/index.html","id":"tidyquant-057","dir":"Changelog","previous_headings":"","what":"tidyquant 0.5.7","title":"tidyquant 0.5.7","text":"CRAN release: 2019-09-20 Stock Index & Exchanges tq_exchange() - Fix NASDAQ URL change Issue #138. Visualizations & Color Palettes geom_candlestick geom_barchart - Issue #112. Added color names theme_tq palettes (palette_light, palette_dark, palette_green) easier identification. Compatability tidyr v1.0.0 Improvements ensure compatability tidyr v1.0.0 [Potential Breaking Change] Move tidyverse suggests actually potentially “breaking change” (although users see difference since likely load tidyverse scripts) - load tidyverse, now need . Previously tidyquant loaded tidyverse behind scenes.","code":""},{"path":"/news/index.html","id":"tidyquant-056","dir":"Changelog","previous_headings":"","what":"tidyquant 0.5.6","title":"tidyquant 0.5.6","text":"CRAN release: 2019-04-22 Morningstar Key Ratios: tq_get() argument get = \"key.ratios\" deprecated due change Morningstar’s website. (Help Wanted - Ref. Issue #125) Remove dependency XLConnect. Replace readxl. Issue #119.","code":""},{"path":"/news/index.html","id":"tidyquant-055","dir":"Changelog","previous_headings":"","what":"tidyquant 0.5.5","title":"tidyquant 0.5.5","text":"CRAN release: 2018-05-09 Bux fix tq_get() get = \"financials\" now returns warning NA Google Finance longer provides data. actively looking alternative data sources. tq_get() get = \"stock.prices.google\" now returns warning NA Google Finance longer provides data. Use get = \"stock.prices\" instead use Yahoo Finance, use riingo package download Tiingo. Catch duplicate names col_rename renaming 1 column. Duplicate names allowed return error. Fix duplicate name collision issue original name already includes .. Duplicate names now get ..1, ..2, etc. opposed .1, .2.","code":""},{"path":"/news/index.html","id":"tidyquant-054","dir":"Changelog","previous_headings":"","what":"tidyquant 0.5.4","title":"tidyquant 0.5.4","text":"CRAN release: 2018-02-19 Incorporate alphavantager, lightweight API Alpha Vantage financial data provider. Integrate Rblpapi, R interface “Bloomberg”. must Bloomberg account use . Add Google Finance source tq_get(get = \"stock.prices.google\") Remove Key Statistics tq_get(get = \"key.stats\"). Yahoo Finance longer supports Key Statistics CSV API. Completed deprecation tidyquant::as_tibble() tidyquant::as_xts(). Use timetk::tk_tbl() timetk::tk_xts() instead. tibbletime support added tidyquant functions play nicely tbl_time objects. hard dependency XLConnect removed. ease use package, especially Mac users. tests failed testthat 2.0. updated.","code":""},{"path":"/news/index.html","id":"tidyquant-053","dir":"Changelog","previous_headings":"","what":"tidyquant 0.5.3","title":"tidyquant 0.5.3","text":"CRAN release: 2017-08-03 Fixes compatibility purrr v0.2.3.","code":""},{"path":"/news/index.html","id":"tidyquant-052","dir":"Changelog","previous_headings":"","what":"tidyquant 0.5.2","title":"tidyquant 0.5.2","text":"CRAN release: 2017-07-27 Incorporated robust timetk coercion functions. Deprecated tidyquant::as_xts() tidyquant::as_tibble(). Use timetk::tk_xts() timetk::tk_tbl() instead. tq_index() longer pulls marketvolume. Instead, 9 indices available SPDR. indices reliable, include weights stock index. Fixed 2 tests results tq_get(get = \"stock.prices\") 1 2 rows tests expected. likely new yahoo finance API.","code":""},{"path":"/news/index.html","id":"tidyquant-051","dir":"Changelog","previous_headings":"","what":"tidyquant 0.5.1","title":"tidyquant 0.5.1","text":"CRAN release: 2017-04-24 Added pkgdown integration. Require new quantmod version 0.4-8 fix Oanda Yahoo bugs. Quandl data returned newest oldest. consistency tq_get() data, now returns oldest newest. Oanda returns 180 days FX Metals data now. Updated tests account . Also added error handling check valid date ranges. Fixed bug tq_portfolio() weights = NULL execute equal weighting scheme. Added error handling dollar percent conversion get = “key.ratios” get = “key.stats”.","code":""},{"path":"/news/index.html","id":"tidyquant-050","dir":"Changelog","previous_headings":"","what":"tidyquant 0.5.0","title":"tidyquant 0.5.0","text":"CRAN release: 2017-04-03 tq_get(get = \"quandl\") wrapper Quandl::Quandl() pulls multiple Quandl Codes “tidy” fashion. tq_get(get = \"quandl.datatable\") wrapper Quandl::Quandl.datable() pulls Quandl datatables. quandl_api_key() wrapper Quandl::Quandl.api_key(). quandl_search wrapper Quandl::Quandl.search(). Yahoo Japan Integration: tq_get(get = \"stock.prices.japan\") wrapper quantmod::getSymbols(src = \"yahooj\") enables getting stocks Yahoo Finance Japan. tq_mutate() tq_transmute() now accept non-OHLC data select argument. also now work rollapply. tq_mutate() tq_transmute() now accept PerformanceAnalytics functions work clean transform asset returns. Deprecated ohlc_fun argument instead use select tq_mutate() tq_transmute .Deprecated -> .Defunct tq_transform() tq_transform_xy(). Use tq_transmute() tq_transmute_xy(). Move sign post functions deprecated.R Remove previously deprecated argument, transform_fun tq_transmute(). Use mutate_fun instead. Fix issue tq_mutate returning rows incorrectly sorted Fix issue tq_get returning data frames nested Fix tq_get error return full error issues present.","code":""},{"path":"/news/index.html","id":"tidyquant-040","dir":"Changelog","previous_headings":"","what":"tidyquant 0.4.0","title":"tidyquant 0.4.0","text":"CRAN release: 2017-03-03 tq_transmute() replaces tq_transform() consistency dplyr. tq_performance() integrates performance analysis functions PerformanceAnalytics. tq_portfolio() enables aggregating portfolios individual stock returns. tq_tranform(): Added NA-handling functions zoo list compatible, provide number useful methods handling NA values data sets. Added Return.calculate Return.excess calculating returns returns excess risk-free rate, respectively. tq_mutate() tq_transmute() help pages combined. Split introduction four separate vignettes, improves flow enables readers easily get needed documentation. Now five docs total covering primary needs tidyquant users! tq_exchange() gets stock list NASDAQ, NYSE, AMEX exchanges. Use tq_exchange_options() exchange options. FANG data set palette_() functions used create scales exported. theme_tq() creates light, dark, green themes tidyquant visualizations. scale_color_tq() scale_fill_tq() add color/fill scales data used tidyquant visualizations. transform_fun argument tq_transmute() replaced mutate_fun consistency tq_mutate(). Core functions now generics allow extendability. Issue #11: Part 2. Fix multiple stocks return 110 lines. Handle stocks return csv “’re sorry” message. Issue #11: Part 1. Fix instability get = key.ratios failing HTTP 500 error download. Use httr RETRY case failure. Fixed issue get = \"key.ratios\" stocks listed AMEX exchange able return key ratios. Issue #9: Fix problem get = \"key.stats\" NA’s multiple x (e.g. c(\"AAPL\", \"GOOG\")) cause call fail coercion. Issue #8, Part 2: Enable compound gets (e.g. tq_get(\"AAPL\", get = c(\"stock.prices\", \"financials\"))). Issue #8, Part 1: Create tq_index() function return stock index. tq_get(get = \"stock.index\") deprecated removed next version 0.4.0. Use tq_index_options() index options. Issue #7: Fixed issue date column inadvertently coerced dttm.","code":""},{"path":"/news/index.html","id":"tidyquant-030","dir":"Changelog","previous_headings":"","what":"tidyquant 0.3.0","title":"tidyquant 0.3.0","text":"CRAN release: 2017-01-21 New tq_get option get = \"key.stats\", retrieves current key statistics (55 total) www.finance.yahoo.com/. include various current data Ask, Bid, Day’s High, Day’s Low, Last Trade Price, current P/E Ratio, EPS, Current Market Cap, EPS Projected Current Year, EPS Projected Next Year many . Example: tq_get(\"AAPL\", get = \"key.stats\"). Chart geoms: Bar charts (geom_barchart) candlestick charts (geom_candlestick) can quickly created new geoms. Moving Averages: Seven moving averages can quickly visualized / prototyped using geom_ma. geom wraps TTR::SMA functions. Bollinger bands can visualized geom_bbands. seven moving averages compatible geom. Zooming Chart Sections: Two functions (coord_x_date coord_x_datetime) added enable zooming chart sections using dates --bounds data loss (e.g. --bounds data loss scale_x_ functions). New Vignette: Covers “Charting tidyquant”. Issue #5: tq_get can now accept character vectors data frames x arg, addition single character input. streamlines getting data multiple inputs (e.g. stock symbols, stock indexes, etc). Issue #4: Added col_rename arg tq_mutate tq_transform, enables fast easy renaming operation. Issue #3: Integrated dplyr::group_by() tq_mutate() tq_transform(). transform mutate functions now work properly grouped data frames. Issue #2: Fixed bug tq_get(), get = \"key.ratios\", key ratios stocks NYSE returned NA. Removed support deprecated arguments: x_fun, .x, .y respective transform mutate functions.","code":""},{"path":"/news/index.html","id":"tidyquant-020","dir":"Changelog","previous_headings":"","what":"tidyquant 0.2.0","title":"tidyquant 0.2.0","text":"CRAN release: 2017-01-08 New get = \"key.ratios\" option tq_get(), retrieves 10-years key performance ratios (89 total) www.morningstar.com. include various historical measures financial performance including profitability, growth, cash flow, financial health, efficiency, valuation ratios. Example: tq_get(\"AAPL\", get = \"key.ratios\"). Added zoo rollapply() functions list compatible / integrated functions used tq_transform() tq_mutate(). See tq_transform_fun_options() full list. x_fun now ohlc_fun tq_mutate() tq_transform() .x now x .y now y tq_mutate_xy() tq_transform_xy() Fixed duplication column names tq_mutate. Names now sequentually indexed duplicate names starting .1 suffix.","code":""},{"path":"/news/index.html","id":"tidyquant-010","dir":"Changelog","previous_headings":"","what":"tidyquant 0.1.0","title":"tidyquant 0.1.0","text":"CRAN release: 2016-12-31 Initial release tidyquant, seamless quantitative financial analysis (xts, quantmod, TTR) package integration tidyverse.","code":""}] +[{"path":"/articles/TQ00-introduction-to-tidyquant.html","id":"minutes-to-tidyquant","dir":"Articles","previous_headings":"","what":"2-Minutes To Tidyquant","title":"Introduction to tidyquant","text":"short introduction tidyquant YouTube. Check entire Software Intro Series YouTube!","code":""},{"path":"/articles/TQ00-introduction-to-tidyquant.html","id":"benefits","dir":"Articles","previous_headings":"","what":"Benefits","title":"Introduction to tidyquant","text":"core functions lot power Integrates quantitative analysis functionality zoo, xts, quantmod, TTR, PerformanceAnalytics Designed modeling scaling analyses using tidyverse tools R Data Science Implements ggplot2 functionality beautiful meaningful financial visualizations User-friendly documentation get speed quickly!","code":""},{"path":"/articles/TQ00-introduction-to-tidyquant.html","id":"a-few-core-functions-with-a-lot-of-power","dir":"Articles","previous_headings":"Benefits","what":"A Few Core Functions with A Lot of Power","title":"Introduction to tidyquant","text":"Minimizing number functions reduces learning curve. ’ve done group core functions four categories: Get Stock Index, tq_index(), Stock Exchange, tq_exchange(): Returns stock symbols various attributes every stock index exchange. Eighteen indexes three exchanges available. Get Quantitative Data, tq_get(): one-stop shop get data various web-sources. Transmute, tq_transmute(), Mutate, tq_mutate(), Quantitative Data: Perform scale financial calculations completely within tidyverse. workhorse functions integrate xts, zoo, quantmod, TTR, PerformanceAnalytics packages. Performance analysis, tq_performance(), portfolio aggregation, tq_portfolio(): PerformanceAnalytics integration enables analyzing performance assets portfolios. Refer Performance Analysis tidyquant. information, refer first topic-specific vignette, Core Functions tidyquant.","code":""},{"path":"/articles/TQ00-introduction-to-tidyquant.html","id":"integrates-the-quantitative-analysis-functionality-of-xtszoo-quantmod-ttr-and-performance-analytics","dir":"Articles","previous_headings":"Benefits","what":"Integrates the Quantitative Analysis Functionality of xts/zoo, quantmod TTR and Performance Analytics","title":"Introduction to tidyquant","text":"’s wide range useful quantitative analysis functions (QAF) work time-series objects. problem many wonderful functions don’t work data frames tidyverse workflow. now. tidyquant package integrates useful functions xts, zoo, quantmod, TTR, PerformanceAnalytics packages, enabling seamless usage within tidyverse workflow. Refer information performance analysis portfolio attribution PerformanceAnalytics integration. information, refer second topic-specific vignette, R Quantitative Analysis Package Integrations tidyquant.","code":""},{"path":"/articles/TQ00-introduction-to-tidyquant.html","id":"designed-for-the-data-science-workflow-of-the-tidyverse","dir":"Articles","previous_headings":"Benefits","what":"Designed for the data science workflow of the tidyverse","title":"Introduction to tidyquant","text":"greatest benefit tidyquant ability easily model scale financial analysis. Scaling process creating analysis one security extending multiple groups. idea scaling incredibly useful financial analysts typically one wants compare many securities make informed decisions. Fortunately, tidyquant package integrates tidyverse making scaling super simple! tidyquant functions return data tibble (tidy data frame) format, allows interaction within tidyverse. means can: Seamlessly scale data retrieval mutations Use pipe (%>%) chaining operations Use dplyr tidyr: select, filter, group_by, nest/unnest, spread/gather, etc Use purrr: mapping functions map information, refer third topic-specific vignette, Scaling Modeling tidyquant.","code":""},{"path":"/articles/TQ00-introduction-to-tidyquant.html","id":"implements-ggplot2-functionality-for-financial-visualizations","dir":"Articles","previous_headings":"Benefits","what":"Implements ggplot2 Functionality for Financial Visualizations","title":"Introduction to tidyquant","text":"tidyquant package includes charting tools assist users developing quick visualizations ggplot2 using grammar graphics format workflow. information, refer fourth topic-specific vignette, Charting tidyquant.","code":""},{"path":"/articles/TQ00-introduction-to-tidyquant.html","id":"performance-analysis-of-asset-and-portfolio-returns","dir":"Articles","previous_headings":"Benefits","what":"Performance Analysis of Asset and Portfolio Returns","title":"Introduction to tidyquant","text":"Asset portfolio performance analysis deep field wide range theories methods analyzing risk versus reward. PerformanceAnalytics package consolidates many widely used performance metrics functions can applied stock portfolio returns. tidquant implements functionality two primary functions: tq_performance implements performance analysis functions tidy way, enabling scaling analysis using split, apply, combine framework. tq_portfolio provides useful toolset aggregating group individual asset returns one many portfolios. Performance based statistical properties returns, result functions use returns opposed stock prices. information, refer fifth topic-specific vignette, Performance Analysis tidyquant.","code":""},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"overview","dir":"Articles","previous_headings":"","what":"Overview","title":"Core Functions in tidyquant","text":"tidyquant package core functions lot power. functions means less learning curve user, handful functions user needs learn perform vast majority financial analysis tasks. main functions : Get Stock Index, tq_index(), Stock Exchange, tq_exchange(): Returns stock symbols various attributes every stock index exchange. Eighteen indexes three exchanges available. Get Quantitative Data, tq_get(): one-stop shop get data various web-sources. Transmute, tq_transmute(), Mutate, tq_mutate(), Quantitative Data: Perform scale financial calculations completely within tidyverse. workhorse functions integrate xts, zoo, quantmod, TTR packages. Performance analysis, tq_performance(), portfolio aggregation, tq_portfolio(): PerformanceAnalytics integration enables analyzing performance assets portfolios. breadth topic, refer Performance Analysis tidyquant tutorial functions.","code":""},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"prerequisites","dir":"Articles","previous_headings":"","what":"Prerequisites","title":"Core Functions in tidyquant","text":"Load tidyquant package get started.","code":"# Loads tidyquant, lubridate, xts, quantmod, TTR library(dplyr) library(tidyquant)"},{"path":[]},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"stock-indexes","dir":"Articles","previous_headings":"1.0 Retrieve Consolidated Symbol Data","what":"1.1 Stock Indexes","title":"Core Functions in tidyquant","text":"wide range stock index / exchange lists can retrieved using tq_index(). get full list options, use tq_index_options(). Set x one options list options get desired stock index / exchange. data source State Street Global Advisors - US SPDRS ETFs.","code":"tq_index_options() ## [1] \"DOW\" \"DOWGLOBAL\" \"SP400\" \"SP500\" \"SP600\" tq_index(\"SP500\")"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"stock-exchanges","dir":"Articles","previous_headings":"1.0 Retrieve Consolidated Symbol Data","what":"1.2 Stock Exchanges","title":"Core Functions in tidyquant","text":"Stock lists three stock exchanges available: NASDAQ, NYSE, AMEX. forget, just use tq_exchange_options(). can easily get full list stocks NASDAQ exchange.","code":"tq_exchange(\"NASDAQ\")"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"get-quantitative-data","dir":"Articles","previous_headings":"","what":"1.0 Get Quantitative Data","title":"Core Functions in tidyquant","text":"tq_get() function used collect data changing get argument. data sources: Yahoo Finance - Daily stock data FRED - Economic data Quandl - Economic, Energy, & Financial Data API Tiingo - Financial API sub-daily stock data crypto-currency Alpha Vantage - Financial API sub-daily, ForEx, crypto-currency data Bloomberg - Financial API. Paid account required. Use tq_get_options() see full list.","code":"tq_get_options() ## [1] \"stock.prices\" \"stock.prices.japan\" \"dividends\" ## [4] \"splits\" \"economic.data\" \"quandl\" ## [7] \"quandl.datatable\" \"tiingo\" \"tiingo.iex\" ## [10] \"tiingo.crypto\" \"alphavantager\" \"alphavantage\" ## [13] \"rblpapi\""},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"yahoo-finance","dir":"Articles","previous_headings":"1.0 Get Quantitative Data","what":"2.1 Yahoo! Finance","title":"Core Functions in tidyquant","text":"stock prices can retrieved succinctly using get = \"stock.prices\". returns stock price data Yahoo Finance. Yahoo Japan stock prices can retrieved using similar call, get = \"stock.prices.japan\". data source Yahoo Finance (https://finance.yahoo.com/) Yahoo Finance Japan (https://finance.yahoo.co.jp/).","code":"aapl_prices <- tq_get(\"AAPL\", get = \"stock.prices\", from = \" 1990-01-01\") aapl_prices ## # A tibble: 8,502 × 8 ## symbol date open high low close volume adjusted ## ## 1 AAPL 1990-01-02 0.315 0.335 0.312 0.333 183198400 0.264 ## 2 AAPL 1990-01-03 0.339 0.339 0.335 0.335 207995200 0.266 ## 3 AAPL 1990-01-04 0.342 0.346 0.333 0.336 221513600 0.266 ## 4 AAPL 1990-01-05 0.337 0.342 0.330 0.337 123312000 0.267 ## 5 AAPL 1990-01-08 0.335 0.339 0.330 0.339 101572800 0.269 ## 6 AAPL 1990-01-09 0.339 0.339 0.330 0.336 86139200 0.266 ## 7 AAPL 1990-01-10 0.336 0.336 0.319 0.321 199718400 0.255 ## 8 AAPL 1990-01-11 0.324 0.324 0.308 0.308 211052800 0.244 ## 9 AAPL 1990-01-12 0.306 0.310 0.301 0.308 171897600 0.244 ## 10 AAPL 1990-01-15 0.308 0.319 0.306 0.306 161739200 0.243 ## # ℹ 8,492 more rows x8411T <- tq_get(\"8411.T\", get = \"stock.prices.japan\", from = \"2016-01-01\", to = \"2016-12-31\")"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"fred-economic-data","dir":"Articles","previous_headings":"1.0 Get Quantitative Data","what":"2.2 FRED Economic Data","title":"Core Functions in tidyquant","text":"wealth economic data can extracted Federal Reserve Economic Data (FRED) database. FRED contains 10K data sets free use. See FRED categories narrow data base get data codes. WTI Crude Oil Prices shown .","code":"wti_price_usd <- tq_get(\"DCOILWTICO\", get = \"economic.data\") wti_price_usd ## # A tibble: 2,800 × 3 ## symbol date price ## ## 1 DCOILWTICO 2013-01-01 NA ## 2 DCOILWTICO 2013-01-02 93.1 ## 3 DCOILWTICO 2013-01-03 93.0 ## 4 DCOILWTICO 2013-01-04 93.1 ## 5 DCOILWTICO 2013-01-07 93.2 ## 6 DCOILWTICO 2013-01-08 93.2 ## 7 DCOILWTICO 2013-01-09 93.1 ## 8 DCOILWTICO 2013-01-10 93.8 ## 9 DCOILWTICO 2013-01-11 93.6 ## 10 DCOILWTICO 2013-01-14 94.3 ## # ℹ 2,790 more rows"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"nasdaq-data-link-quandl-api","dir":"Articles","previous_headings":"1.0 Get Quantitative Data","what":"2.3 Nasdaq Data Link (Quandl) API","title":"Core Functions in tidyquant","text":"Quandl provides access vast number financial economic databases. Quandl packages must installed separately.","code":"install.packages(\"Quandl\")"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"authentication","dir":"Articles","previous_headings":"1.0 Get Quantitative Data > 2.3 Nasdaq Data Link (Quandl) API","what":"Authentication","title":"Core Functions in tidyquant","text":"make full use integration recommend set api key. create sign Quandl account go account api key page.","code":"quandl_api_key(\"\")"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"search","dir":"Articles","previous_headings":"1.0 Get Quantitative Data > 2.3 Nasdaq Data Link (Quandl) API","what":"Search","title":"Core Functions in tidyquant","text":"Searching Quandl within R console possible quandl_search(), wrapper Quandl::Quandl.search(). example search shown . required argument query. can also visit Quandl Search webpage search available database codes.","code":"quandl_search(query = \"Oil\", database_code = \"NSE\", per_page = 3)"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"getting-quandl-data","dir":"Articles","previous_headings":"1.0 Get Quantitative Data > 2.3 Nasdaq Data Link (Quandl) API","what":"Getting Quandl Data","title":"Core Functions in tidyquant","text":"Getting data integrated tq_get(). Two get options exist retrieve Quandl data: get = \"quandl\": Get’s Quandl time series data. wrapper Quandl(). get = \"quandl.datatable\": Gets Quandl datatables (larger data sets may time series). wrapper Quandl.datatable(). Getting data Quandl can achieved much way “get” options. Just pass “codes” data along desired arguments underlying function. following uses get = \"quandl\" “WIKI” database download daily stock prices AAPL 2016. output tidy data frame. following time series options available passed underlying Quandl() function: start_date () = “yyyy-mm-dd” | end_date () = “yyyy-mm-dd” column_index = numeric column number (e.g. 1) rows = numeric row number indicating first n rows (e.g. 100) collapse = “none”, “daily”, “weekly”, “monthly”, “quarterly”, “annual” transform = “none”, “diff”, “rdiff”, “cumul”, “normalize” ’s example get period returns adj.close (column index 11) using column_index, collapse transform arguments. Datatables larger data sets. can downloaded using get = \"quandl.datatable\". Note time series arguments work data tables. ’s several examples Zacks Fundamentals Collection B","code":"c(\"WIKI/AAPL\") %>% tq_get(get = \"quandl\", from = \"2016-01-01\", to = \"2016-12-31\") \"WIKI/AAPL\" %>% tq_get(get = \"quandl\", from = \"2007-01-01\", to = \"2016-12-31\", column_index = 11, collapse = \"annual\", transform = \"rdiff\") # Zacks Fundamentals Collection B (DOW 30 Available to non subscribers) tq_get(\"ZACKS/FC\", get = \"quandl.datatable\") # Zacks Fundamentals Condensed tq_get(\"ZACKS/FR\", get = \"quandl.datatable\") # Zacks Fundamental Ratios tq_get(\"ZACKS/MT\", get = \"quandl.datatable\") # Zacks Master Table tq_get(\"ZACKS/MKTV\", get = \"quandl.datatable\") # Zacks Market Value Supplement tq_get(\"ZACKS/SHRS\", get = \"quandl.datatable\") # Zacks Shares Out Supplement"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"tiingo-api","dir":"Articles","previous_headings":"1.0 Get Quantitative Data","what":"2.4 Tiingo API","title":"Core Functions in tidyquant","text":"Tiingo API free source stock prices, cryptocurrencies, intraday feeds IEX (Investors Exchange). can serve alternate source data Yahoo! Finance.","code":""},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"authentication-1","dir":"Articles","previous_headings":"1.0 Get Quantitative Data > 2.4 Tiingo API","what":"Authentication","title":"Core Functions in tidyquant","text":"make full use integration need get API key set api key. don’t one already, go Tiingo account get FREE API key. can set follows:","code":"tiingo_api_key('')"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"getting-tiingo-data","dir":"Articles","previous_headings":"1.0 Get Quantitative Data > 2.4 Tiingo API","what":"Getting Tiingo Data","title":"Core Functions in tidyquant","text":"tidyquant package provides convenient wrappers riingo package (R interface Tiingo). ’s tq_get() maps riingo: Tiingo Prices: tq_get(get = \"tiingo\") = riingo::riingo_prices() Tiingo IEX Data: tq_get(get = \"tiingo.iex\") = riingo::riingo_iex_prices() Tiingo Crypto Data: tq_get(get = \"tiingo.crypto\") = riingo::riingo_crypto_prices()","code":"# Tiingo Prices (Free alternative to Yahoo Finance!) tq_get(c(\"AAPL\", \"GOOG\"), get = \"tiingo\", from = \"2010-01-01\") # Sub-daily prices from IEX ---- tq_get(c(\"AAPL\", \"GOOG\"), get = \"tiingo.iex\", from = \"2020-01-01\", to = \"2020-01-15\", resample_frequency = \"5min\") # Tiingo Bitcoin in USD ---- tq_get(c(\"btcusd\"), get = \"tiingo.crypto\", from = \"2020-01-01\", to = \"2020-01-15\", resample_frequency = \"5min\")"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"alpha-vantage-api","dir":"Articles","previous_headings":"1.0 Get Quantitative Data","what":"2.5 Alpha Vantage API","title":"Core Functions in tidyquant","text":"Alpha Vantage provides access real-time historical financial data. alphavantager package, lightweight R interface, integrated tidyquant follows. benefit integration scalability since can now get multiple symbols returned tidy format. need install first.","code":"install.packages(\"alphavantager\")"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"authentication-2","dir":"Articles","previous_headings":"1.0 Get Quantitative Data > 2.5 Alpha Vantage API","what":"Authentication","title":"Core Functions in tidyquant","text":"make full use integration need get API key set api key. don’t one already, go Alpha Vantage account get FREE API key. can set follows:","code":"# install.packages(\"alphavantager\") av_api_key(\"\")"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"getting-alpha-vantage-data","dir":"Articles","previous_headings":"1.0 Get Quantitative Data > 2.5 Alpha Vantage API","what":"Getting Alpha Vantage Data","title":"Core Functions in tidyquant","text":"Getting data simple structure follows Alpha Vantage API documentation. example, wish retrieve intraday data 5 minute intervals META MSFT, can build parameters x = c(\"META\", \"MSFT\"), get = \"alphavantager\", av_fun = \"TIME_SERIES_INTRADAY\", interval = \"5min\". familiar x get always use. av_fun argument comes alphavantager::av_get() Alpha Vantage documentation. interval argument comes docs well.","code":"# Scaling is as simple as supplying multiple symbols c(\"META\", \"MSFT\") %>% tq_get(get = \"alphavantage\", av_fun = \"TIME_SERIES_INTRADAY\", interval = \"5min\")"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"bloomberg","dir":"Articles","previous_headings":"1.0 Get Quantitative Data","what":"2.6 Bloomberg","title":"Core Functions in tidyquant","text":"Bloomberg provides access arguably comprehensive financial data actively used major financial instutions work financial data. Rblpapi package, R interface Bloomberg, integrated tidyquant follows. benefit integration scalability since can now get multiple symbols returned tidy format.","code":""},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"authentication-3","dir":"Articles","previous_headings":"1.0 Get Quantitative Data > 2.6 Bloomberg","what":"Authentication","title":"Core Functions in tidyquant","text":"make full use integration need Bloomberg Terminal account (Note free service). Bloomberg Terminal running machine, can connect follows:","code":"# install.packages(\"Rblpapi\") Rblpapi::blpConnect()"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"getting-bloomberg-data","dir":"Articles","previous_headings":"1.0 Get Quantitative Data > 2.6 Bloomberg","what":"Getting Bloomberg Data","title":"Core Functions in tidyquant","text":"Getting data simple structure follows Rblpapi API documentation. example, wish retrieve monthly data SPX Index AGTHX Equity, can build tq_get parameters follows: x = c('SPX Index','ODMAX Equity') get = \"rblpapi\" rblpapi_fun = \"bdh\" Note “bdh” default, options include “bdh” (Bloomberg Data History), “bds” (Bloomberg Data Set), “bdp” (Bloomberg Data Point) / get passed start.date end.date can provided “YYYY-MM-DD” character format. Note start.date end.date Rblpapi can used must converted date datetime. arguments: options depend rblpapi_fun. See Rblpapi documentation.","code":"# Get Bloomberg data in a tidy data frame my_bloomberg_data <- c('SPX Index','ODMAX Equity') %>% tq_get(get = \"Rblpapi\", rblpapi_fun = \"bdh\", fields = c(\"PX_LAST\"), options = c(\"periodicitySelection\" = \"WEEKLY\"), from = \"2016-01-01\", to = \"2016-12-31\")"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"mutate-quantitative-data","dir":"Articles","previous_headings":"","what":"3.0 Mutate Quantitative Data","title":"Core Functions in tidyquant","text":"Mutating functions enable xts/zoo, quantmod TTR functions shine. ’ll touch mutation functions briefly using FANG data set, consists daily prices META, AMZN, GOOG, NFLX beginning 2013 end 2016. ’ll apply functions grouped data sets get feel works detailed walkthrough compatible functions, see next vignette series, R Quantitative Analysis Package Integrations tidyquant.","code":"FANG ## # A tibble: 4,032 × 8 ## symbol date open high low close volume adjusted ## ## 1 META 2013-01-02 27.4 28.2 27.4 28 69846400 28 ## 2 META 2013-01-03 27.9 28.5 27.6 27.8 63140600 27.8 ## 3 META 2013-01-04 28.0 28.9 27.8 28.8 72715400 28.8 ## 4 META 2013-01-07 28.7 29.8 28.6 29.4 83781800 29.4 ## 5 META 2013-01-08 29.5 29.6 28.9 29.1 45871300 29.1 ## 6 META 2013-01-09 29.7 30.6 29.5 30.6 104787700 30.6 ## 7 META 2013-01-10 30.6 31.5 30.3 31.3 95316400 31.3 ## 8 META 2013-01-11 31.3 32.0 31.1 31.7 89598000 31.7 ## 9 META 2013-01-14 32.1 32.2 30.6 31.0 98892800 31.0 ## 10 META 2013-01-15 30.6 31.7 29.9 30.1 173242600 30.1 ## # ℹ 4,022 more rows"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"transmute-quantitative-data-tq_transmute","dir":"Articles","previous_headings":"3.0 Mutate Quantitative Data","what":"3.1 Transmute Quantitative Data, tq_transmute","title":"Core Functions in tidyquant","text":"Transmute results tq_get(). Transmute holds almost meaning dplyr, newly created columns returned, tq_transmute(), number rows returned can different original data frame. important changing periodicity. example periodicity aggregation daily monthly. Let’s go happened. select allows easily choose columns get passed mutate_fun. example , adjusted selects “adjusted” column data, sends mutate function, .monthly, mutates periodicity daily monthly. Additional arguments can passed mutate_fun way .... passing indexAt argument return date matches first date period.","code":"FANG %>% group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = to.monthly, indexAt = \"lastof\") ## # A tibble: 192 × 3 ## # Groups: symbol [4] ## symbol date adjusted ## ## 1 META 2013-01-31 31.0 ## 2 META 2013-02-28 27.2 ## 3 META 2013-03-31 25.6 ## 4 META 2013-04-30 27.8 ## 5 META 2013-05-31 24.4 ## 6 META 2013-06-30 24.9 ## 7 META 2013-07-31 36.8 ## 8 META 2013-08-31 41.3 ## 9 META 2013-09-30 50.2 ## 10 META 2013-10-31 50.2 ## # ℹ 182 more rows"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"working-with-non-ohlc-data","dir":"Articles","previous_headings":"3.0 Mutate Quantitative Data > 3.1 Transmute Quantitative Data, tq_transmute","what":"Working with non-OHLC data","title":"Core Functions in tidyquant","text":"Returns FRED, Oanda, sources open, high, low, close (OHLC) format. However, problem select. following example shows transmute WTI Crude daily prices monthly prices. Since single column pass, can leave select argument NULL selects columns default. sends price column .period mutate function.","code":"wti_prices <- tq_get(\"DCOILWTICO\", get = \"economic.data\") wti_prices %>% tq_transmute(mutate_fun = to.period, period = \"months\", col_rename = \"WTI Price\") ## # A tibble: 129 × 2 ## date `WTI Price` ## ## 1 2013-01-31 97.6 ## 2 2013-02-28 92.0 ## 3 2013-03-28 97.2 ## 4 2013-04-30 93.2 ## 5 2013-05-31 91.9 ## 6 2013-06-28 96.4 ## 7 2013-07-31 105. ## 8 2013-08-30 108. ## 9 2013-09-30 102. ## 10 2013-10-31 96.3 ## # ℹ 119 more rows"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"mutate-quantitative-data-tq_mutate","dir":"Articles","previous_headings":"3.0 Mutate Quantitative Data","what":"3.2 Mutate Quantitative Data, tq_mutate","title":"Core Functions in tidyquant","text":"Adds column set columns tibble calculated attributes (hence original tibble returned, mutated additional columns). example getting MACD close, mutates original input adding MACD Signal columns. Note can quickly rename columns using col_rename argument. Note mutation can occur , , mutation structure original tibble. words, calculation must number rows row.names (date fields), otherwise mutation performed.","code":"FANG %>% group_by(symbol) %>% tq_mutate(select = close, mutate_fun = MACD, col_rename = c(\"MACD\", \"Signal\")) ## # A tibble: 4,032 × 10 ## # Groups: symbol [4] ## symbol date open high low close volume adjusted MACD Signal ## ## 1 META 2013-01-02 27.4 28.2 27.4 28 69846400 28 NA NA ## 2 META 2013-01-03 27.9 28.5 27.6 27.8 63140600 27.8 NA NA ## 3 META 2013-01-04 28.0 28.9 27.8 28.8 72715400 28.8 NA NA ## 4 META 2013-01-07 28.7 29.8 28.6 29.4 83781800 29.4 NA NA ## 5 META 2013-01-08 29.5 29.6 28.9 29.1 45871300 29.1 NA NA ## 6 META 2013-01-09 29.7 30.6 29.5 30.6 104787700 30.6 NA NA ## 7 META 2013-01-10 30.6 31.5 30.3 31.3 95316400 31.3 NA NA ## 8 META 2013-01-11 31.3 32.0 31.1 31.7 89598000 31.7 NA NA ## 9 META 2013-01-14 32.1 32.2 30.6 31.0 98892800 31.0 NA NA ## 10 META 2013-01-15 30.6 31.7 29.9 30.1 173242600 30.1 NA NA ## # ℹ 4,022 more rows"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"mutate-rolling-regressions-with-rollapply","dir":"Articles","previous_headings":"3.0 Mutate Quantitative Data > 3.2 Mutate Quantitative Data, tq_mutate","what":"Mutate rolling regressions with rollapply","title":"Core Functions in tidyquant","text":"powerful example applying custom functions across rolling window using rollapply. specific example using rollapply function compute rolling regression. example slightly complicated broken three steps: Get returns Create custom function Apply custom function accross rolling window using tq_mutate(mutate_fun = rollapply) Step 1: Get Returns First, get combined returns. asset baseline returns wide format, needed lm function next step. Step 2: Create custom function Next, create custom regression function, used apply rolling window Step 3. important point “data” passed regression function xts object. timetk::tk_tbl function takes care converting data frame lm function work properly columns “fb.returns” “xlk.returns”. Step 3: Apply custom function Now can use tq_mutate() apply custom regression function rolling window using rollapply zoo package. Internally, since left select = NULL, returns_combined data frame passed automatically data argument rollapply function. need specify mutate_fun = rollapply additional arguments necessary apply rollapply function. ’ll specify 12 week window via width = 12. FUN argument custom regression function, regr_fun. ’s extremely important specify .column = FALSE, tells rollapply perform computation using data whole rather apply function column independently. col_rename argument used rename added columns. shown , rolling regression coefficients added data frame.","code":"fb_returns <- tq_get(\"META\", get = \"stock.prices\", from = \"2016-01-01\", to = \"2016-12-31\") %>% tq_transmute(adjusted, periodReturn, period = \"weekly\", col_rename = \"fb.returns\") xlk_returns <- tq_get(\"XLK\", from = \"2016-01-01\", to = \"2016-12-31\") %>% tq_transmute(adjusted, periodReturn, period = \"weekly\", col_rename = \"xlk.returns\") returns_combined <- left_join(fb_returns, xlk_returns, by = \"date\") returns_combined ## # A tibble: 52 × 3 ## date fb.returns xlk.returns ## ## 1 2016-01-08 -0.0478 -0.0516 ## 2 2016-01-15 -0.0242 -0.0187 ## 3 2016-01-22 0.0313 0.0264 ## 4 2016-01-29 0.146 0.0213 ## 5 2016-02-05 -0.0725 -0.0422 ## 6 2016-02-12 -0.0198 -0.00582 ## 7 2016-02-19 0.0251 0.0354 ## 8 2016-02-26 0.0320 0.0148 ## 9 2016-03-04 0.00436 0.0281 ## 10 2016-03-11 0.00941 0.0106 ## # ℹ 42 more rows regr_fun <- function(data) { coef(lm(fb.returns ~ xlk.returns, data = timetk::tk_tbl(data, silent = TRUE))) } returns_combined %>% tq_mutate(mutate_fun = rollapply, width = 12, FUN = regr_fun, by.column = FALSE, col_rename = c(\"coef.0\", \"coef.1\")) ## # A tibble: 52 × 5 ## date fb.returns xlk.returns coef.0 coef.1 ## ## 1 2016-01-08 -0.0478 -0.0516 NA NA ## 2 2016-01-15 -0.0242 -0.0187 NA NA ## 3 2016-01-22 0.0313 0.0264 NA NA ## 4 2016-01-29 0.146 0.0213 NA NA ## 5 2016-02-05 -0.0725 -0.0422 NA NA ## 6 2016-02-12 -0.0198 -0.00582 NA NA ## 7 2016-02-19 0.0251 0.0354 NA NA ## 8 2016-02-26 0.0320 0.0148 NA NA ## 9 2016-03-04 0.00436 0.0281 NA NA ## 10 2016-03-11 0.00941 0.0106 NA NA ## # ℹ 42 more rows returns_combined ## # A tibble: 52 × 3 ## date fb.returns xlk.returns ## ## 1 2016-01-08 -0.0478 -0.0516 ## 2 2016-01-15 -0.0242 -0.0187 ## 3 2016-01-22 0.0313 0.0264 ## 4 2016-01-29 0.146 0.0213 ## 5 2016-02-05 -0.0725 -0.0422 ## 6 2016-02-12 -0.0198 -0.00582 ## 7 2016-02-19 0.0251 0.0354 ## 8 2016-02-26 0.0320 0.0148 ## 9 2016-03-04 0.00436 0.0281 ## 10 2016-03-11 0.00941 0.0106 ## # ℹ 42 more rows"},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"xy-variants-tq_mutate_xy-and-tq_transmute_xy","dir":"Articles","previous_headings":"3.0 Mutate Quantitative Data","what":"3.3 _xy Variants, tq_mutate_xy and tq_transmute_xy","title":"Core Functions in tidyquant","text":"Enables working mutation functions require two primary inputs (e.g. EVWMA, VWAP, etc).","code":""},{"path":"/articles/TQ01-core-functions-in-tidyquant.html","id":"mutate-with-two-primary-inputs","dir":"Articles","previous_headings":"3.0 Mutate Quantitative Data > 3.3 _xy Variants, tq_mutate_xy and tq_transmute_xy","what":"Mutate with two primary inputs","title":"Core Functions in tidyquant","text":"EVWMA (exponential volume-weighted moving average) requires two inputs, price volume. work columns, can switch xy variants, tq_transmute_xy() tq_mutate_xy(). difference instead select argument, use x y arguments pass columns needed based mutate_fun documentation.","code":"FANG %>% group_by(symbol) %>% tq_mutate_xy(x = close, y = volume, mutate_fun = EVWMA, col_rename = \"EVWMA\") ## # A tibble: 4,032 × 9 ## # Groups: symbol [4] ## symbol date open high low close volume adjusted EVWMA ## ## 1 META 2013-01-02 27.4 28.2 27.4 28 69846400 28 NA ## 2 META 2013-01-03 27.9 28.5 27.6 27.8 63140600 27.8 NA ## 3 META 2013-01-04 28.0 28.9 27.8 28.8 72715400 28.8 NA ## 4 META 2013-01-07 28.7 29.8 28.6 29.4 83781800 29.4 NA ## 5 META 2013-01-08 29.5 29.6 28.9 29.1 45871300 29.1 NA ## 6 META 2013-01-09 29.7 30.6 29.5 30.6 104787700 30.6 NA ## 7 META 2013-01-10 30.6 31.5 30.3 31.3 95316400 31.3 NA ## 8 META 2013-01-11 31.3 32.0 31.1 31.7 89598000 31.7 NA ## 9 META 2013-01-14 32.1 32.2 30.6 31.0 98892800 31.0 NA ## 10 META 2013-01-15 30.6 31.7 29.9 30.1 173242600 30.1 30.1 ## # ℹ 4,022 more rows"},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"overview","dir":"Articles","previous_headings":"","what":"Overview","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"’s wide range useful quantitative analysis functions work time-series objects. problem many wonderful functions don’t work data frames tidyverse workflow. now! tidyquant package integrates useful functions xts, zoo, quantmod, TTR, PerformanceAnalytics packages. vignette focuses following core functions demonstrate integratation works quantitative finance packages: Transmute, tq_transmute(): Returns new tidy data frame typically different periodicity input. Mutate, tq_mutate(): Adds columns existing tidy data frame. Refer Performance Analysis tidyquant full discussion performance analysis portfolio attribution tidyquant.","code":""},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"prerequisites","dir":"Articles","previous_headings":"","what":"Prerequisites","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"Load tidyquant package get started.","code":"# Loads tidyquant, lubridate, xts, quantmod, TTR library(tidyquant) library(lubridate) library(dplyr) library(tidyr) library(ggplot2)"},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"function-compatibility","dir":"Articles","previous_headings":"","what":"1.0 Function Compatibility","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"tq_transmute_fun_options() returns list compatible mutate functions package. ’ll discuss options package briefly.","code":"tq_transmute_fun_options() %>% str() ## List of 5 ## $ zoo : chr [1:14] \"rollapply\" \"rollapplyr\" \"rollmax\" \"rollmax.default\" ... ## $ xts : chr [1:27] \"apply.daily\" \"apply.monthly\" \"apply.quarterly\" \"apply.weekly\" ... ## $ quantmod : chr [1:25] \"allReturns\" \"annualReturn\" \"ClCl\" \"dailyReturn\" ... ## $ TTR : chr [1:64] \"adjRatios\" \"ADX\" \"ALMA\" \"aroon\" ... ## $ PerformanceAnalytics: chr [1:7] \"Return.annualized\" \"Return.annualized.excess\" \"Return.clean\" \"Return.cumulative\" ..."},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"zoo-functionality","dir":"Articles","previous_headings":"1.0 Function Compatibility","what":"zoo Functionality","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"zoo functions compatible listed . Generally speaking, : generic function applying function rolling margins. Form: rollapply(data, width, FUN, ..., = 1, .column = TRUE, fill = (na.pad) NA, na.pad = FALSE, partial = FALSE, align = c(\"center\", \"left\", \"right\"), coredata = TRUE). Options include rollmax, rollmean, rollmedian, rollsum, etc.","code":"# Get zoo functions that work with tq_transmute and tq_mutate tq_transmute_fun_options()$zoo ## [1] \"rollapply\" \"rollapplyr\" \"rollmax\" ## [4] \"rollmax.default\" \"rollmaxr\" \"rollmean\" ## [7] \"rollmean.default\" \"rollmeanr\" \"rollmedian\" ## [10] \"rollmedian.default\" \"rollmedianr\" \"rollsum\" ## [13] \"rollsum.default\" \"rollsumr\""},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"xts-functionality","dir":"Articles","previous_headings":"1.0 Function Compatibility","what":"xts Functionality","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"xts functions compatible listed . Generally speaking, : Apply function time segment (e.g. max, min, mean, etc). Form: apply.daily(x, FUN, ...). Options include apply.daily, weekly, monthly, quarterly, yearly. Convert time series time series lower periodicity (e.g. convert daily monthly periodicity). Form: .period(x, period = 'months', k = 1, indexAt, name = NULL, OHLC = TRUE, ...). Options include .minutes, hourly, daily, weekly, monthly, quarterly, yearly. Note 1 (Important): return structure different .period .monthly (.weekly, .quarterly, etc) forms. .period returns date, .months returns character MON YYYY. Best use .period want work time-series via lubridate.","code":"# Get xts functions that work with tq_transmute and tq_mutate tq_transmute_fun_options()$xts ## [1] \"apply.daily\" \"apply.monthly\" \"apply.quarterly\" \"apply.weekly\" ## [5] \"apply.yearly\" \"diff.xts\" \"lag.xts\" \"period.apply\" ## [9] \"period.max\" \"period.min\" \"period.prod\" \"period.sum\" ## [13] \"periodicity\" \"to_period\" \"to.daily\" \"to.hourly\" ## [17] \"to.minutes\" \"to.minutes10\" \"to.minutes15\" \"to.minutes3\" ## [21] \"to.minutes30\" \"to.minutes5\" \"to.monthly\" \"to.period\" ## [25] \"to.quarterly\" \"to.weekly\" \"to.yearly\""},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"quantmod-functionality","dir":"Articles","previous_headings":"1.0 Function Compatibility","what":"quantmod Functionality","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"quantmod functions compatible listed . Generally speaking, : Variations Delt: ClCl, HiCl, LoCl, LoHi, OpCl, OpHi, OpLo, OpOp Form: OpCl(OHLC) Lag: Lag(x, k = 1) / Next: Next(x, k = 1) (Can also use dplyr::lag dplyr::lead) Get arithmetic logarithmic returns various periodicity, include daily, weekly, monthly, quarterly, yearly. Form: periodReturn(x, period = 'monthly', subset = NULL, type = 'arithmetic', leading = TRUE, ...) Return values describe series. Options include describing increases/decreases, acceleration/deceleration, hi/low. Forms: seriesHi(x), seriesIncr(x, thresh = 0, diff. = 1L), seriesAccel(x)","code":"# Get quantmod functions that work with tq_transmute and tq_mutate tq_transmute_fun_options()$quantmod ## [1] \"allReturns\" \"annualReturn\" \"ClCl\" \"dailyReturn\" ## [5] \"Delt\" \"HiCl\" \"Lag\" \"LoCl\" ## [9] \"LoHi\" \"monthlyReturn\" \"Next\" \"OpCl\" ## [13] \"OpHi\" \"OpLo\" \"OpOp\" \"periodReturn\" ## [17] \"quarterlyReturn\" \"seriesAccel\" \"seriesDecel\" \"seriesDecr\" ## [21] \"seriesHi\" \"seriesIncr\" \"seriesLo\" \"weeklyReturn\" ## [25] \"yearlyReturn\""},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"ttr-functionality","dir":"Articles","previous_headings":"1.0 Function Compatibility","what":"TTR Functionality","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"’ brief description popular functions TTR: ADX(HLC, n = 14, maType, ...) BBands(HLC, n = 20, maType, sd = 2, ...): Bollinger Bands ROC(x, n = 1, type = c(\"continuous\", \"discrete\"), na.pad = TRUE): Rate Change momentum(x, n = 1, na.pad = TRUE): Momentum SMA(x, n = 10, ...): Simple Moving Average EMA(x, n = 10, wilder = FALSE, ratio = NULL, ...): Exponential Moving Average DEMA(x, n = 10, v = 1, wilder = FALSE, ratio = NULL): Double Exponential Moving Average WMA(x, n = 10, wts = 1:n, ...): Weighted Moving Average EVWMA(price, volume, n = 10, ...): Elastic, Volume-Weighted Moving Average ZLEMA(x, n = 10, ratio = NULL, ...): Zero Lag Exponential Moving Average VWAP(price, volume, n = 10, ...): Volume-Weighted Moving Average Price VMA(x, w, ratio = 1, ...): Variable-Length Moving Average HMA(x, n = 20, ...): Hull Moving Average ALMA(x, n = 9, offset = 0.85, sigma = 6, ...): Arnaud Legoux Moving Average MACD(x, nFast = 12, nSlow = 26, nSig = 9, maType, percent = TRUE, ...) RSI(price, n = 14, maType, ...) runSum(x, n = 10, cumulative = FALSE): returns sums n-period moving window. runMin(x, n = 10, cumulative = FALSE): returns minimums n-period moving window. runMax(x, n = 10, cumulative = FALSE): returns maximums n-period moving window. runMean(x, n = 10, cumulative = FALSE): returns means n-period moving window. runMedian(x, n = 10, non.unique = \"mean\", cumulative = FALSE): returns medians n-period moving window. runCov(x, y, n = 10, use = \".obs\", sample = TRUE, cumulative = FALSE): returns covariances n-period moving window. runCor(x, y, n = 10, use = \".obs\", sample = TRUE, cumulative = FALSE): returns correlations n-period moving window. runVar(x, y = NULL, n = 10, sample = TRUE, cumulative = FALSE): returns variances n-period moving window. runSD(x, n = 10, sample = TRUE, cumulative = FALSE): returns standard deviations n-period moving window. runMAD(x, n = 10, center = NULL, stat = \"median\", constant = 1.4826, non.unique = \"mean\", cumulative = FALSE): returns median/mean absolute deviations n-period moving window. wilderSum(x, n = 10): retuns Welles Wilder style weighted sum n-period moving window. stoch(HLC, nFastK = 14, nFastD = 3, nSlowD = 3, maType, bounded = TRUE, smooth = 1, ...): Stochastic Oscillator SMI(HLC, n = 13, nFast = 2, nSlow = 25, nSig = 9, maType, bounded = TRUE, ...): Stochastic Momentum Index","code":"# Get TTR functions that work with tq_transmute and tq_mutate tq_transmute_fun_options()$TTR ## [1] \"adjRatios\" \"ADX\" \"ALMA\" ## [4] \"aroon\" \"ATR\" \"BBands\" ## [7] \"CCI\" \"chaikinAD\" \"chaikinVolatility\" ## [10] \"CLV\" \"CMF\" \"CMO\" ## [13] \"CTI\" \"DEMA\" \"DonchianChannel\" ## [16] \"DPO\" \"DVI\" \"EMA\" ## [19] \"EMV\" \"EVWMA\" \"GMMA\" ## [22] \"growth\" \"HMA\" \"keltnerChannels\" ## [25] \"KST\" \"lags\" \"MACD\" ## [28] \"MFI\" \"momentum\" \"OBV\" ## [31] \"PBands\" \"ROC\" \"rollSFM\" ## [34] \"RSI\" \"runCor\" \"runCov\" ## [37] \"runMAD\" \"runMax\" \"runMean\" ## [40] \"runMedian\" \"runMin\" \"runPercentRank\" ## [43] \"runSD\" \"runSum\" \"runVar\" ## [46] \"SAR\" \"SMA\" \"SMI\" ## [49] \"SNR\" \"stoch\" \"TDI\" ## [52] \"TRIX\" \"ultimateOscillator\" \"VHF\" ## [55] \"VMA\" \"volatility\" \"VWAP\" ## [58] \"VWMA\" \"wilderSum\" \"williamsAD\" ## [61] \"WMA\" \"WPR\" \"ZigZag\" ## [64] \"ZLEMA\""},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"performanceanalytics-functionality","dir":"Articles","previous_headings":"1.0 Function Compatibility","what":"PerformanceAnalytics Functionality","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"PerformanceAnalytics mutation functions deal returns: Return.annualized Return.annualized.excess: Takes period returns consolidates annualized returns Return.clean: Removes outliers returns Return.excess: Removes risk-free rate returns yield returns excess risk-free rate zerofill: Used replace NA values zeros.","code":"# Get PerformanceAnalytics functions that work with tq_transmute and tq_mutate tq_transmute_fun_options()$PerformanceAnalytics ## [1] \"Return.annualized\" \"Return.annualized.excess\" ## [3] \"Return.clean\" \"Return.cumulative\" ## [5] \"Return.excess\" \"Return.Geltner\" ## [7] \"zerofill\""},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"quantitative-power-in-action","dir":"Articles","previous_headings":"","what":"2.0 Quantitative Power In Action","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"’ll go examples, first let’s get data. FANG data set used consists stock prices META, AMZN, NFLX, GOOG beginning 2013 end 2016.","code":"FANG ## # A tibble: 4,032 × 8 ## symbol date open high low close volume adjusted ## ## 1 META 2013-01-02 27.4 28.2 27.4 28 69846400 28 ## 2 META 2013-01-03 27.9 28.5 27.6 27.8 63140600 27.8 ## 3 META 2013-01-04 28.0 28.9 27.8 28.8 72715400 28.8 ## 4 META 2013-01-07 28.7 29.8 28.6 29.4 83781800 29.4 ## 5 META 2013-01-08 29.5 29.6 28.9 29.1 45871300 29.1 ## 6 META 2013-01-09 29.7 30.6 29.5 30.6 104787700 30.6 ## 7 META 2013-01-10 30.6 31.5 30.3 31.3 95316400 31.3 ## 8 META 2013-01-11 31.3 32.0 31.1 31.7 89598000 31.7 ## 9 META 2013-01-14 32.1 32.2 30.6 31.0 98892800 31.0 ## 10 META 2013-01-15 30.6 31.7 29.9 30.1 173242600 30.1 ## # ℹ 4,022 more rows"},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"example-1-use-quantmod-periodreturn-to-convert-prices-to-returns","dir":"Articles","previous_headings":"2.0 Quantitative Power In Action","what":"Example 1: Use quantmod periodReturn to Convert Prices to Returns","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"quantmod::periodReturn() function generates returns periodicity. ’ll go couple usage cases.","code":""},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"example-1a-getting-and-charting-annual-returns","dir":"Articles","previous_headings":"2.0 Quantitative Power In Action > Example 1: Use quantmod periodReturn to Convert Prices to Returns","what":"Example 1A: Getting and Charting Annual Returns","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"want use adjusted closing prices column (adjusted stock splits, can make appear stock performing poorly split included). set select = adjusted. research periodReturn function, found accepts type = \"arithmetic\" period = \"yearly\", returns annual returns. Charting annual returns just quick use ggplot2 package.","code":"FANG_annual_returns <- FANG %>% group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"yearly\", type = \"arithmetic\") FANG_annual_returns ## # A tibble: 16 × 3 ## # Groups: symbol [4] ## symbol date yearly.returns ## ## 1 META 2013-12-31 0.952 ## 2 META 2014-12-31 0.428 ## 3 META 2015-12-31 0.341 ## 4 META 2016-12-30 0.0993 ## 5 AMZN 2013-12-31 0.550 ## 6 AMZN 2014-12-31 -0.222 ## 7 AMZN 2015-12-31 1.18 ## 8 AMZN 2016-12-30 0.109 ## 9 NFLX 2013-12-31 3.00 ## 10 NFLX 2014-12-31 -0.0721 ## 11 NFLX 2015-12-31 1.34 ## 12 NFLX 2016-12-30 0.0824 ## 13 GOOG 2013-12-31 0.550 ## 14 GOOG 2014-12-31 -0.0597 ## 15 GOOG 2015-12-31 0.442 ## 16 GOOG 2016-12-30 0.0171 FANG_annual_returns %>% ggplot(aes(x = date, y = yearly.returns, fill = symbol)) + geom_col() + geom_hline(yintercept = 0, color = palette_light()[[1]]) + scale_y_continuous(labels = scales::percent) + labs(title = \"FANG: 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()"},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"example-1b-getting-daily-log-returns","dir":"Articles","previous_headings":"2.0 Quantitative Power In Action > Example 1: Use quantmod periodReturn to Convert Prices to Returns","what":"Example 1B: Getting Daily Log Returns","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"Daily log returns follows similar approach. Normally go transmute function, tq_transmute, periodReturn function accepts different periodicity options, anything daily blow mutation. , situation period returns periodicity stock prices periodicity (daily), can use either. want use adjusted closing prices column (adjusted stock splits, can make appear stock performing poorly split included), set select = adjusted. researched periodReturn function, found accepts type = \"log\" period = \"daily\", returns daily log returns.","code":"FANG_daily_log_returns <- FANG %>% group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"daily\", type = \"log\", col_rename = \"monthly.returns\") FANG_daily_log_returns %>% ggplot(aes(x = monthly.returns, fill = symbol)) + geom_density(alpha = 0.5) + labs(title = \"FANG: Charting the Daily Log Returns\", x = \"Monthly Returns\", y = \"Density\") + theme_tq() + scale_fill_tq() + facet_wrap(~ symbol, ncol = 2)"},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"example-2-use-xts-to-period-to-change-the-periodicity-from-daily-to-monthly","dir":"Articles","previous_headings":"2.0 Quantitative Power In Action","what":"Example 2: Use xts to.period to Change the Periodicity from Daily to Monthly","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"xts::.period function used periodicity aggregation (converting lower level periodicity higher level minutes hours months years). seeking return structure different time scale input (daily versus weekly), need use transmute function. select tq_transmute() pass open, high, low, close volume columns via select = open:volume. Looking documentation .period, see accepts period argument can set \"weeks\". result OHLCV data returned dates changed one day per week. common usage case reduce number points smooth time series plots. Let’s check difference daily monthly plots.","code":"FANG %>% group_by(symbol) %>% tq_transmute(select = open:volume, mutate_fun = to.period, period = \"months\") ## # A tibble: 192 × 7 ## # Groups: symbol [4] ## symbol date open high low close volume ## ## 1 META 2013-01-31 29.2 31.5 28.7 31.0 190744900 ## 2 META 2013-02-28 26.8 27.3 26.3 27.2 83027800 ## 3 META 2013-03-28 26.1 26.2 25.5 25.6 28585700 ## 4 META 2013-04-30 27.1 27.8 27.0 27.8 36245700 ## 5 META 2013-05-31 24.6 25.0 24.3 24.4 35925000 ## 6 META 2013-06-28 24.7 25.0 24.4 24.9 96778900 ## 7 META 2013-07-31 38.0 38.3 36.3 36.8 154828700 ## 8 META 2013-08-30 42.0 42.3 41.1 41.3 67735100 ## 9 META 2013-09-30 50.1 51.6 49.8 50.2 100095000 ## 10 META 2013-10-31 47.2 52 46.5 50.2 248809000 ## # ℹ 182 more rows"},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"without-periodicity-aggregation","dir":"Articles","previous_headings":"2.0 Quantitative Power In Action > Example 2: Use xts to.period to Change the Periodicity from Daily to Monthly","what":"Without Periodicity Aggregation","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"","code":"FANG_daily <- FANG %>% group_by(symbol) FANG_daily %>% ggplot(aes(x = date, y = adjusted, color = symbol)) + geom_line(linewidth = 1) + labs(title = \"Daily Stock Prices\", x = \"\", y = \"Adjusted Prices\", color = \"\") + facet_wrap(~ symbol, ncol = 2, scales = \"free_y\") + scale_y_continuous(labels = scales::dollar) + theme_tq() + scale_color_tq()"},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"with-monthly-periodicity-aggregation","dir":"Articles","previous_headings":"2.0 Quantitative Power In Action > Example 2: Use xts to.period to Change the Periodicity from Daily to Monthly","what":"With Monthly Periodicity Aggregation","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"","code":"FANG_monthly <- FANG %>% group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = to.period, period = \"months\") FANG_monthly %>% ggplot(aes(x = date, y = adjusted, color = symbol)) + geom_line(linewidth = 1) + labs(title = \"Monthly Stock Prices\", x = \"\", y = \"Adjusted Prices\", color = \"\") + facet_wrap(~ symbol, ncol = 2, scales = \"free_y\") + scale_y_continuous(labels = scales::dollar) + theme_tq() + scale_color_tq()"},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"example-3-use-ttr-runcor-to-visualize-rolling-correlations-of-returns","dir":"Articles","previous_headings":"2.0 Quantitative Power In Action","what":"Example 3: Use TTR runCor to Visualize Rolling Correlations of Returns","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"Return correlations common way analyze closely asset portfolio mimics baseline index fund. need set returns stocks baseline. stock FANG data set baseline Spdr XLK technology sector. prices “FANG” stocks, use tq_get retrieve “XLK” prices. returns can calculated “adjusted” prices using process Example 1. Next, join asset returns baseline returns date. TTR::runCor function can used evaluate rolling correlations using xy pattern. Looking documentation (?runCor), can see arguments include x y along additional arguments including n width rolling correlation. scale monthly, ’ll go n = 6 6-month rolling correlation. col_rename argument enables easy renaming output column(s). , can plot rolling correlations FANG stocks.","code":"# Asset Returns FANG_returns_monthly <- FANG %>% dplyr::group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"monthly\") # Baseline Returns baseline_returns_monthly <- \"XLK\" %>% tq_get(get = \"stock.prices\", from = \"2013-01-01\", to = \"2016-12-31\") %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"monthly\") returns_joined <- left_join(FANG_returns_monthly, baseline_returns_monthly, by = \"date\") returns_joined ## # A tibble: 192 × 4 ## # Groups: symbol [4] ## symbol date monthly.returns.x monthly.returns.y ## ## 1 META 2013-01-31 0.106 -0.0138 ## 2 META 2013-02-28 -0.120 0.00782 ## 3 META 2013-03-28 -0.0613 0.0258 ## 4 META 2013-04-30 0.0856 0.0175 ## 5 META 2013-05-31 -0.123 0.0279 ## 6 META 2013-06-28 0.0218 -0.0289 ## 7 META 2013-07-31 0.479 0.0373 ## 8 META 2013-08-30 0.122 -0.0104 ## 9 META 2013-09-30 0.217 0.0253 ## 10 META 2013-10-31 -0.000398 0.0503 ## # ℹ 182 more rows FANG_rolling_corr <- returns_joined %>% tq_transmute_xy(x = monthly.returns.x, y = monthly.returns.y, mutate_fun = runCor, n = 6, col_rename = \"rolling.corr.6\") FANG_rolling_corr %>% ggplot(aes(x = date, y = rolling.corr.6, color = symbol)) + geom_hline(yintercept = 0, color = palette_light()[[1]]) + geom_line(linewidth = 1) + labs(title = \"FANG: Six Month Rolling Correlation to XLK\", x = \"\", y = \"Correlation\", color = \"\") + facet_wrap(~ symbol, ncol = 2) + theme_tq() + scale_color_tq()"},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"example-4-use-ttr-macd-to-visualize-moving-average-convergence-divergence","dir":"Articles","previous_headings":"2.0 Quantitative Power In Action","what":"Example 4: Use TTR MACD to Visualize Moving Average Convergence Divergence","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"reviewing available options TTR package, see MACD get us Moving Average Convergence Divergence (MACD). researching documentation, return periodicity input functions work OHLC functions, can use tq_mutate(). MACD requires price, select close. , can visualize data like .","code":"FANG_macd <- FANG %>% group_by(symbol) %>% tq_mutate(select = close, mutate_fun = MACD, nFast = 12, nSlow = 26, nSig = 9, maType = SMA) %>% mutate(diff = macd - signal) %>% select(-(open:volume)) FANG_macd ## # A tibble: 4,032 × 6 ## # Groups: symbol [4] ## symbol date adjusted macd signal diff ## ## 1 META 2013-01-02 28 NA NA NA ## 2 META 2013-01-03 27.8 NA NA NA ## 3 META 2013-01-04 28.8 NA NA NA ## 4 META 2013-01-07 29.4 NA NA NA ## 5 META 2013-01-08 29.1 NA NA NA ## 6 META 2013-01-09 30.6 NA NA NA ## 7 META 2013-01-10 31.3 NA NA NA ## 8 META 2013-01-11 31.7 NA NA NA ## 9 META 2013-01-14 31.0 NA NA NA ## 10 META 2013-01-15 30.1 NA NA NA ## # ℹ 4,022 more rows FANG_macd %>% filter(date >= as_date(\"2016-10-01\")) %>% ggplot(aes(x = date)) + geom_hline(yintercept = 0, color = palette_light()[[1]]) + geom_line(aes(y = macd, col = symbol)) + geom_line(aes(y = signal), color = \"blue\", linetype = 2) + geom_bar(aes(y = diff), stat = \"identity\", color = palette_light()[[1]]) + facet_wrap(~ symbol, ncol = 2, scale = \"free_y\") + labs(title = \"FANG: Moving Average Convergence Divergence\", y = \"MACD\", x = \"\", color = \"\") + theme_tq() + scale_color_tq()"},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"example-5-use-xts-apply-quarterly-to-get-the-max-and-min-price-for-each-quarter","dir":"Articles","previous_headings":"2.0 Quantitative Power In Action","what":"Example 5: Use xts apply.quarterly to Get the Max and Min Price for Each Quarter","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"xts::apply.quarterly() function part period apply group can used apply functions quarterly time segments. seeking return structure different time scale input (quarterly versus daily), need use transmute function. select tq_transmute pass close price using select, send subset data apply.quarterly function via mutate_fun argument. Looking documentation apply.quarterly, see can pass function argument, FUN. want maximum values, set FUN = max. result quarters returned date maximum closing price quarter returned double. minimum quarter can retrieved much way. data frames can joined using left_join get max min quarter. , can visualize data like .","code":"FANG_max_by_qtr <- FANG %>% group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = apply.quarterly, FUN = max, col_rename = \"max.close\") %>% mutate(year.qtr = paste0(year(date), \"-Q\", quarter(date))) %>% select(-date) FANG_max_by_qtr ## # A tibble: 64 × 3 ## # Groups: symbol [4] ## symbol max.close year.qtr ## ## 1 META 32.5 2013-Q1 ## 2 META 29.0 2013-Q2 ## 3 META 51.2 2013-Q3 ## 4 META 58.0 2013-Q4 ## 5 META 72.0 2014-Q1 ## 6 META 67.6 2014-Q2 ## 7 META 79.0 2014-Q3 ## 8 META 81.4 2014-Q4 ## 9 META 85.3 2015-Q1 ## 10 META 88.9 2015-Q2 ## # ℹ 54 more rows FANG_min_by_qtr <- FANG %>% group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = apply.quarterly, FUN = min, col_rename = \"min.close\") %>% mutate(year.qtr = paste0(year(date), \"-Q\", quarter(date))) %>% select(-date) FANG_by_qtr <- left_join(FANG_max_by_qtr, FANG_min_by_qtr, by = c(\"symbol\" = \"symbol\", \"year.qtr\" = \"year.qtr\")) FANG_by_qtr ## # A tibble: 64 × 4 ## # Groups: symbol [4] ## symbol max.close year.qtr min.close ## ## 1 META 32.5 2013-Q1 25.1 ## 2 META 29.0 2013-Q2 22.9 ## 3 META 51.2 2013-Q3 24.4 ## 4 META 58.0 2013-Q4 44.8 ## 5 META 72.0 2014-Q1 53.5 ## 6 META 67.6 2014-Q2 56.1 ## 7 META 79.0 2014-Q3 62.8 ## 8 META 81.4 2014-Q4 72.6 ## 9 META 85.3 2015-Q1 74.1 ## 10 META 88.9 2015-Q2 77.5 ## # ℹ 54 more rows FANG_by_qtr %>% ggplot(aes(x = year.qtr, color = symbol)) + geom_segment(aes(xend = year.qtr, y = min.close, yend = max.close), linewidth = 1) + geom_point(aes(y = max.close), size = 2) + geom_point(aes(y = min.close), size = 2) + facet_wrap(~ symbol, ncol = 2, scale = \"free_y\") + labs(title = \"FANG: 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())"},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"example-6-use-zoo-rollapply-to-visualize-a-rolling-regression","dir":"Articles","previous_headings":"2.0 Quantitative Power In Action","what":"Example 6: Use zoo rollapply to visualize a rolling regression","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"good way analyze relationships time using rolling calculations compare two assets. Pairs trading common mechanism similar assets. go pairs trade analysis, analyze relationship two similar assets precursor pairs trade. example analyze two similar assets, Mastercard (MA) Visa (V) show relationship via regression. analyze rolling regression, ’s helpful view overall trend returns. , use tq_get() get stock prices assets tq_transmute() transform daily prices daily returns. ’ll collect data visualize via scatter plot. can visualize relationship returns stock pairs like . can get statistcs relationship lm function. model highly correlated p-value essential zero. coefficient estimate V (Coefficient 1) 0.8134 indicating positive relationship, meaning V increases MA also tends increase. characterizes overall relationship, ’s missing time aspect. Fortunately, can use rollapply function zoo package plot rolling regression, showing model coefficent varies rolling basis time. calculate rolling regressions tq_mutate() two additional steps: Create custom function Apply function tq_mutate(mutate_fun = rollapply) First, create custom regression function. important point “data” passed regression function xts object. timetk::tk_tbl function takes care converting data frame. Now can use tq_mutate() apply custom regression function rolling window using rollapply zoo package. Internally, returns_combined data frame passed automatically data argument rollapply function. need specify mutate_fun = rollapply additional arguments necessary apply rollapply function. ’ll specify 90 day window via width = 90. FUN argument custom regression function, regr_fun. ’s extremely important specify .column = FALSE, tells rollapply perform computation using data whole rather apply function column independently. col_rename argument used rename added columns. Finally, can visualize first coefficient like . horizontal line added using full data set model. gives us insight points time relationship deviates significantly long run trend can explored potential pair trade opportunities. Stock returns time period.","code":"# Get stock pairs stock_prices <- c(\"MA\", \"V\") %>% tq_get(get = \"stock.prices\", from = \"2015-01-01\", to = \"2016-12-31\") %>% group_by(symbol) stock_pairs <- stock_prices %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"daily\", type = \"log\", col_rename = \"returns\") %>% spread(key = symbol, value = returns) stock_pairs %>% ggplot(aes(x = V, y = MA)) + geom_point(color = palette_light()[[1]], alpha = 0.5) + geom_smooth(method = \"lm\") + labs(title = \"Visualizing Returns Relationship of Stock Pairs\") + theme_tq() lm(MA ~ V, data = stock_pairs) %>% summary() ## ## Call: ## lm(formula = MA ~ V, data = stock_pairs) ## ## Residuals: ## Min 1Q Median 3Q Max ## -0.0269576 -0.0039656 0.0002149 0.0039652 0.0289463 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 0.0001130 0.0003097 0.365 0.715 ## V 0.8133658 0.0226394 35.927 <2e-16 *** ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ## ## Residual standard error: 0.00695 on 502 degrees of freedom ## Multiple R-squared: 0.72, Adjusted R-squared: 0.7194 ## F-statistic: 1291 on 1 and 502 DF, p-value: < 2.2e-16 regr_fun <- function(data) { coef(lm(MA ~ V, data = timetk::tk_tbl(data, silent = TRUE))) } stock_pairs <- stock_pairs %>% tq_mutate(mutate_fun = rollapply, width = 90, FUN = regr_fun, by.column = FALSE, col_rename = c(\"coef.0\", \"coef.1\")) stock_pairs ## # A tibble: 504 × 5 ## date MA V coef.0 coef.1 ## ## 1 2015-01-02 0 0 NA NA ## 2 2015-01-05 -0.0285 -0.0223 NA NA ## 3 2015-01-06 -0.00216 -0.00646 NA NA ## 4 2015-01-07 0.0154 0.0133 NA NA ## 5 2015-01-08 0.0154 0.0133 NA NA ## 6 2015-01-09 -0.0128 -0.0149 NA NA ## 7 2015-01-12 -0.0129 -0.00196 NA NA ## 8 2015-01-13 0.00228 0.00292 NA NA ## 9 2015-01-14 -0.00108 -0.0202 NA NA ## 10 2015-01-15 -0.0146 -0.00955 NA NA ## # ℹ 494 more rows stock_pairs %>% ggplot(aes(x = date, y = coef.1)) + geom_line(linewidth = 1, color = palette_light()[[1]]) + geom_hline(yintercept = 0.8134, linewidth = 1, color = palette_light()[[2]]) + labs(title = \"MA ~ V: Visualizing Rolling Regression Coefficient\", x = \"\") + theme_tq() stock_prices %>% 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(linewidth = 1) + labs(title = \"MA and V: Stock Prices\") + theme_tq() + scale_color_tq()"},{"path":"/articles/TQ02-quant-integrations-in-tidyquant.html","id":"example-7-use-return-clean-and-return-excess-to-clean-and-calculate-excess-returns","dir":"Articles","previous_headings":"2.0 Quantitative Power In Action","what":"Example 7: Use Return.clean and Return.excess to clean and calculate excess returns","title":"R Quantitative Analysis Package Integrations in tidyquant","text":"example use several PerformanceAnalytics functions clean format returns. example uses three progressive applications tq_transmute apply various quant functions grouped stock prices FANG data set. First, calculate daily returns using quantmod::periodReturn. Next, use Return.clean clean outliers return data. alpha parameter percentage oultiers cleaned. Finally, excess returns calculated using risk-free rate 3% (divided 252 252 trade days one year).","code":"FANG %>% 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) ## # A tibble: 4,032 × 3 ## # Groups: symbol [4] ## symbol date `daily.returns > Rf` ## ## 1 META 2013-01-02 -0.000119 ## 2 META 2013-01-03 -0.00833 ## 3 META 2013-01-04 0.0355 ## 4 META 2013-01-07 0.0228 ## 5 META 2013-01-08 -0.0124 ## 6 META 2013-01-09 0.0525 ## 7 META 2013-01-10 0.0231 ## 8 META 2013-01-11 0.0133 ## 9 META 2013-01-14 -0.0244 ## 10 META 2013-01-15 -0.0276 ## # ℹ 4,022 more rows"},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"overview","dir":"Articles","previous_headings":"","what":"Overview","title":"Scaling and Modeling with tidyquant","text":"greatest benefit tidyquant ability apply data science workflow easily model scale financial analysis described R Data Science. Scaling process creating analysis one asset extending multiple groups. idea scaling incredibly useful financial analysts typically one wants compare many assets make informed decisions. Fortunately, tidyquant package integrates tidyverse making scaling super simple! tidyquant functions return data tibble (tidy data frame) format, allows interaction within tidyverse. means can: Seamlessly scale data retrieval mutations Use pipe (%>%) chaining operations Use dplyr tidyr: select, filter, group_by, nest/unnest, spread/gather, etc Use purrr: mapping functions map Model financial analysis using data science workflow R Data Science ’ll go useful techniques getting manipulating groups data.","code":""},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"prerequisites","dir":"Articles","previous_headings":"","what":"Prerequisites","title":"Scaling and Modeling with tidyquant","text":"Load tidyquant package get started.","code":"# Loads tidyquant, lubridate, xts, quantmod, TTR, and PerformanceAnalytics library(lubridate) library(dplyr) library(purrr) library(ggplot2) library(tidyr) library(tidyquant)"},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"scaling-the-getting-of-financial-data","dir":"Articles","previous_headings":"","what":"1.0 Scaling the Getting of Financial Data","title":"Scaling and Modeling with tidyquant","text":"basic example retrieving stock prices multiple stocks. three primary ways :","code":""},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"method-1-map-a-character-vector-with-multiple-stock-symbols","dir":"Articles","previous_headings":"1.0 Scaling the Getting of Financial Data","what":"Method 1: Map a character vector with multiple stock symbols","title":"Scaling and Modeling with tidyquant","text":"output single level tibble stock prices one tibble. auto-generated column name “symbol”, can pre-emptively renamed giving vector name (e.g. stocks <- c(\"AAPL\", \"GOOG\", \"META\")) piping tq_get.","code":"c(\"AAPL\", \"GOOG\", \"META\") %>% tq_get(get = \"stock.prices\", from = \"2016-01-01\", to = \"2017-01-01\") ## # A tibble: 756 × 8 ## symbol date open high low close volume adjusted ## ## 1 AAPL 2016-01-04 25.7 26.3 25.5 26.3 270597600 24.0 ## 2 AAPL 2016-01-05 26.4 26.5 25.6 25.7 223164000 23.4 ## 3 AAPL 2016-01-06 25.1 25.6 25.0 25.2 273829600 22.9 ## 4 AAPL 2016-01-07 24.7 25.0 24.1 24.1 324377600 22.0 ## 5 AAPL 2016-01-08 24.6 24.8 24.2 24.2 283192000 22.1 ## 6 AAPL 2016-01-11 24.7 24.8 24.3 24.6 198957600 22.5 ## 7 AAPL 2016-01-12 25.1 25.2 24.7 25.0 196616800 22.8 ## 8 AAPL 2016-01-13 25.1 25.3 24.3 24.3 249758400 22.2 ## 9 AAPL 2016-01-14 24.5 25.1 23.9 24.9 252680400 22.7 ## 10 AAPL 2016-01-15 24.0 24.4 23.8 24.3 319335600 22.1 ## # ℹ 746 more rows"},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"method-2-map-a-tibble-with-stocks-in-first-column","dir":"Articles","previous_headings":"1.0 Scaling the Getting of Financial Data","what":"Method 2: Map a tibble with stocks in first column","title":"Scaling and Modeling with tidyquant","text":"First, get stock list data frame format either making tibble retrieving tq_index / tq_exchange. stock symbols must first column.","code":""},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"method-2a-make-a-tibble","dir":"Articles","previous_headings":"1.0 Scaling the Getting of Financial Data > Method 2: Map a tibble with stocks in first column","what":"Method 2A: Make a tibble","title":"Scaling and Modeling with tidyquant","text":"Second, send stock list tq_get. Notice symbol industry columns automatically expanded length stock prices.","code":"stock_list <- tibble(stocks = c(\"AAPL\", \"JPM\", \"CVX\"), industry = c(\"Technology\", \"Financial\", \"Energy\")) stock_list ## # A tibble: 3 × 2 ## stocks industry ## ## 1 AAPL Technology ## 2 JPM Financial ## 3 CVX Energy stock_list %>% tq_get(get = \"stock.prices\", from = \"2016-01-01\", to = \"2017-01-01\") ## # A tibble: 756 × 9 ## stocks industry date open high low close volume adjusted ## ## 1 AAPL Technology 2016-01-04 25.7 26.3 25.5 26.3 270597600 24.0 ## 2 AAPL Technology 2016-01-05 26.4 26.5 25.6 25.7 223164000 23.4 ## 3 AAPL Technology 2016-01-06 25.1 25.6 25.0 25.2 273829600 22.9 ## 4 AAPL Technology 2016-01-07 24.7 25.0 24.1 24.1 324377600 22.0 ## 5 AAPL Technology 2016-01-08 24.6 24.8 24.2 24.2 283192000 22.1 ## 6 AAPL Technology 2016-01-11 24.7 24.8 24.3 24.6 198957600 22.5 ## 7 AAPL Technology 2016-01-12 25.1 25.2 24.7 25.0 196616800 22.8 ## 8 AAPL Technology 2016-01-13 25.1 25.3 24.3 24.3 249758400 22.2 ## 9 AAPL Technology 2016-01-14 24.5 25.1 23.9 24.9 252680400 22.7 ## 10 AAPL Technology 2016-01-15 24.0 24.4 23.8 24.3 319335600 22.1 ## # ℹ 746 more rows"},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"method-2b-use-index-or-exchange","dir":"Articles","previous_headings":"1.0 Scaling the Getting of Financial Data > Method 2: Map a tibble with stocks in first column","what":"Method 2B: Use index or exchange","title":"Scaling and Modeling with tidyquant","text":"Get index… …, get exchange. Send index exchange tq_get. Important Note: can take several minutes depending size index exchange, first three stocks evaluated vignette. can use applicable “getter” get data every stock index exchange! includes: “stock.prices”, “key.ratios”, “key.stats”, .","code":"tq_index(\"DOW\") ## # A tibble: 31 × 8 ## symbol company identifier sedol weight sector shares_held local_currency ## ## 1 UNH UNITEDHEALT… 91324P102 2917… 0.0996 - 5477820 USD ## 2 GS GOLDMAN SAC… 38141G104 2407… 0.0635 - 5477820 USD ## 3 MSFT MICROSOFT C… 594918104 2588… 0.0612 - 5477820 USD ## 4 HD HOME DEPOT … 437076102 2434… 0.0592 - 5477820 USD ## 5 CAT CATERPILLAR… 149123101 2180… 0.0539 - 5477820 USD ## 6 AMGN AMGEN INC 031162100 2023… 0.0529 - 5477820 USD ## 7 MCD MCDONALD S … 580135101 2550… 0.0518 - 5477820 USD ## 8 V VISA INC CL… 92826C839 B2PZ… 0.0452 - 5477820 USD ## 9 CRM SALESFORCE … 79466L302 2310… 0.0397 - 5477820 USD ## 10 BA BOEING CO/T… 097023105 2108… 0.0372 - 5477820 USD ## # ℹ 21 more rows tq_exchange(\"NYSE\") tq_index(\"DOW\") %>% slice(1:3) %>% tq_get(get = \"stock.prices\") ## # A tibble: 8,115 × 15 ## symbol company identifier sedol weight sector shares_held local_currency ## ## 1 UNH UNITEDHEALT… 91324P102 2917… 0.0996 - 5477820 USD ## 2 UNH UNITEDHEALT… 91324P102 2917… 0.0996 - 5477820 USD ## 3 UNH UNITEDHEALT… 91324P102 2917… 0.0996 - 5477820 USD ## 4 UNH UNITEDHEALT… 91324P102 2917… 0.0996 - 5477820 USD ## 5 UNH UNITEDHEALT… 91324P102 2917… 0.0996 - 5477820 USD ## 6 UNH UNITEDHEALT… 91324P102 2917… 0.0996 - 5477820 USD ## 7 UNH UNITEDHEALT… 91324P102 2917… 0.0996 - 5477820 USD ## 8 UNH UNITEDHEALT… 91324P102 2917… 0.0996 - 5477820 USD ## 9 UNH UNITEDHEALT… 91324P102 2917… 0.0996 - 5477820 USD ## 10 UNH UNITEDHEALT… 91324P102 2917… 0.0996 - 5477820 USD ## # ℹ 8,105 more rows ## # ℹ 7 more variables: date , open , high , low , ## # close , volume , adjusted "},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"scaling-the-mutation-of-financial-data","dir":"Articles","previous_headings":"","what":"2.0 Scaling the Mutation of Financial Data","title":"Scaling and Modeling with tidyquant","text":"get data, typically want something . can easily scale. Let’s get yearly returns multiple stocks using tq_transmute. First, get prices. ’ll use FANG data set, typically use tq_get retrieve data “tibble” format. Second, use group_by group stock symbol. Third, apply mutation. can one easy workflow. periodReturn function applied group stock prices, new data frame returned annual returns correct periodicity. Last, can visualize returns.","code":"FANG ## # A tibble: 4,032 × 8 ## symbol date open high low close volume adjusted ## ## 1 META 2013-01-02 27.4 28.2 27.4 28 69846400 28 ## 2 META 2013-01-03 27.9 28.5 27.6 27.8 63140600 27.8 ## 3 META 2013-01-04 28.0 28.9 27.8 28.8 72715400 28.8 ## 4 META 2013-01-07 28.7 29.8 28.6 29.4 83781800 29.4 ## 5 META 2013-01-08 29.5 29.6 28.9 29.1 45871300 29.1 ## 6 META 2013-01-09 29.7 30.6 29.5 30.6 104787700 30.6 ## 7 META 2013-01-10 30.6 31.5 30.3 31.3 95316400 31.3 ## 8 META 2013-01-11 31.3 32.0 31.1 31.7 89598000 31.7 ## 9 META 2013-01-14 32.1 32.2 30.6 31.0 98892800 31.0 ## 10 META 2013-01-15 30.6 31.7 29.9 30.1 173242600 30.1 ## # ℹ 4,022 more rows FANG_returns_yearly <- FANG %>% group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"yearly\", col_rename = \"yearly.returns\") FANG_returns_yearly %>% ggplot(aes(x = year(date), y = yearly.returns, fill = symbol)) + geom_bar(position = \"dodge\", stat = \"identity\") + labs(title = \"FANG: Annual Returns\", subtitle = \"Mutating at scale is quick and easy!\", y = \"Returns\", x = \"\", color = \"\") + scale_y_continuous(labels = scales::percent) + coord_flip() + theme_tq() + scale_fill_tq()"},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"modeling-financial-data-using-purrr","dir":"Articles","previous_headings":"","what":"3.0 Modeling Financial Data using purrr","title":"Scaling and Modeling with tidyquant","text":"Eventually want begin modeling (generally applying functions) scale! One best features tidyverse ability map functions nested tibbles using purrr. Many Models chapter “R Data Science”, can apply modeling workflow financial analysis. Using two step workflow: Model single stock Scale many stocks Let’s go example illustrate.","code":""},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"example-applying-a-regression-model-to-detect-a-positive-trend","dir":"Articles","previous_headings":"3.0 Modeling Financial Data using purrr","what":"Example: Applying a Regression Model to Detect a Positive Trend","title":"Scaling and Modeling with tidyquant","text":"example, ’ll use simple linear model identify trend annual returns determine stock returns decreasing increasing time.","code":""},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"analyze-a-single-stock","dir":"Articles","previous_headings":"3.0 Modeling Financial Data using purrr > Example: Applying a Regression Model to Detect a Positive Trend","what":"Analyze a Single Stock","title":"Scaling and Modeling with tidyquant","text":"First, let’s collect stock data tq_get() Next, come function help us collect annual log returns. function mutates stock prices period returns using tq_transmute(). add type = \"log\" period = \"monthly\" arguments ensure retrieve tibble monthly log returns. Last, take mean monthly returns get MMLR. Let’s test get_annual_returns . now annual log returns past ten years. Let’s visualize identify trends. can see linear trend line AAPL’s stock returns declining. Now, can get linear model using lm() function. However, one problem: output “tidy”. can utilize broom package get “tidy” data model. ’s three primary functions: augment: adds columns original data predictions, residuals cluster assignments glance: provides one-row summary model-level statistics tidy: summarizes model’s statistical findings coefficients regression ’ll use tidy retrieve model coefficients. Adding workflow, following: Testing single stock. can see “term” contains direction trend (slope) “year(date)”. interpetation year increases one unit, annual returns decrease 3%. Now identified trend direction, looks like ready scale.","code":"AAPL <- tq_get(\"AAPL\", from = \"2007-01-01\", to = \"2016-12-31\") AAPL ## # A tibble: 2,518 × 8 ## symbol date open high low close volume adjusted ## ## 1 AAPL 2007-01-03 3.08 3.09 2.92 2.99 1238319600 2.54 ## 2 AAPL 2007-01-04 3.00 3.07 2.99 3.06 847260400 2.60 ## 3 AAPL 2007-01-05 3.06 3.08 3.01 3.04 834741600 2.58 ## 4 AAPL 2007-01-08 3.07 3.09 3.05 3.05 797106800 2.59 ## 5 AAPL 2007-01-09 3.09 3.32 3.04 3.31 3349298400 2.81 ## 6 AAPL 2007-01-10 3.38 3.49 3.34 3.46 2952880000 2.94 ## 7 AAPL 2007-01-11 3.43 3.46 3.40 3.42 1440252800 2.90 ## 8 AAPL 2007-01-12 3.38 3.39 3.33 3.38 1312690400 2.87 ## 9 AAPL 2007-01-16 3.42 3.47 3.41 3.47 1244076400 2.94 ## 10 AAPL 2007-01-17 3.48 3.49 3.39 3.39 1646260000 2.88 ## # ℹ 2,508 more rows get_annual_returns <- function(stock.returns) { stock.returns %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, type = \"log\", period = \"yearly\") } AAPL_annual_log_returns <- get_annual_returns(AAPL) AAPL_annual_log_returns ## # A tibble: 10 × 2 ## date yearly.returns ## ## 1 2007-12-31 0.860 ## 2 2008-12-31 -0.842 ## 3 2009-12-31 0.904 ## 4 2010-12-31 0.426 ## 5 2011-12-30 0.228 ## 6 2012-12-31 0.282 ## 7 2013-12-31 0.0776 ## 8 2014-12-31 0.341 ## 9 2015-12-31 -0.0306 ## 10 2016-12-30 0.118 AAPL_annual_log_returns %>% ggplot(aes(x = year(date), y = yearly.returns)) + geom_hline(yintercept = 0, color = palette_light()[[1]]) + geom_point(size = 2, color = palette_light()[[3]]) + geom_line(linewidth = 1, color = palette_light()[[3]]) + geom_smooth(method = \"lm\", se = FALSE) + labs(title = \"AAPL: Visualizing Trends in Annual Returns\", x = \"\", y = \"Annual Returns\", color = \"\") + theme_tq() mod <- lm(yearly.returns ~ year(date), data = AAPL_annual_log_returns) mod ## ## Call: ## lm(formula = yearly.returns ~ year(date), data = AAPL_annual_log_returns) ## ## Coefficients: ## (Intercept) year(date) ## 58.86280 -0.02915 library(broom) tidy(mod) ## # A tibble: 2 × 5 ## term estimate std.error statistic p.value ## ## 1 (Intercept) 58.9 113. 0.520 0.617 ## 2 year(date) -0.0291 0.0562 -0.518 0.618 get_model <- function(stock_data) { annual_returns <- get_annual_returns(stock_data) mod <- lm(yearly.returns ~ year(date), data = annual_returns) tidy(mod) } get_model(AAPL) ## # A tibble: 2 × 5 ## term estimate std.error statistic p.value ## ## 1 (Intercept) 58.9 113. 0.520 0.617 ## 2 year(date) -0.0291 0.0562 -0.518 0.618"},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"scale-to-many-stocks","dir":"Articles","previous_headings":"3.0 Modeling Financial Data using purrr > Example: Applying a Regression Model to Detect a Positive Trend","what":"Scale to Many Stocks","title":"Scaling and Modeling with tidyquant","text":"analysis one stock done scale many stocks simple. brevity, ’ll randomly sample ten stocks S&P500 call dplyr::sample_n(). can now apply analysis function stocks using dplyr::mutate purrr::map. mutate() function adds column tibble, map() function maps custom get_model function tibble stocks using symbol column. tidyr::unnest function unrolls nested data frame model statistics accessable top data frame level. filter, arrange select steps just manipulate data frame isolate arrange data viewing. ’re done! now coefficient linear regression tracks direction trend line. can easily extend type analysis larger lists stock indexes. example, entire S&P500 analyzed removing sample_n() following call tq_index(\"SP500\").","code":"set.seed(10) stocks_tbl <- tq_index(\"SP500\") %>% sample_n(5) stocks_tbl ## # A tibble: 5 × 8 ## symbol company identifier sedol weight sector shares_held local_currency ## ## 1 TPR TAPESTRY INC 876030107 BF09… 1.81e-4 - 2586531 USD ## 2 FCX FREEPORT MC… 35671D857 2352… 1.48e-3 - 15983335 USD ## 3 HWM HOWMET AERO… 443201108 BKLJ… 5.04e-4 - 4369675 USD ## 4 ATO ATMOS ENERG… 049560105 2315… 4.35e-4 - 1656490 USD ## 5 EMN EASTMAN CHE… 277432100 2298… 2.55e-4 - 1338851 USD stocks_model_stats <- stocks_tbl %>% select(symbol, company) %>% tq_get(from = \"2007-01-01\", to = \"2016-12-31\") %>% # Nest group_by(symbol, company) %>% nest() %>% # Apply the get_model() function to the new \"nested\" data column mutate(model = map(data, get_model)) %>% # Unnest and collect slope unnest(model) %>% filter(term == \"year(date)\") %>% arrange(desc(estimate)) %>% select(-term) stocks_model_stats ## # A tibble: 5 × 7 ## # Groups: symbol, company [5] ## symbol company data estimate std.error statistic p.value ## ## 1 ATO ATMOS ENERGY CORP 0.0291 0.0126 2.32 0.0490 ## 2 EMN EASTMAN CHEMICAL CO 0.00566 0.0435 0.130 0.900 ## 3 TPR TAPESTRY INC 0.000725 0.0382 0.0190 0.985 ## 4 FCX FREEPORT MCMORAN INC -0.0460 0.0974 -0.472 0.649 ## 5 HWM HOWMET AEROSPACE INC NA NA NA NA"},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"error-handling-when-scaling","dir":"Articles","previous_headings":"","what":"4.0 Error Handling when Scaling","title":"Scaling and Modeling with tidyquant","text":"Eventually run stock index, stock symbol, FRED data code, etc retrieved. Possible reasons : index becomes date company goes private stock ticker symbol changes Yahoo / FRED just doesn’t like stock symbol / FRED code becomes painful scaling functions return errors. , tq_get() function designed handle errors gracefully. means NA value returned error generated along gentle error warning.","code":"tq_get(\"XYZ\", \"stock.prices\") ## [1] NA"},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"pros-and-cons-to-built-in-error-handling","dir":"Articles","previous_headings":"4.0 Error Handling when Scaling","what":"Pros and Cons to Built-In Error-Handling","title":"Scaling and Modeling with tidyquant","text":"pros cons approach may agree , believe helps long run. Just aware happens: Pros: Long running scripts interrupted one error Cons: Errors can inadvertently handled flow downstream users read warnings","code":""},{"path":"/articles/TQ03-scaling-and-modeling-with-tidyquant.html","id":"bad-apples-fail-gracefully-tq_get","dir":"Articles","previous_headings":"4.0 Error Handling when Scaling","what":"Bad Apples Fail Gracefully, tq_get","title":"Scaling and Modeling with tidyquant","text":"Let’s see example using tq_get() get stock prices long list stocks one BAD APPLE. argument complete_cases comes handy. default TRUE, removes “bad apples” future analysis complete cases compute . Note gentle warning stating error occurred dealt removing rows results. Now switching complete_cases = FALSE retain errors NA values nested data frame. Notice error message output change. error message now states NA values exist output return “nested” data structure. cases, prudent user review warnings determine happened whether acceptable. complete_cases = FALSE example, user attempts perform downstream computations scale, computations likely fail grinding analysis hault. , advantage user easily able filter problem childs determine happened decide whether acceptable .","code":"c(\"AAPL\", \"GOOG\", \"BAD APPLE\") %>% tq_get(get = \"stock.prices\", complete_cases = TRUE) ## Warning: There was 1 warning in `dplyr::mutate()`. ## ℹ In argument: `data.. = purrr::map(...)`. ## Caused by warning: ## ! x = 'BAD APPLE', get = 'stock.prices': Error in getSymbols.yahoo(Symbols = \"BAD APPLE\", env = , : Unable to import \"BAD APPLE\". ## URL using bad/illegal format or missing URL ## Removing BAD APPLE. ## # A tibble: 5,410 × 8 ## symbol date open high low close volume adjusted ## ## 1 AAPL 2013-01-02 19.8 19.8 19.3 19.6 560518000 16.8 ## 2 AAPL 2013-01-03 19.6 19.6 19.3 19.4 352965200 16.6 ## 3 AAPL 2013-01-04 19.2 19.2 18.8 18.8 594333600 16.1 ## 4 AAPL 2013-01-07 18.6 18.9 18.4 18.7 484156400 16.0 ## 5 AAPL 2013-01-08 18.9 19.0 18.6 18.8 458707200 16.1 ## 6 AAPL 2013-01-09 18.7 18.8 18.4 18.5 407604400 15.8 ## 7 AAPL 2013-01-10 18.9 18.9 18.4 18.7 601146000 16.0 ## 8 AAPL 2013-01-11 18.6 18.8 18.5 18.6 350506800 15.9 ## 9 AAPL 2013-01-14 18.0 18.1 17.8 17.9 734207600 15.3 ## 10 AAPL 2013-01-15 17.8 17.8 17.3 17.4 876772400 14.9 ## # ℹ 5,400 more rows c(\"AAPL\", \"GOOG\", \"BAD APPLE\") %>% tq_get(get = \"stock.prices\", complete_cases = FALSE) ## Warning: There was 1 warning in `dplyr::mutate()`. ## ℹ In argument: `data.. = purrr::map(...)`. ## Caused by warning: ## ! x = 'BAD APPLE', get = 'stock.prices': Error in getSymbols.yahoo(Symbols = \"BAD APPLE\", env = , : Unable to import \"BAD APPLE\". ## URL using bad/illegal format or missing URL ## # A tibble: 5,411 × 8 ## symbol date open high low close volume adjusted ## ## 1 AAPL 2013-01-02 19.8 19.8 19.3 19.6 560518000 16.8 ## 2 AAPL 2013-01-03 19.6 19.6 19.3 19.4 352965200 16.6 ## 3 AAPL 2013-01-04 19.2 19.2 18.8 18.8 594333600 16.1 ## 4 AAPL 2013-01-07 18.6 18.9 18.4 18.7 484156400 16.0 ## 5 AAPL 2013-01-08 18.9 19.0 18.6 18.8 458707200 16.1 ## 6 AAPL 2013-01-09 18.7 18.8 18.4 18.5 407604400 15.8 ## 7 AAPL 2013-01-10 18.9 18.9 18.4 18.7 601146000 16.0 ## 8 AAPL 2013-01-11 18.6 18.8 18.5 18.6 350506800 15.9 ## 9 AAPL 2013-01-14 18.0 18.1 17.8 17.9 734207600 15.3 ## 10 AAPL 2013-01-15 17.8 17.8 17.3 17.4 876772400 14.9 ## # ℹ 5,401 more rows"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"overview","dir":"Articles","previous_headings":"","what":"Overview","title":"Charting with tidyquant","text":"tidyquant package includes charting tools assist users developing quick visualizations ggplot2 using grammar graphics format workflow. currently three primary geometry (geom) categories one coordinate manipulation (coord) category within tidyquant: Chart Types: Two chart type visualizations available using geom_barchart geom_candlestick. Moving Averages: Seven moving average visualizations available using geom_ma. Bollinger Bands: Bollinger bands can visualized using geom_bbands. BBand moving average can one seven available Moving Averages. Zooming Date Ranges: Two coord functions available (coord_x_date coord_x_datetime), prevent data loss zooming specific regions chart. important using moving average Bollinger band geoms.","code":""},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"prerequisites","dir":"Articles","previous_headings":"","what":"Prerequisites","title":"Charting with tidyquant","text":"Load tidyquant package get started. following stock data used examples. Use tq_get get stock prices. end date parameter used setting date limits throughout examples. AAPL_range_60 used adjust zoom plots.","code":"# Loads tidyquant, lubridate, xts, quantmod, TTR, and PerformanceAnalytics library(lubridate) library(dplyr) library(ggplot2) library(tidyquant) # Use FANG data set # Get AAPL and AMZN Stock Prices AAPL <- tq_get(\"AAPL\", get = \"stock.prices\", from = \"2015-09-01\", to = \"2016-12-31\") AMZN <- tq_get(\"AMZN\", get = \"stock.prices\", from = \"2000-01-01\", to = \"2016-12-31\") end <- as_date(\"2016-12-31\") end ## [1] \"2016-12-31\" aapl_range_60_tbl <- AAPL %>% tail(60) %>% summarise( max_high = max(high), min_low = min(low) ) aapl_range_60_tbl ## # A tibble: 1 × 2 ## max_high min_low ## ## 1 29.7 26.0"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"chart-types","dir":"Articles","previous_headings":"","what":"Chart Types","title":"Charting with tidyquant","text":"Financial charts provide visual cues open, high, low, close prices. following chart geoms available: Bar Chart: Use geom_barchart Candlestick Chart: Use geom_candlestick","code":""},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"line-chart","dir":"Articles","previous_headings":"Chart Types","what":"Line Chart","title":"Charting with tidyquant","text":"visualize bar charts candlestick charts using tidyquant geoms, let’s visualize stock prices simple line chart get sense “grammar graphics” workflow. done using geom_line ggplot2 package. workflow begins stock data, uses pipe operator (%>%) send ggplot() function. primary features controlling chart aesthetic arguments: used add data chart way aes() function. added inside ggplot() function, aesthetic arguments available underlying layers. Alternatively, aesthetic arguments can applied geom individually, typically minimized practice duplicates code. set aesthetic arguments, x = date y = close, chart closing price versus date. geom_line() function inherits aesthetic arguments ggplot() function produces line chart. Labels added separately using labs() function. Thus, chart built ground starting data progressively adding geoms, labels, coordinates / scales attributes create final chart. enables maximum flexibility wherein analyst can create complex charts using “grammar graphics”.","code":"AAPL %>% ggplot(aes(x = date, y = close)) + geom_line() + labs(title = \"AAPL Line Chart\", y = \"Closing Price\", x = \"\") + theme_tq()"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"bar-chart","dir":"Articles","previous_headings":"Chart Types","what":"Bar Chart","title":"Charting with tidyquant","text":"Visualizing bar chart simple replacing geom_line geom_barchart ggplot workflow. bar chart uses open, high, low, close prices visualization, need specify part aesthetic arguments, aes(). can internal geom ggplot() function. zoom specific sections using coord_x_date, xlim ylim arguments specified c(start, end) focus specific region chart. xlim, ’ll use lubridate convert character date date class, subtract six weeks using weeks() function. ylim zoom prices range 100 120. colors can modified using colour_up colour_down arguments, parameters size can used control appearance.","code":"AAPL %>% ggplot(aes(x = date, y = close)) + geom_barchart(aes(open = open, high = high, low = low, close = close)) + labs(title = \"AAPL Bar Chart\", y = \"Closing Price\", x = \"\") + theme_tq() AAPL %>% ggplot(aes(x = date, y = close)) + geom_barchart(aes(open = open, high = high, low = low, close = close)) + labs(title = \"AAPL Bar Chart\", subtitle = \"Zoomed in using coord_x_date\", y = \"Closing Price\", x = \"\") + coord_x_date(xlim = c(end - weeks(6), end), ylim = c(aapl_range_60_tbl$min_low, aapl_range_60_tbl$max_high)) + theme_tq() AAPL %>% ggplot(aes(x = date, y = close)) + geom_barchart(aes(open = open, high = high, low = low, close = close), colour_up = \"darkgreen\", colour_down = \"darkred\", size = 1) + labs(title = \"AAPL Bar Chart\", subtitle = \"Zoomed in, Experimenting with Formatting\", y = \"Closing Price\", x = \"\") + coord_x_date(xlim = c(end - lubridate::weeks(6), end), c(aapl_range_60_tbl$min_low, aapl_range_60_tbl$max_high)) + theme_tq()"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"candlestick-chart","dir":"Articles","previous_headings":"Chart Types","what":"Candlestick Chart","title":"Charting with tidyquant","text":"Creating candlestick chart similar process bar chart. Using geom_candlestick, can insert ggplot workflow. zoom specific sections using coord_x_date. colors can modified using colour_up colour_down, control line color, fill_up fill_down, control rectangle fills.","code":"AAPL %>% ggplot(aes(x = date, y = close)) + geom_candlestick(aes(open = open, high = high, low = low, close = close)) + labs(title = \"AAPL Candlestick Chart\", y = \"Closing Price\", x = \"\") + theme_tq() AAPL %>% ggplot(aes(x = date, y = close)) + geom_candlestick(aes(open = open, high = high, low = low, close = close)) + labs(title = \"AAPL Candlestick Chart\", subtitle = \"Zoomed in using coord_x_date\", y = \"Closing Price\", x = \"\") + coord_x_date(xlim = c(end - weeks(6), end), c(aapl_range_60_tbl$min_low, aapl_range_60_tbl$max_high)) + theme_tq() AAPL %>% ggplot(aes(x = date, y = close)) + geom_candlestick(aes(open = open, high = high, low = low, close = close), colour_up = \"darkgreen\", colour_down = \"darkred\", fill_up = \"darkgreen\", fill_down = \"darkred\") + labs(title = \"AAPL Candlestick Chart\", subtitle = \"Zoomed in, Experimenting with Formatting\", y = \"Closing Price\", x = \"\") + coord_x_date(xlim = c(end - weeks(6), end), c(aapl_range_60_tbl$min_low, aapl_range_60_tbl$max_high)) + theme_tq()"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"charting-multiple-securities","dir":"Articles","previous_headings":"Chart Types","what":"Charting Multiple Securities","title":"Charting with tidyquant","text":"can use facet_wrap visualize multiple stocks time. adding group aesthetic main ggplot() function combining facet_wrap() function end ggplot workflow, four “FANG” stocks can viewed simultaneously. may notice odd filter() call call ggplot(). ’ll discuss next. note --bounds data (“clipping”), particularly important faceting charting moving averages: coord_x_date coordinate function designed zoom specific sections chart without “clipping” data outside view. contrast scale_x_date, removes --bounds data charting. normal circumstances clipping big deal (actually helpful scaling y-axis), financial applications users want chart rolling/moving averages, lags, etc depend data outside view port. need --bounds data, trade-charting: much --bounds data distorts scale y-axis, little get moving average. optimal method include “just enough” --bounds data get chart want. FANG data filtered date double number moving-average days (2 * n) previous start date. yields nice y-axis scale still allows us create moving average line using geom_ma.","code":"start <- end - weeks(6) FANG %>% dplyr::filter(date >= start - days(2 * 15)) %>% ggplot(aes(x = date, y = close, group = symbol)) + geom_candlestick(aes(open = open, high = high, low = low, close = close)) + labs(title = \"FANG Candlestick Chart\", subtitle = \"Experimenting with Mulitple Stocks\", y = \"Closing Price\", x = \"\") + coord_x_date(xlim = c(start, end)) + facet_wrap(~ symbol, ncol = 2, scale = \"free_y\") + theme_tq() start <- end - weeks(6) FANG %>% dplyr::filter(date >= start - days(2 * 15)) %>% ggplot(aes(x = date, y = close, group = symbol)) + geom_candlestick(aes(open = open, high = high, low = low, close = close)) + geom_ma(ma_fun = SMA, n = 15, color = \"darkblue\", size = 1) + labs(title = \"FANG Candlestick Chart\", subtitle = \"Experimenting with Mulitple Stocks\", y = \"Closing Price\", x = \"\") + coord_x_date(xlim = c(start, end)) + facet_wrap(~ symbol, ncol = 2, scale = \"free_y\") + theme_tq()"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"visualizing-trends","dir":"Articles","previous_headings":"","what":"Visualizing Trends","title":"Charting with tidyquant","text":"Moving averages critical evaluating time-series trends. tidyquant includes geoms enable “rapid prototyping” quickly visualize signals using moving averages Bollinger bands.","code":""},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"moving-averages","dir":"Articles","previous_headings":"Visualizing Trends","what":"Moving Averages","title":"Charting with tidyquant","text":"following moving averages available: Simple moving averages (SMA) Exponential moving averages (EMA) Weighted moving averages (WMA) Double exponential moving averages (DEMA) Zero-lag exponential moving averages (ZLEMA) Volume-weighted moving averages (VWMA) (also known VWAP) Elastic, volume-weighted moving averages (EVWMA) (also known MVWAP) Moving averages applied added layer chart geom_ma function. geom wrapper underlying moving average functions TTR package: SMA, EMA, WMA, DEMA, ZLEMA, VWMA, EVWMA. ’s use geom: Select moving average function, ma_fun, want apply. Determine function arguments need passed ma_fun. can investigate underlying function searching ?TTR::SMA. Determine aesthetic arguments pass. typically aes(x = date, y = close). volume-weighted functions require volume argument aes() function. Apply moving average geom ggplot workflow. Important Note: zooming section, use coord_x_date coord_x_datetime prevent --bounds data loss. use scale_x_date, affect moving average calculation. Refer Charting Multiple Securities.","code":""},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"example-1-charting-the-50-day-and-200-day-simple-moving-average","dir":"Articles","previous_headings":"Visualizing Trends > Moving Averages","what":"Example 1: Charting the 50-day and 200-day simple moving average","title":"Charting with tidyquant","text":"want apply SMA, research TTR function see accepts, n, number periods average . see aesthetics required x, date, y, price. Since already main ggplot() function, don’t need add aesthetics geom. apply moving average geoms candlestick geom overlay moving averages top candlesticks. add two moving average calls, one 50-day 200-day. add color = \"red\" linetype = 5 distinguish 200-day 50-day.","code":"AAPL %>% ggplot(aes(x = date, y = close)) + geom_candlestick(aes(open = open, high = high, low = low, close = close)) + geom_ma(ma_fun = SMA, n = 50, linetype = 5, size = 1.25) + geom_ma(ma_fun = SMA, n = 200, color = \"red\", size = 1.25) + labs(title = \"AAPL Candlestick Chart\", subtitle = \"50 and 200-Day SMA\", y = \"Closing Price\", x = \"\") + coord_x_date(xlim = c(end - weeks(24), end), c(aapl_range_60_tbl$min_low * 0.9, aapl_range_60_tbl$max_high)) + theme_tq()"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"example-2-charting-exponential-moving-averages","dir":"Articles","previous_headings":"Visualizing Trends > Moving Averages","what":"Example 2: Charting exponential moving averages","title":"Charting with tidyquant","text":"want EMA, research TTR function see accepts, n, number periods average , wilder Boolean, ratio arguments. use wilder = TRUE go default ratio arg. see aesthetics required x, date, y, price. Since already main ggplot() function, don’t need modify geom. ready apply bar chart geom.","code":"AAPL %>% ggplot(aes(x = date, y = close)) + geom_barchart(aes(open = open, high = high, low = low, close = close)) + geom_ma(ma_fun = EMA, n = 50, wilder = TRUE, linetype = 5, size = 1.25) + geom_ma(ma_fun = EMA, n = 200, wilder = TRUE, color = \"red\", size = 1.25) + labs(title = \"AAPL Bar Chart\", subtitle = \"50 and 200-Day EMA\", y = \"Closing Price\", x = \"\") + coord_x_date(xlim = c(end - weeks(24), end), c(aapl_range_60_tbl$min_low * 0.9, aapl_range_60_tbl$max_high)) + theme_tq()"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"example-3-charting-moving-averages-for-multiple-stocks-at-once","dir":"Articles","previous_headings":"Visualizing Trends > Moving Averages","what":"Example 3: Charting moving averages for multiple stocks at once","title":"Charting with tidyquant","text":"’ll double using volume-weighted average (VWMA) apply FANG stocks . Since VWMA volume-weighted function, need add volume aesthetic. viewing multiple stocks, add group aesthetic setting symbol column contains FANG stock symbols. facet wrap added end create four charts instead one overlayed chart.","code":"start <- end - weeks(6) FANG %>% dplyr::filter(date >= start - days(2 * 50)) %>% ggplot(aes(x = date, y = close, volume = volume, group = symbol)) + geom_candlestick(aes(open = open, high = high, low = low, close = close)) + geom_ma(ma_fun = VWMA, n = 15, wilder = TRUE, linetype = 5) + geom_ma(ma_fun = VWMA, n = 50, wilder = TRUE, color = \"red\") + labs(title = \"FANG Bar Chart\", subtitle = \"50 and 200-Day EMA, Experimenting with Multiple Stocks\", y = \"Closing Price\", x = \"\") + coord_x_date(xlim = c(start, end)) + facet_wrap(~ symbol, ncol = 2, scales = \"free_y\") + theme_tq()"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"bollinger-bands","dir":"Articles","previous_headings":"Visualizing Trends","what":"Bollinger Bands","title":"Charting with tidyquant","text":"Bollinger Bands used visualize volatility plotting range around moving average typically two standard deviations . use moving average, geom_bbands function works almost identically geom_ma. seven moving averages compatible. main difference addition standard deviation, sd, argument 2 default, high, low close aesthetics required calculate bands. Refer Moving Averages detailed discussion moving averages available. Important Note: zooming section, use coord_x_date coord_x_datetime prevent --bounds data loss. use scale_x_date, affect moving average calculation. Refer Charting Multiple Securities.","code":""},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"example-1-applying-bbands-using-a-sma","dir":"Articles","previous_headings":"Visualizing Trends > Bollinger Bands","what":"Example 1: Applying BBands using a SMA","title":"Charting with tidyquant","text":"Let’s basic example add Bollinger Bands using simple moving average. candlestick geom BBands geom use high, low close prices, move aesthetics main ggplot() function avoid duplication. add BBands candlestick geom overlay BBands top.","code":"AAPL %>% ggplot(aes(x = date, y = close, open = open, high = high, low = low, close = close)) + geom_candlestick() + geom_bbands(ma_fun = SMA, sd = 2, n = 20) + labs(title = \"AAPL Candlestick Chart\", subtitle = \"BBands with SMA Applied\", y = \"Closing Price\", x = \"\") + coord_x_date(xlim = c(end - weeks(24), end), ylim = c(aapl_range_60_tbl$min_low * 0.85, aapl_range_60_tbl$max_high) * 1.05) + theme_tq()"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"example-2-modifying-the-appearance-of-bollinger-bands","dir":"Articles","previous_headings":"Visualizing Trends > Bollinger Bands","what":"Example 2: Modifying the appearance of Bollinger Bands","title":"Charting with tidyquant","text":"appearance can modified using color_ma, color_bands, alpha, fill arguments. ’s plot Example 1, new formatting applied BBands.","code":"AAPL %>% ggplot(aes(x = date, y = close, open = open, high = high, low = low, close = close)) + geom_candlestick() + geom_bbands(ma_fun = SMA, sd = 2, n = 20, linetype = 4, size = 1, alpha = 0.2, fill = palette_light()[[1]], color_bands = palette_light()[[1]], color_ma = palette_light()[[2]]) + labs(title = \"AAPL Candlestick Chart\", subtitle = \"BBands with SMA Applied, Experimenting with Formatting\", y = \"Closing Price\", x = \"\") + coord_x_date(xlim = c(end - weeks(24), end), ylim = c(aapl_range_60_tbl$min_low * 0.85, aapl_range_60_tbl$max_high) * 1.05) + theme_tq()"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"example-3-adding-bbands-to-multiple-stocks","dir":"Articles","previous_headings":"Visualizing Trends > Bollinger Bands","what":"Example 3: Adding BBands to multiple stocks","title":"Charting with tidyquant","text":"process similar charting moving averages multiple stocks.","code":"start <- end - weeks(24) FANG %>% dplyr::filter(date >= start - days(2 * 20)) %>% ggplot(aes(x = date, y = close, open = open, high = high, low = low, close = close, group = symbol)) + geom_barchart() + geom_bbands(ma_fun = SMA, sd = 2, n = 20, linetype = 5) + labs(title = \"FANG Bar Chart\", subtitle = \"BBands with SMA Applied, Experimenting with Multiple Stocks\", y = \"Closing Price\", x = \"\") + coord_x_date(xlim = c(start, end)) + facet_wrap(~ symbol, ncol = 2, scales = \"free_y\") + theme_tq()"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"ggplot2-functionality","dir":"Articles","previous_headings":"","what":"ggplot2 Functionality","title":"Charting with tidyquant","text":"Base ggplot2 ton functionality can useful analyzing financial data. ’ll go brief examples using Amazon (AMZN).","code":""},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"example-1-log-scale-with-scale_y_log10","dir":"Articles","previous_headings":"ggplot2 Functionality","what":"Example 1: Log Scale with scale_y_log10","title":"Charting with tidyquant","text":"ggplot2 scale_y_log10() function scale y-axis logarithmic scale. extremely helpful tends expose linear trends can analyzed. Continuous Scale: Log Scale:","code":"AMZN %>% ggplot(aes(x = date, y = adjusted)) + geom_line(color = palette_light()[[1]]) + scale_y_continuous() + labs(title = \"AMZN Line Chart\", subtitle = \"Continuous Scale\", y = \"Closing Price\", x = \"\") + theme_tq() AMZN %>% ggplot(aes(x = date, y = adjusted)) + geom_line(color = palette_light()[[1]]) + scale_y_log10() + labs(title = \"AMZN Line Chart\", subtitle = \"Log Scale\", y = \"Closing Price\", x = \"\") + theme_tq()"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"example-2-regression-trendlines-with-geom_smooth","dir":"Articles","previous_headings":"ggplot2 Functionality","what":"Example 2: Regression trendlines with geom_smooth","title":"Charting with tidyquant","text":"can apply trend line quickly adding geom_smooth() function workflow. function several prediction methods including linear (\"lm\") loess (\"loess\") name . Linear:","code":"AMZN %>% ggplot(aes(x = date, y = adjusted)) + geom_line(color = palette_light()[[1]]) + scale_y_log10() + geom_smooth(method = \"lm\") + labs(title = \"AMZN Line Chart\", subtitle = \"Log Scale, Applying Linear Trendline\", y = \"Adjusted Closing Price\", x = \"\") + theme_tq()"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"example-3-charting-volume-with-geom_segment","dir":"Articles","previous_headings":"ggplot2 Functionality","what":"Example 3: Charting volume with geom_segment","title":"Charting with tidyquant","text":"can use geom_segment() function chart daily volume, uses xy points beginning end line. Using aesthetic color argument, color based value volume make data stick . , can zoom specific region. Using scale_color_gradient can quickly visualize high low points, using geom_smooth can see trend.","code":"AMZN %>% ggplot(aes(x = date, y = volume)) + geom_segment(aes(xend = date, yend = 0, color = volume)) + geom_smooth(method = \"loess\", se = FALSE) + labs(title = \"AMZN Volume Chart\", subtitle = \"Charting Daily Volume\", y = \"Volume\", x = \"\") + theme_tq() + theme(legend.position = \"none\") start <- end - weeks(24) AMZN %>% dplyr::filter(date >= start - days(50)) %>% ggplot(aes(x = date, y = volume)) + geom_segment(aes(xend = date, yend = 0, color = volume)) + geom_smooth(method = \"loess\", se = FALSE) + labs(title = \"AMZN Bar Chart\", subtitle = \"Charting Daily Volume, Zooming In\", y = \"Volume\", x = \"\") + coord_x_date(xlim = c(start, end)) + scale_color_gradient(low = \"red\", high = \"darkblue\") + theme_tq() + theme(legend.position = \"none\")"},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"themes","dir":"Articles","previous_headings":"","what":"Themes","title":"Charting with tidyquant","text":"tidyquant package comes three themes help quickly customize financial charts: Light: theme_tq() + scale_color_tq() + scale_fill_tq() Dark: theme_tq_dark() + scale_color_tq(theme = \"dark\") + scale_fill_tq(theme = \"dark\") Green: theme_tq_green() + scale_color_tq(theme = \"green\") + scale_fill_tq(theme = \"green\")","code":""},{"path":"/articles/TQ04-charting-with-tidyquant.html","id":"dark","dir":"Articles","previous_headings":"Themes","what":"Dark","title":"Charting with tidyquant","text":"","code":"n_mavg <- 50 # Number of periods (days) for moving average FANG %>% dplyr::filter(date >= start - days(2 * n_mavg)) %>% ggplot(aes(x = date, y = close, color = symbol)) + geom_line(linewidth = 1) + geom_ma(n = 15, color = \"darkblue\", size = 1) + geom_ma(n = n_mavg, color = \"red\", size = 1) + labs(title = \"Dark Theme\", x = \"\", y = \"Closing Price\") + coord_x_date(xlim = c(start, end)) + facet_wrap(~ symbol, scales = \"free_y\") + theme_tq_dark() + scale_color_tq(theme = \"dark\") + scale_y_continuous(labels = scales::label_dollar())"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"overview","dir":"Articles","previous_headings":"","what":"Overview","title":"Performance Analysis with tidyquant","text":"Financial asset (individual stocks, securities, etc) portfolio (groups stocks, securities, etc) performance analysis deep field wide range theories methods analyzing risk versus reward. PerformanceAnalytics package consolidates functions compute many widely used performance metrics. tidquant integrates functionality can used scale using split, apply, combine framework within tidyverse. Two primary functions integrate performance analysis functionality: tq_performance implements performance analysis functions tidy way, enabling scaling analysis using split, apply, combine framework. tq_portfolio provides useful tool set aggregating group individual asset returns one many portfolios. vignette aims cover three aspects performance analysis: general workflow go start finish asset portfolio level available techniques implement workflow implemented customize tq_portfolio tq_performance using ... parameter","code":""},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"key-concepts","dir":"Articles","previous_headings":"","what":"1.0 Key Concepts","title":"Performance Analysis with tidyquant","text":"important concept performance analysis based statistical properties returns (prices). result, package uses inputs time-based returns opposed stock prices. arguments change Ra asset returns Rb baseline returns. ’ll go get returns Workflow section. Another important concept baseline. baseline measuring performance . baseline can anything, many cases ’s representative average investment might perform little effort. Often indexes S&P500 used general market performance. times specific Exchange Traded Funds (ETFs) used SPDR Technology ETF (XLK). important concept measure asset performance (Ra) baseline (Rb). Now quick tutorial show PerformanceAnalytics package integration.","code":""},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"quick-example","dir":"Articles","previous_headings":"","what":"2.0 Quick Example","title":"Performance Analysis with tidyquant","text":"One widely used risk return metrics Capital Asset Pricing Model (CAPM). According Investopedia: capital asset pricing model (CAPM) model describes relationship systematic risk expected return assets, particularly stocks. CAPM widely used throughout finance pricing risky securities, generating expected returns assets given risk assets calculating costs capital. ’ll use PerformanceAnalytics function, table.CAPM, evaluate returns several technology stocks SPDR Technology ETF (XLK). First, load tidyquant package. Second, get stock returns stocks wish evaluate. use tq_get get stock prices Yahoo Finance, group_by group stock prices related symbol, tq_transmute retrieve period returns monthly periodicity using “adjusted” stock prices (adjusted stock splits, can throw returns, affecting performance analysis). Review output see three groups symbols indicating data grouped appropriately. Next, get baseline prices. ’ll use XLK. Note need group just getting one data set. Now, combine two data sets using “date” field using left_join dplyr package. Review results see still three groups returns, columns “Ra” “Rb” side--side. Finally, can retrieve performance metrics using tq_performance(). can use tq_performance_fun_options() see full list compatible performance functions. can quickly isolate attributes, alpha, measure growth, beta, measure risk. tidyquant ’s efficient easy get CAPM information! , ’s just one 129 available functions analyze stock portfolio return performance. Just use tq_performance_fun_options() see full list.","code":"library(dplyr) library(ggplot2) library(tidyquant) Ra <- c(\"AAPL\", \"GOOG\", \"NFLX\") %>% tq_get(get = \"stock.prices\", from = \"2010-01-01\", to = \"2015-12-31\") %>% group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"monthly\", col_rename = \"Ra\") Ra ## # A tibble: 216 × 3 ## # Groups: symbol [3] ## symbol date Ra ## ## 1 AAPL 2010-01-29 -0.103 ## 2 AAPL 2010-02-26 0.0654 ## 3 AAPL 2010-03-31 0.148 ## 4 AAPL 2010-04-30 0.111 ## 5 AAPL 2010-05-28 -0.0161 ## 6 AAPL 2010-06-30 -0.0208 ## 7 AAPL 2010-07-30 0.0227 ## 8 AAPL 2010-08-31 -0.0550 ## 9 AAPL 2010-09-30 0.167 ## 10 AAPL 2010-10-29 0.0607 ## # ℹ 206 more rows Rb <- \"XLK\" %>% tq_get(get = \"stock.prices\", from = \"2010-01-01\", to = \"2015-12-31\") %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"monthly\", col_rename = \"Rb\") Rb ## # A tibble: 72 × 2 ## date Rb ## ## 1 2010-01-29 -0.0993 ## 2 2010-02-26 0.0348 ## 3 2010-03-31 0.0684 ## 4 2010-04-30 0.0126 ## 5 2010-05-28 -0.0748 ## 6 2010-06-30 -0.0540 ## 7 2010-07-30 0.0745 ## 8 2010-08-31 -0.0561 ## 9 2010-09-30 0.117 ## 10 2010-10-29 0.0578 ## # ℹ 62 more rows RaRb <- left_join(Ra, Rb, by = c(\"date\" = \"date\")) RaRb ## # A tibble: 216 × 4 ## # Groups: symbol [3] ## symbol date Ra Rb ## ## 1 AAPL 2010-01-29 -0.103 -0.0993 ## 2 AAPL 2010-02-26 0.0654 0.0348 ## 3 AAPL 2010-03-31 0.148 0.0684 ## 4 AAPL 2010-04-30 0.111 0.0126 ## 5 AAPL 2010-05-28 -0.0161 -0.0748 ## 6 AAPL 2010-06-30 -0.0208 -0.0540 ## 7 AAPL 2010-07-30 0.0227 0.0745 ## 8 AAPL 2010-08-31 -0.0550 -0.0561 ## 9 AAPL 2010-09-30 0.167 0.117 ## 10 AAPL 2010-10-29 0.0607 0.0578 ## # ℹ 206 more rows RaRb_capm <- RaRb %>% tq_performance(Ra = Ra, Rb = Rb, performance_fun = table.CAPM) RaRb_capm ## # A tibble: 3 × 13 ## # Groups: symbol [3] ## symbol ActivePremium Alpha AnnualizedAlpha Beta `Beta-` `Beta+` Correlation ## ## 1 AAPL 0.119 0.0089 0.112 1.11 0.578 1.04 0.659 ## 2 GOOG 0.034 0.0028 0.034 1.14 1.39 1.16 0.644 ## 3 NFLX 0.447 0.053 0.859 0.384 -1.52 0.0045 0.0817 ## # ℹ 5 more variables: `Correlationp-value` , InformationRatio , ## # `R-squared` , TrackingError , TreynorRatio RaRb_capm %>% select(symbol, Alpha, Beta) ## # A tibble: 3 × 3 ## # Groups: symbol [3] ## symbol Alpha Beta ## ## 1 AAPL 0.0089 1.11 ## 2 GOOG 0.0028 1.14 ## 3 NFLX 0.053 0.384"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"workflow","dir":"Articles","previous_headings":"","what":"3.0 Workflow","title":"Performance Analysis with tidyquant","text":"general workflow shown diagram . ’ll step workflow first group individual assets (stocks) portfolios stocks. Performance Analysis Workflow","code":""},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"individual-assets","dir":"Articles","previous_headings":"3.0 Workflow","what":"3.1 Individual Assets","title":"Performance Analysis with tidyquant","text":"Individual assets simplest form analysis portfolio aggregation (Step 3A). ’ll re-“Quick Example” time getting Sharpe Ratio, measure reward--risk. get started let’s find performance function want use PerformanceAnalytics. Searching tq_performance_fun_options, can see SharpeRatio available. Type ?SharpeRatio, can see arguments : can actually skip baseline path function require Rb. function takes R, passed using Ra tq_performance(Ra, Rb, performance_fun, ...). little bit foresight saves us work.","code":"args(SharpeRatio) ## function (R, Rf = 0, p = 0.95, FUN = c(\"StdDev\", \"VaR\", \"ES\"), ## weights = NULL, annualize = FALSE, SE = FALSE, SE.control = NULL, ## ...) ## NULL"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"step-1a-get-stock-prices","dir":"Articles","previous_headings":"3.0 Workflow > 3.1 Individual Assets","what":"Step 1A: Get stock prices","title":"Performance Analysis with tidyquant","text":"Use tq_get() get stock prices.","code":"stock_prices <- c(\"AAPL\", \"GOOG\", \"NFLX\") %>% tq_get(get = \"stock.prices\", from = \"2010-01-01\", to = \"2015-12-31\") stock_prices ## # A tibble: 4,527 × 8 ## symbol date open high low close volume adjusted ## ## 1 AAPL 2010-01-04 7.62 7.66 7.59 7.64 493729600 6.49 ## 2 AAPL 2010-01-05 7.66 7.70 7.62 7.66 601904800 6.50 ## 3 AAPL 2010-01-06 7.66 7.69 7.53 7.53 552160000 6.40 ## 4 AAPL 2010-01-07 7.56 7.57 7.47 7.52 477131200 6.38 ## 5 AAPL 2010-01-08 7.51 7.57 7.47 7.57 447610800 6.43 ## 6 AAPL 2010-01-11 7.60 7.61 7.44 7.50 462229600 6.37 ## 7 AAPL 2010-01-12 7.47 7.49 7.37 7.42 594459600 6.30 ## 8 AAPL 2010-01-13 7.42 7.53 7.29 7.52 605892000 6.39 ## 9 AAPL 2010-01-14 7.50 7.52 7.47 7.48 432894000 6.35 ## 10 AAPL 2010-01-15 7.53 7.56 7.35 7.35 594067600 6.24 ## # ℹ 4,517 more rows"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"step-2a-mutate-to-returns","dir":"Articles","previous_headings":"3.0 Workflow > 3.1 Individual Assets","what":"Step 2A: Mutate to returns","title":"Performance Analysis with tidyquant","text":"Using tidyverse split, apply, combine framework, can mutate groups stocks first “grouping” group_by applying mutating function using tq_transmute. use quantmod function periodReturn mutating function. pass along arguments period = \"monthly\" return results monthly periodicity. Last, use col_rename argument rename output column.","code":"stock_returns_monthly <- stock_prices %>% group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"monthly\", col_rename = \"Ra\") stock_returns_monthly ## # A tibble: 216 × 3 ## # Groups: symbol [3] ## symbol date Ra ## ## 1 AAPL 2010-01-29 -0.103 ## 2 AAPL 2010-02-26 0.0654 ## 3 AAPL 2010-03-31 0.148 ## 4 AAPL 2010-04-30 0.111 ## 5 AAPL 2010-05-28 -0.0161 ## 6 AAPL 2010-06-30 -0.0208 ## 7 AAPL 2010-07-30 0.0227 ## 8 AAPL 2010-08-31 -0.0550 ## 9 AAPL 2010-09-30 0.167 ## 10 AAPL 2010-10-29 0.0607 ## # ℹ 206 more rows"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"step-3a-aggregate-to-portfolio-returns-skipped","dir":"Articles","previous_headings":"3.0 Workflow > 3.1 Individual Assets","what":"Step 3A: Aggregate to Portfolio Returns (Skipped)","title":"Performance Analysis with tidyquant","text":"Step 3A can skipped interested Sharpe Ratio individual stocks (portfolio). Step 3B can also skipped SharpeRatio function PerformanceAnalytics require baseline.","code":""},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"step-4-analyze-performance","dir":"Articles","previous_headings":"3.0 Workflow > 3.1 Individual Assets","what":"Step 4: Analyze Performance","title":"Performance Analysis with tidyquant","text":"last step apply SharpeRatio function groups stock returns. using tq_performance() arguments Ra = Ra, Rb = NULL (required), performance_fun = SharpeRatio. can also pass arguments SharpeRatio function Rf, p, FUN, annualize. just use defaults example. Now Sharpe Ratio three stocks. want adjust parameters function? can just add arguments underlying function.","code":"stock_returns_monthly %>% tq_performance( Ra = Ra, Rb = NULL, performance_fun = SharpeRatio ) ## # A tibble: 3 × 4 ## # Groups: symbol [3] ## symbol `ESSharpe(Rf=0%,p=95%)` StdDevSharpe(Rf=0%,p=9…¹ VaRSharpe(Rf=0%,p=95…² ## ## 1 AAPL 0.173 0.292 0.218 ## 2 GOOG 0.129 0.203 0.157 ## 3 NFLX 0.237 0.284 0.272 ## # ℹ abbreviated names: ¹​`StdDevSharpe(Rf=0%,p=95%)`, ²​`VaRSharpe(Rf=0%,p=95%)` stock_returns_monthly %>% tq_performance( Ra = Ra, Rb = NULL, performance_fun = SharpeRatio, Rf = 0.03 / 12, p = 0.99 ) ## # A tibble: 3 × 4 ## # Groups: symbol [3] ## symbol `ESSharpe(Rf=0.2%,p=99%)` StdDevSharpe(Rf=0.2%…¹ VaRSharpe(Rf=0.2%,p=…² ## ## 1 AAPL 0.116 0.258 0.134 ## 2 GOOG 0.0826 0.170 0.0998 ## 3 NFLX 0.115 0.272 0.142 ## # ℹ abbreviated names: ¹​`StdDevSharpe(Rf=0.2%,p=99%)`, ## # ²​`VaRSharpe(Rf=0.2%,p=99%)`"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"portfolios-asset-groups","dir":"Articles","previous_headings":"3.0 Workflow","what":"3.2 Portfolios (Asset Groups)","title":"Performance Analysis with tidyquant","text":"Portfolios slightly complicated now dealing groups assets versus individual stocks, need aggregate weighted returns. Fortunately, one extra step tidyquant using tq_portfolio().","code":""},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"single-portfolio","dir":"Articles","previous_headings":"3.0 Workflow > 3.2 Portfolios (Asset Groups)","what":"Single Portfolio","title":"Performance Analysis with tidyquant","text":"Let’s recreate CAPM analysis “Quick Example” time comparing portfolio technology stocks SPDR Technology ETF (XLK).","code":""},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"steps-1a-and-2a-asset-period-returns","dir":"Articles","previous_headings":"3.0 Workflow > 3.2 Portfolios (Asset Groups) > Single Portfolio","what":"Steps 1A and 2A: Asset Period Returns","title":"Performance Analysis with tidyquant","text":"previously get monthly returns groups individual stock prices. use split, apply, combine framework using workflow tq_get, group_by, tq_transmute.","code":"stock_returns_monthly <- c(\"AAPL\", \"GOOG\", \"NFLX\") %>% tq_get(get = \"stock.prices\", from = \"2010-01-01\", to = \"2015-12-31\") %>% group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"monthly\", col_rename = \"Ra\") stock_returns_monthly ## # A tibble: 216 × 3 ## # Groups: symbol [3] ## symbol date Ra ## ## 1 AAPL 2010-01-29 -0.103 ## 2 AAPL 2010-02-26 0.0654 ## 3 AAPL 2010-03-31 0.148 ## 4 AAPL 2010-04-30 0.111 ## 5 AAPL 2010-05-28 -0.0161 ## 6 AAPL 2010-06-30 -0.0208 ## 7 AAPL 2010-07-30 0.0227 ## 8 AAPL 2010-08-31 -0.0550 ## 9 AAPL 2010-09-30 0.167 ## 10 AAPL 2010-10-29 0.0607 ## # ℹ 206 more rows"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"steps-1b-and-2b-baseline-period-returns","dir":"Articles","previous_headings":"3.0 Workflow > 3.2 Portfolios (Asset Groups) > Single Portfolio","what":"Steps 1B and 2B: Baseline Period Returns","title":"Performance Analysis with tidyquant","text":"also done previously.","code":"baseline_returns_monthly <- \"XLK\" %>% tq_get(get = \"stock.prices\", from = \"2010-01-01\", to = \"2015-12-31\") %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"monthly\", col_rename = \"Rb\") baseline_returns_monthly ## # A tibble: 72 × 2 ## date Rb ## ## 1 2010-01-29 -0.0993 ## 2 2010-02-26 0.0348 ## 3 2010-03-31 0.0684 ## 4 2010-04-30 0.0126 ## 5 2010-05-28 -0.0748 ## 6 2010-06-30 -0.0540 ## 7 2010-07-30 0.0745 ## 8 2010-08-31 -0.0561 ## 9 2010-09-30 0.117 ## 10 2010-10-29 0.0578 ## # ℹ 62 more rows"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"step-3a-aggregate-to-portfolio-period-returns","dir":"Articles","previous_headings":"3.0 Workflow > 3.2 Portfolios (Asset Groups) > Single Portfolio","what":"Step 3A: Aggregate to Portfolio Period Returns","title":"Performance Analysis with tidyquant","text":"tidyquant function, tq_portfolio() aggregates group individual assets single return using weighted composition underlying assets. need first develop portfolio weights. two ways single portfolio: Supplying vector weights Supplying two column tidy data frame (tibble) stock symbols first column weights map second. Suppose want split portfolio evenly AAPL NFLX. ’ll show using methods.","code":""},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"method-1-aggregating-a-portfolio-using-vector-of-weights","dir":"Articles","previous_headings":"","what":"Performance Analysis with tidyquant","title":"Performance Analysis with tidyquant","text":"’ll use weight vector, c(0.5, 0, 0.5). Two important aspects supplying numeric vector weights: First, notice length (3) equal number assets (3). requirement. Second, notice sum weighting vector equal 1. “required”, best practice. sum 1, weights distributed accordingly scaling vector 1, warning message appear. now aggregated portfolio 50/50 blend AAPL NFLX. may asking didn’t use GOOG? important thing understand assets asset returns don’t need used creating portfolio! enables us scale individual stock returns vary weights optimize portfolio (subject address future!)","code":"wts <- c(0.5, 0.0, 0.5) portfolio_returns_monthly <- stock_returns_monthly %>% tq_portfolio(assets_col = symbol, returns_col = Ra, weights = wts, col_rename = \"Ra\") portfolio_returns_monthly ## # A tibble: 72 × 2 ## date Ra ## ## 1 2010-01-29 0.0307 ## 2 2010-02-26 0.0629 ## 3 2010-03-31 0.130 ## 4 2010-04-30 0.239 ## 5 2010-05-28 0.0682 ## 6 2010-06-30 -0.0219 ## 7 2010-07-30 -0.0272 ## 8 2010-08-31 0.116 ## 9 2010-09-30 0.251 ## 10 2010-10-29 0.0674 ## # ℹ 62 more rows"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"method-2-aggregating-a-portfolio-using-two-column-tibble-with-symbols-and-weights","dir":"Articles","previous_headings":"","what":"Performance Analysis with tidyquant","title":"Performance Analysis with tidyquant","text":"possibly useful method aggregating returns using tibble symbols weights mapped portfolio. ’ll recreate previous portfolio example using mapped weights. Next, supply two column tibble, symbols first column weights second, weights argument tq_performance(). aggregated returns exactly . advantage method symbols need specified. symbol specified default gets weight zero. Now, imagine entire index, Russell 2000, 2000 individual stock returns nice tidy data frame. easy adjust portfolios compute blended returns, need supply symbols want blend. symbols default zero!","code":"wts_map <- tibble( symbols = c(\"AAPL\", \"NFLX\"), weights = c(0.5, 0.5) ) wts_map ## # A tibble: 2 × 2 ## symbols weights ## ## 1 AAPL 0.5 ## 2 NFLX 0.5 stock_returns_monthly %>% tq_portfolio(assets_col = symbol, returns_col = Ra, weights = wts_map, col_rename = \"Ra_using_wts_map\") ## # A tibble: 72 × 2 ## date Ra_using_wts_map ## ## 1 2010-01-29 0.0307 ## 2 2010-02-26 0.0629 ## 3 2010-03-31 0.130 ## 4 2010-04-30 0.239 ## 5 2010-05-28 0.0682 ## 6 2010-06-30 -0.0219 ## 7 2010-07-30 -0.0272 ## 8 2010-08-31 0.116 ## 9 2010-09-30 0.251 ## 10 2010-10-29 0.0674 ## # ℹ 62 more rows"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"step-3b-merging-ra-and-rb","dir":"Articles","previous_headings":"3.0 Workflow > 3.2 Portfolios (Asset Groups) > Single Portfolio","what":"Step 3B: Merging Ra and Rb","title":"Performance Analysis with tidyquant","text":"Now aggregated portfolio returns (“Ra”) Step 3A baseline returns (“Rb”) Step 2B, can merge get consolidated table asset baseline returns. Nothing new .","code":"RaRb_single_portfolio <- left_join(portfolio_returns_monthly, baseline_returns_monthly, by = \"date\") RaRb_single_portfolio ## # A tibble: 72 × 3 ## date Ra Rb ## ## 1 2010-01-29 0.0307 -0.0993 ## 2 2010-02-26 0.0629 0.0348 ## 3 2010-03-31 0.130 0.0684 ## 4 2010-04-30 0.239 0.0126 ## 5 2010-05-28 0.0682 -0.0748 ## 6 2010-06-30 -0.0219 -0.0540 ## 7 2010-07-30 -0.0272 0.0745 ## 8 2010-08-31 0.116 -0.0561 ## 9 2010-09-30 0.251 0.117 ## 10 2010-10-29 0.0674 0.0578 ## # ℹ 62 more rows"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"step-4-computing-the-capm-table","dir":"Articles","previous_headings":"3.0 Workflow > 3.2 Portfolios (Asset Groups) > Single Portfolio","what":"Step 4: Computing the CAPM Table","title":"Performance Analysis with tidyquant","text":"CAPM table computed function table.CAPM PerformanceAnalytics. just perform task performed “Quick Example”. Now CAPM performance metrics portfolio! cool, ’s cooler multiple portfolios. Let’s see .","code":"RaRb_single_portfolio %>% tq_performance(Ra = Ra, Rb = Rb, performance_fun = table.CAPM) ## # A tibble: 1 × 12 ## ActivePremium Alpha AnnualizedAlpha Beta `Beta-` `Beta+` Correlation ## ## 1 0.327 0.0299 0.425 0.754 -0.243 0.503 0.283 ## # ℹ 5 more variables: `Correlationp-value` , InformationRatio , ## # `R-squared` , TrackingError , TreynorRatio "},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"multiple-portfolios","dir":"Articles","previous_headings":"3.0 Workflow > 3.2 Portfolios (Asset Groups)","what":"Multiple Portfolios","title":"Performance Analysis with tidyquant","text":"understand process single portfolio using Step 3A, Method 2 (aggregating weights mapping), scaling multiple portfolios just building concept. Let’s recreate example “Single Portfolio” Example time three portfolios: 50% AAPL, 25% GOOG, 25% NFLX 25% AAPL, 50% GOOG, 25% NFLX 25% AAPL, 25% GOOG, 50% NFLX","code":""},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"steps-1-and-2-are-the-exact-same-as-the-single-portfolio-example","dir":"Articles","previous_headings":"3.0 Workflow > 3.2 Portfolios (Asset Groups) > Multiple Portfolios","what":"Steps 1 and 2 are the Exact Same as the Single Portfolio Example","title":"Performance Analysis with tidyquant","text":"First, get individual asset returns grouped asset, exact Steps 1A 1B Single Portfolio example. Second, get baseline asset returns, exact Steps 1B 2B Single Portfolio example.","code":"stock_returns_monthly <- c(\"AAPL\", \"GOOG\", \"NFLX\") %>% tq_get(get = \"stock.prices\", from = \"2010-01-01\", to = \"2015-12-31\") %>% group_by(symbol) %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"monthly\", col_rename = \"Ra\") baseline_returns_monthly <- \"XLK\" %>% tq_get(get = \"stock.prices\", from = \"2010-01-01\", to = \"2015-12-31\") %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"monthly\", col_rename = \"Rb\")"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"step-3a-aggregate-portfolio-returns-for-multiple-portfolios","dir":"Articles","previous_headings":"3.0 Workflow > 3.2 Portfolios (Asset Groups) > Multiple Portfolios","what":"Step 3A: Aggregate Portfolio Returns for Multiple Portfolios","title":"Performance Analysis with tidyquant","text":"gets fun. picked Single Portfolio, Step3A, Method 2 (mapping weights), just extension multiple portfolios. First, need grow portfolios. tidyquant handy, albeit simple, function, tq_repeat_df(), scaling single portfolio many. takes data frame, number repeats, n, index_col_name, adds sequential index. Let’s see works example. need three portfolios: Examining results, can see things happened: length (number rows) tripled. essence tq_repeat_df: grows data frame length-wise, repeating data frame n times. case, n = 3. data frame, grouped symbol, ungrouped. needed prevent tq_portfolio blending individual stocks. tq_portfolio works groups stocks. new column, named “portfolio”. “portfolio” column name key tells tq_portfolio multiple groups exist analyze. Just note multiple portfolio analysis, “portfolio” column name required. three groups portfolios. tq_portfolio split, apply (aggregate), combine . Now tricky part: need new table weights map . ’s requirements: must supply three column tibble following columns: “portfolio”, asset, weight order. “portfolio” column must named “portfolio” since key name mapping. tibble must grouped portfolio column. ’s weights table look like example: Now just pass expanded stock_returns_monthly_multi weights_table tq_portfolio portfolio aggregation. Let’s assess output. now single, “long” format data frame portfolio returns. three groups aggregated portfolios blended mapping weight_table.","code":"stock_returns_monthly_multi <- stock_returns_monthly %>% tq_repeat_df(n = 3) stock_returns_monthly_multi ## # A tibble: 648 × 4 ## # Groups: portfolio [3] ## portfolio symbol date Ra ## ## 1 1 AAPL 2010-01-29 -0.103 ## 2 1 AAPL 2010-02-26 0.0654 ## 3 1 AAPL 2010-03-31 0.148 ## 4 1 AAPL 2010-04-30 0.111 ## 5 1 AAPL 2010-05-28 -0.0161 ## 6 1 AAPL 2010-06-30 -0.0208 ## 7 1 AAPL 2010-07-30 0.0227 ## 8 1 AAPL 2010-08-31 -0.0550 ## 9 1 AAPL 2010-09-30 0.167 ## 10 1 AAPL 2010-10-29 0.0607 ## # ℹ 638 more rows weights <- c( 0.50, 0.25, 0.25, 0.25, 0.50, 0.25, 0.25, 0.25, 0.50 ) stocks <- c(\"AAPL\", \"GOOG\", \"NFLX\") weights_table <- tibble(stocks) %>% tq_repeat_df(n = 3) %>% bind_cols(tibble(weights)) %>% group_by(portfolio) weights_table ## # A tibble: 9 × 3 ## # Groups: portfolio [3] ## portfolio stocks weights ## ## 1 1 AAPL 0.5 ## 2 1 GOOG 0.25 ## 3 1 NFLX 0.25 ## 4 2 AAPL 0.25 ## 5 2 GOOG 0.5 ## 6 2 NFLX 0.25 ## 7 3 AAPL 0.25 ## 8 3 GOOG 0.25 ## 9 3 NFLX 0.5 portfolio_returns_monthly_multi <- stock_returns_monthly_multi %>% tq_portfolio(assets_col = symbol, returns_col = Ra, weights = weights_table, col_rename = \"Ra\") portfolio_returns_monthly_multi ## # A tibble: 216 × 3 ## # Groups: portfolio [3] ## portfolio date Ra ## ## 1 1 2010-01-29 -0.0489 ## 2 1 2010-02-26 0.0482 ## 3 1 2010-03-31 0.123 ## 4 1 2010-04-30 0.145 ## 5 1 2010-05-28 0.0245 ## 6 1 2010-06-30 -0.0308 ## 7 1 2010-07-30 0.000600 ## 8 1 2010-08-31 0.0474 ## 9 1 2010-09-30 0.222 ## 10 1 2010-10-29 0.0789 ## # ℹ 206 more rows"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"steps-3b-and-4-merging-and-assessing-performance","dir":"Articles","previous_headings":"3.0 Workflow > 3.2 Portfolios (Asset Groups) > Multiple Portfolios","what":"Steps 3B and 4: Merging and Assessing Performance","title":"Performance Analysis with tidyquant","text":"steps exact Single Portfolio example. First, merge baseline using “date” key. Finally, calculate performance portfolios using tq_performance. Make sure data frame grouped “portfolio”. Inspecting results, now multiple portfolio comparison CAPM table PerformanceAnalytics. can thing SharpeRatio well.","code":"RaRb_multiple_portfolio <- left_join(portfolio_returns_monthly_multi, baseline_returns_monthly, by = \"date\") RaRb_multiple_portfolio ## # A tibble: 216 × 4 ## # Groups: portfolio [3] ## portfolio date Ra Rb ## ## 1 1 2010-01-29 -0.0489 -0.0993 ## 2 1 2010-02-26 0.0482 0.0348 ## 3 1 2010-03-31 0.123 0.0684 ## 4 1 2010-04-30 0.145 0.0126 ## 5 1 2010-05-28 0.0245 -0.0748 ## 6 1 2010-06-30 -0.0308 -0.0540 ## 7 1 2010-07-30 0.000600 0.0745 ## 8 1 2010-08-31 0.0474 -0.0561 ## 9 1 2010-09-30 0.222 0.117 ## 10 1 2010-10-29 0.0789 0.0578 ## # ℹ 206 more rows RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = Rb, performance_fun = table.CAPM) ## # A tibble: 3 × 13 ## # Groups: portfolio [3] ## portfolio ActivePremium Alpha AnnualizedAlpha Beta `Beta-` `Beta+` ## ## 1 1 0.231 0.0193 0.258 0.908 0.312 0.741 ## 2 2 0.219 0.0192 0.256 0.886 0.436 0.660 ## 3 3 0.319 0.0308 0.439 0.721 -0.179 0.394 ## # ℹ 6 more variables: Correlation , `Correlationp-value` , ## # InformationRatio , `R-squared` , TrackingError , ## # TreynorRatio RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = NULL, performance_fun = SharpeRatio) ## # A tibble: 3 × 4 ## # Groups: portfolio [3] ## portfolio ESSharpe(Rf=0%,p=95%…¹ StdDevSharpe(Rf=0%,p…² VaRSharpe(Rf=0%,p=95…³ ## ## 1 1 0.172 0.355 0.263 ## 2 2 0.146 0.334 0.236 ## 3 3 0.150 0.317 0.238 ## # ℹ abbreviated names: ¹​`ESSharpe(Rf=0%,p=95%)`, ²​`StdDevSharpe(Rf=0%,p=95%)`, ## # ³​`VaRSharpe(Rf=0%,p=95%)`"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"available-functions","dir":"Articles","previous_headings":"","what":"4.0 Available Functions","title":"Performance Analysis with tidyquant","text":"’ve scratched surface analysis functions available PerformanceAnalytics. list includes compatible functions grouped function type. table functions useful get cross section metrics. ’ll touch . ’ll also go VaR SharpeRatio commonly used performance measures.","code":"tq_performance_fun_options() ## $table.funs ## [1] \"table.AnnualizedReturns\" \"table.Arbitrary\" ## [3] \"table.Autocorrelation\" \"table.CAPM\" ## [5] \"table.CaptureRatios\" \"table.Correlation\" ## [7] \"table.Distributions\" \"table.DownsideRisk\" ## [9] \"table.DownsideRiskRatio\" \"table.DrawdownsRatio\" ## [11] \"table.HigherMoments\" \"table.InformationRatio\" ## [13] \"table.RollingPeriods\" \"table.SFM\" ## [15] \"table.SpecificRisk\" \"table.Stats\" ## [17] \"table.TrailingPeriods\" \"table.UpDownRatios\" ## [19] \"table.Variability\" ## ## $CAPM.funs ## [1] \"CAPM.alpha\" \"CAPM.beta\" \"CAPM.beta.bear\" \"CAPM.beta.bull\" ## [5] \"CAPM.CML\" \"CAPM.CML.slope\" \"CAPM.dynamic\" \"CAPM.epsilon\" ## [9] \"CAPM.jensenAlpha\" \"CAPM.RiskPremium\" \"CAPM.SML.slope\" \"TimingRatio\" ## [13] \"MarketTiming\" ## ## $SFM.funs ## [1] \"SFM.alpha\" \"SFM.beta\" \"SFM.CML\" \"SFM.CML.slope\" ## [5] \"SFM.dynamic\" \"SFM.epsilon\" \"SFM.jensenAlpha\" ## ## $descriptive.funs ## [1] \"mean\" \"sd\" \"min\" \"max\" ## [5] \"cor\" \"mean.geometric\" \"mean.stderr\" \"mean.LCL\" ## [9] \"mean.UCL\" ## ## $annualized.funs ## [1] \"Return.annualized\" \"Return.annualized.excess\" ## [3] \"sd.annualized\" \"SharpeRatio.annualized\" ## ## $VaR.funs ## [1] \"VaR\" \"ES\" \"ETL\" \"CDD\" \"CVaR\" ## ## $moment.funs ## [1] \"var\" \"cov\" \"skewness\" \"kurtosis\" ## [5] \"CoVariance\" \"CoSkewness\" \"CoSkewnessMatrix\" \"CoKurtosis\" ## [9] \"CoKurtosisMatrix\" \"M3.MM\" \"M4.MM\" \"BetaCoVariance\" ## [13] \"BetaCoSkewness\" \"BetaCoKurtosis\" ## ## $drawdown.funs ## [1] \"AverageDrawdown\" \"AverageLength\" \"AverageRecovery\" ## [4] \"DrawdownDeviation\" \"DrawdownPeak\" \"maxDrawdown\" ## ## $Bacon.risk.funs ## [1] \"MeanAbsoluteDeviation\" \"Frequency\" \"SharpeRatio\" ## [4] \"MSquared\" \"MSquaredExcess\" \"HurstIndex\" ## ## $Bacon.regression.funs ## [1] \"CAPM.alpha\" \"CAPM.beta\" \"CAPM.epsilon\" \"CAPM.jensenAlpha\" ## [5] \"SystematicRisk\" \"SpecificRisk\" \"TotalRisk\" \"TreynorRatio\" ## [9] \"AppraisalRatio\" \"FamaBeta\" \"Selectivity\" \"NetSelectivity\" ## ## $Bacon.relative.risk.funs ## [1] \"ActivePremium\" \"ActiveReturn\" \"TrackingError\" \"InformationRatio\" ## ## $Bacon.drawdown.funs ## [1] \"PainIndex\" \"PainRatio\" \"CalmarRatio\" \"SterlingRatio\" ## [5] \"BurkeRatio\" \"MartinRatio\" \"UlcerIndex\" ## ## $Bacon.downside.risk.funs ## [1] \"DownsideDeviation\" \"DownsidePotential\" \"DownsideFrequency\" ## [4] \"SemiDeviation\" \"SemiVariance\" \"UpsideRisk\" ## [7] \"UpsidePotentialRatio\" \"UpsideFrequency\" \"BernardoLedoitRatio\" ## [10] \"DRatio\" \"Omega\" \"OmegaSharpeRatio\" ## [13] \"OmegaExcessReturn\" \"SortinoRatio\" \"M2Sortino\" ## [16] \"Kappa\" \"VolatilitySkewness\" \"AdjustedSharpeRatio\" ## [19] \"SkewnessKurtosisRatio\" \"ProspectRatio\" ## ## $misc.funs ## [1] \"KellyRatio\" \"Modigliani\" \"UpDownRatios\""},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"table-stats","dir":"Articles","previous_headings":"4.0 Available Functions","what":"4.1 table.Stats","title":"Performance Analysis with tidyquant","text":"Returns basic set statistics match period data passed (e.g., monthly returns get monthly statistics, daily daily stats, ).","code":"RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = NULL, performance_fun = table.Stats) ## # A tibble: 3 × 17 ## # Groups: portfolio [3] ## portfolio ArithmeticMean GeometricMean Kurtosis `LCLMean(0.95)` Maximum Median ## ## 1 1 0.0293 0.0259 1.14 0.0099 0.222 0.0307 ## 2 2 0.029 0.0252 1.65 0.0086 0.227 0.037 ## 3 3 0.0388 0.0313 1.81 0.01 0.370 0.046 ## # ℹ 10 more variables: Minimum , NAs , Observations , ## # Quartile1 , Quartile3 , SEMean , Skewness , ## # Stdev , `UCLMean(0.95)` , Variance "},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"table-capm","dir":"Articles","previous_headings":"4.0 Available Functions","what":"4.2 table.CAPM","title":"Performance Analysis with tidyquant","text":"Takes set returns relates benchmark return. Provides set measures related excess return single factor model, CAPM.","code":"RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = Rb, performance_fun = table.CAPM) ## # A tibble: 3 × 13 ## # Groups: portfolio [3] ## portfolio ActivePremium Alpha AnnualizedAlpha Beta `Beta-` `Beta+` ## ## 1 1 0.231 0.0193 0.258 0.908 0.312 0.741 ## 2 2 0.219 0.0192 0.256 0.886 0.436 0.660 ## 3 3 0.319 0.0308 0.439 0.721 -0.179 0.394 ## # ℹ 6 more variables: Correlation , `Correlationp-value` , ## # InformationRatio , `R-squared` , TrackingError , ## # TreynorRatio "},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"table-annualizedreturns","dir":"Articles","previous_headings":"4.0 Available Functions","what":"4.3 table.AnnualizedReturns","title":"Performance Analysis with tidyquant","text":"Table Annualized Return, Annualized Std Dev, Annualized Sharpe.","code":"RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = NULL, performance_fun = table.AnnualizedReturns) ## # A tibble: 3 × 4 ## # Groups: portfolio [3] ## portfolio AnnualizedReturn `AnnualizedSharpe(Rf=0%)` AnnualizedStdDev ## ## 1 1 0.360 1.26 0.286 ## 2 2 0.348 1.16 0.301 ## 3 3 0.448 1.06 0.424"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"table-correlation","dir":"Articles","previous_headings":"4.0 Available Functions","what":"4.4 table.Correlation","title":"Performance Analysis with tidyquant","text":"wrapper calculating correlation significance column data provided.","code":"RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = Rb, performance_fun = table.Correlation) ## # A tibble: 3 × 5 ## # Groups: portfolio [3] ## portfolio `p-value` `Lower CI` `Upper CI` to.Rb ## ## 1 1 0.0000284 0.270 0.634 0.472 ## 2 2 0.000122 0.229 0.608 0.438 ## 3 3 0.0325 0.0220 0.457 0.252"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"table-downsiderisk","dir":"Articles","previous_headings":"4.0 Available Functions","what":"4.5 table.DownsideRisk","title":"Performance Analysis with tidyquant","text":"Creates table estimates downside risk measures comparison across multiple instruments funds.","code":"RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = NULL, performance_fun = table.DownsideRisk) ## # A tibble: 3 × 12 ## # Groups: portfolio [3] ## portfolio DownsideDeviation(0%…¹ DownsideDeviation(MA…² DownsideDeviation(Rf…³ ## ## 1 1 0.045 0.0488 0.045 ## 2 2 0.0501 0.0538 0.0501 ## 3 3 0.0684 0.0721 0.0684 ## # ℹ abbreviated names: ¹​`DownsideDeviation(0%)`, ²​`DownsideDeviation(MAR=10%)`, ## # ³​`DownsideDeviation(Rf=0%)` ## # ℹ 8 more variables: GainDeviation , `HistoricalES(95%)` , ## # `HistoricalVaR(95%)` , LossDeviation , MaximumDrawdown , ## # `ModifiedES(95%)` , `ModifiedVaR(95%)` , SemiDeviation "},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"table-downsideriskratio","dir":"Articles","previous_headings":"4.0 Available Functions","what":"4.6 table.DownsideRiskRatio","title":"Performance Analysis with tidyquant","text":"Table Monthly downside risk, Annualized downside risk, Downside potential, Omega, Sortino ratio, Upside potential, Upside potential ratio Omega-Sharpe ratio.","code":"RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = NULL, performance_fun = table.DownsideRiskRatio) ## # A tibble: 3 × 9 ## # Groups: portfolio [3] ## portfolio Annualiseddownsiderisk Downsidepotential monthlydownsiderisk Omega ## ## 1 1 0.156 0.0198 0.045 2.48 ## 2 2 0.173 0.0217 0.0501 2.34 ## 3 3 0.237 0.0294 0.0684 2.32 ## # ℹ 4 more variables: `Omega-sharperatio` , Sortinoratio , ## # Upsidepotential , Upsidepotentialratio "},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"table-highermoments","dir":"Articles","previous_headings":"4.0 Available Functions","what":"4.7 table.HigherMoments","title":"Performance Analysis with tidyquant","text":"Summary higher moments Co-Moments return distribution. Used determine diversification potential. Also called “systematic” moments several papers.","code":"RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = Rb, performance_fun = table.HigherMoments) ## # A tibble: 3 × 6 ## # Groups: portfolio [3] ## portfolio BetaCoKurtosis BetaCoSkewness BetaCoVariance CoKurtosis CoSkewness ## ## 1 1 0.756 0.196 0.908 0 0 ## 2 2 0.772 1.71 0.886 0 0 ## 3 3 0.455 0.369 0.721 0 0"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"table-informationratio","dir":"Articles","previous_headings":"4.0 Available Functions","what":"4.8 table.InformationRatio","title":"Performance Analysis with tidyquant","text":"Table Tracking error, Annualized tracking error Information ratio.","code":"RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = Rb, performance_fun = table.InformationRatio) ## # A tibble: 3 × 4 ## # Groups: portfolio [3] ## portfolio AnnualisedTrackingError InformationRatio TrackingError ## ## 1 1 0.252 0.917 0.0728 ## 2 2 0.271 0.809 0.0782 ## 3 3 0.412 0.774 0.119"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"table-variability","dir":"Articles","previous_headings":"4.0 Available Functions","what":"4.9 table.Variability","title":"Performance Analysis with tidyquant","text":"Table Mean absolute difference, Monthly standard deviation annualized standard deviation.","code":"RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = NULL, performance_fun = table.Variability) ## # A tibble: 3 × 4 ## # Groups: portfolio [3] ## portfolio AnnualizedStdDev MeanAbsolutedeviation monthlyStdDev ## ## 1 1 0.286 0.0658 0.0825 ## 2 2 0.301 0.0679 0.0868 ## 3 3 0.424 0.091 0.122"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"var","dir":"Articles","previous_headings":"4.0 Available Functions","what":"4.10 VaR","title":"Performance Analysis with tidyquant","text":"Calculates Value--Risk (VaR) univariate, component, marginal cases using variety analytical methods.","code":"RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = NULL, performance_fun = VaR) ## # A tibble: 3 × 2 ## # Groups: portfolio [3] ## portfolio VaR ## ## 1 1 -0.111 ## 2 2 -0.123 ## 3 3 -0.163"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"sharperatio","dir":"Articles","previous_headings":"4.0 Available Functions","what":"4.11 SharpeRatio","title":"Performance Analysis with tidyquant","text":"Sharpe ratio simply return per unit risk (represented variability). classic case, unit risk standard deviation returns.","code":"RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, Rb = NULL, performance_fun = SharpeRatio) ## # A tibble: 3 × 4 ## # Groups: portfolio [3] ## portfolio ESSharpe(Rf=0%,p=95%…¹ StdDevSharpe(Rf=0%,p…² VaRSharpe(Rf=0%,p=95…³ ## ## 1 1 0.172 0.355 0.263 ## 2 2 0.146 0.334 0.236 ## 3 3 0.150 0.317 0.238 ## # ℹ abbreviated names: ¹​`ESSharpe(Rf=0%,p=95%)`, ²​`StdDevSharpe(Rf=0%,p=95%)`, ## # ³​`VaRSharpe(Rf=0%,p=95%)`"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"customizing-using-the","dir":"Articles","previous_headings":"","what":"5.0 Customizing using the …","title":"Performance Analysis with tidyquant","text":"One best features tq_portfolio tq_performance able pass features underlying functions. , just wrappers PerformanceAnalytics, probably want able make full use underlying functions. Passing parameters using ... can incredibly useful, let’s see .","code":""},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"customizing-tq_portfolio","dir":"Articles","previous_headings":"5.0 Customizing using the …","what":"5.1 Customizing tq_portfolio","title":"Performance Analysis with tidyquant","text":"tq_portfolio function wrapper Return.portfolio. means portfolio aggregation process, can make use Return.portfolio arguments wealth.index, contribution, geometric, rebalance_on, value. ’s arguments underlying function: Let’s see example passing parameters .... Suppose want instead see money grows $10,000 investment. ’ll use “Single Portfolio” example, portfolio mix 50% AAPL, 0% GOOG, 50% NFLX. Method 3A, Aggregating Portfolio Returns, showed us two methods aggregate single portfolio. Either work example. simplicity, ’ll examine first. ’s original output, without adjusting parameters. good, want see $10,000 initial investment growing. simple underlying Return.portfolio argument, wealth.index = TRUE. need add additional parameters tq_portfolio! Finally, taking one step , apply process “Multiple Portfolio” example: 50% AAPL, 25% GOOG, 25% NFLX 25% AAPL, 50% GOOG, 25% NFLX 25% AAPL, 25% GOOG, 50% NFLX","code":"args(Return.portfolio) ## function (R, weights = NULL, wealth.index = FALSE, contribution = FALSE, ## geometric = TRUE, rebalance_on = c(NA, \"years\", \"quarters\", ## \"months\", \"weeks\", \"days\"), value = 1, verbose = FALSE, ## ...) ## NULL wts <- c(0.5, 0.0, 0.5) portfolio_returns_monthly <- stock_returns_monthly %>% tq_portfolio(assets_col = symbol, returns_col = Ra, weights = wts, col_rename = \"Ra\") portfolio_returns_monthly %>% ggplot(aes(x = date, y = Ra)) + geom_bar(stat = \"identity\", fill = palette_light()[[1]]) + labs(title = \"Portfolio Returns\", subtitle = \"50% AAPL, 0% GOOG, and 50% NFLX\", caption = \"Shows an above-zero trend meaning positive returns\", x = \"\", y = \"Monthly Returns\") + geom_smooth(method = \"lm\") + theme_tq() + scale_color_tq() + scale_y_continuous(labels = scales::percent) wts <- c(0.5, 0, 0.5) portfolio_growth_monthly <- stock_returns_monthly %>% tq_portfolio(assets_col = symbol, returns_col = Ra, weights = wts, col_rename = \"investment.growth\", wealth.index = TRUE) %>% mutate(investment.growth = investment.growth * 10000) portfolio_growth_monthly %>% ggplot(aes(x = date, y = investment.growth)) + geom_line(linewidth = 2, color = palette_light()[[1]]) + labs(title = \"Portfolio Growth\", subtitle = \"50% AAPL, 0% GOOG, and 50% NFLX\", caption = \"Now we can really visualize performance!\", x = \"\", y = \"Portfolio Value\") + geom_smooth(method = \"loess\") + theme_tq() + scale_color_tq() + scale_y_continuous(labels = scales::dollar) portfolio_growth_monthly_multi <- stock_returns_monthly_multi %>% tq_portfolio(assets_col = symbol, returns_col = Ra, weights = weights_table, col_rename = \"investment.growth\", wealth.index = TRUE) %>% mutate(investment.growth = investment.growth * 10000) portfolio_growth_monthly_multi %>% ggplot(aes(x = date, y = investment.growth, color = factor(portfolio))) + geom_line(linewidth = 2) + labs(title = \"Portfolio Growth\", subtitle = \"Comparing Multiple Portfolios\", caption = \"Portfolio 3 is a Standout!\", x = \"\", y = \"Portfolio Value\", color = \"Portfolio\") + geom_smooth(method = \"loess\") + theme_tq() + scale_color_tq() + scale_y_continuous(labels = scales::dollar)"},{"path":"/articles/TQ05-performance-analysis-with-tidyquant.html","id":"customizing-tq_performance","dir":"Articles","previous_headings":"5.0 Customizing using the …","what":"5.2 Customizing tq_performance","title":"Performance Analysis with tidyquant","text":"Finally, concept passing arguments works tidyquant functions wrappers including tq_transmute, tq_mutate, tq_performance, etc. Let’s use final example SharpeRatio, following arguments. can see parameters Rf allows us apply risk-free rate p allows us vary confidence interval. Let’s compare Sharpe ratio annualized risk-free rate 3% confidence interval 0.99. Default: Rf = 0.03 / 12 (adjusted monthly periodicity): , Rf = 0.03 / 12 (adjusted monthly periodicity) p = 0.99:","code":"args(SharpeRatio) ## function (R, Rf = 0, p = 0.95, FUN = c(\"StdDev\", \"VaR\", \"ES\"), ## weights = NULL, annualize = FALSE, SE = FALSE, SE.control = NULL, ## ...) ## NULL RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, performance_fun = SharpeRatio) ## # A tibble: 3 × 4 ## # Groups: portfolio [3] ## portfolio ESSharpe(Rf=0%,p=95%…¹ StdDevSharpe(Rf=0%,p…² VaRSharpe(Rf=0%,p=95…³ ## ## 1 1 0.172 0.355 0.263 ## 2 2 0.146 0.334 0.236 ## 3 3 0.150 0.317 0.238 ## # ℹ abbreviated names: ¹​`ESSharpe(Rf=0%,p=95%)`, ²​`StdDevSharpe(Rf=0%,p=95%)`, ## # ³​`VaRSharpe(Rf=0%,p=95%)` RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, performance_fun = SharpeRatio, Rf = 0.03 / 12) ## # A tibble: 3 × 4 ## # Groups: portfolio [3] ## portfolio ESSharpe(Rf=0.2%,p=9…¹ StdDevSharpe(Rf=0.2%…² VaRSharpe(Rf=0.2%,p=…³ ## ## 1 1 0.157 0.325 0.241 ## 2 2 0.134 0.305 0.216 ## 3 3 0.141 0.296 0.222 ## # ℹ abbreviated names: ¹​`ESSharpe(Rf=0.2%,p=95%)`, ## # ²​`StdDevSharpe(Rf=0.2%,p=95%)`, ³​`VaRSharpe(Rf=0.2%,p=95%)` RaRb_multiple_portfolio %>% tq_performance(Ra = Ra, performance_fun = SharpeRatio, Rf = 0.03 / 12, p = 0.99) ## # A tibble: 3 × 4 ## # Groups: portfolio [3] ## portfolio ESSharpe(Rf=0.2%,p=9…¹ StdDevSharpe(Rf=0.2%…² VaRSharpe(Rf=0.2%,p=…³ ## ## 1 1 0.105 0.325 0.134 ## 2 2 0.0952 0.305 0.115 ## 3 3 0.0915 0.296 0.117 ## # ℹ abbreviated names: ¹​`ESSharpe(Rf=0.2%,p=99%)`, ## # ²​`StdDevSharpe(Rf=0.2%,p=99%)`, ³​`VaRSharpe(Rf=0.2%,p=99%)`"},{"path":"/authors.html","id":null,"dir":"","previous_headings":"","what":"Authors","title":"Authors and Citation","text":"Matt Dancho. Author, maintainer. Davis Vaughan. Author.","code":""},{"path":"/authors.html","id":"citation","dir":"","previous_headings":"","what":"Citation","title":"Authors and Citation","text":"Dancho M, Vaughan D (2023). tidyquant: Tidy Quantitative Financial Analysis. https://business-science.github.io/tidyquant/, https://github.com/business-science/tidyquant.","code":"@Manual{, title = {tidyquant: Tidy Quantitative Financial Analysis}, author = {Matt Dancho and Davis Vaughan}, year = {2023}, note = {https://business-science.github.io/tidyquant/, https://github.com/business-science/tidyquant}, }"},{"path":"/index.html","id":"tidyquant-","dir":"","previous_headings":"","what":"Tidy Quantitative Financial Analysis","title":"Tidy Quantitative Financial Analysis","text":"Bringing financial business analysis tidyverse","code":""},{"path":"/index.html","id":"id_2-minutes-to-tidyquant","dir":"","previous_headings":"","what":"2-Minutes To tidyquant","title":"Tidy Quantitative Financial Analysis","text":"short introduction tidyquant YouTube.","code":""},{"path":"/index.html","id":"features-of-tidyquant","dir":"","previous_headings":"","what":"Features of tidyquant","title":"Tidy Quantitative Financial Analysis","text":"tidyquant integrates best resources collecting analyzing financial data, zoo, xts, quantmod, TTR, PerformanceAnalytics, tidy data infrastructure tidyverse allowing seamless interaction . can now perform complete financial analyses tidyverse. core functions lot power Integrates quantitative analysis functionality zoo, xts, quantmod, TTR, now PerformanceAnalytics Designed modeling scaling analyses using tidyverse tools R Data Science Implements ggplot2 functionality beautiful meaningful financial visualizations User-friendly documentation get speed quickly!","code":""},{"path":"/index.html","id":"new-excel-functionality-in-tidyquant","dir":"","previous_headings":"","what":"New Excel Functionality in tidyquant","title":"Tidy Quantitative Financial Analysis","text":"Excel R - Pivot Tables, VLOOKUPs, : Details Excel integrations covered blog article.","code":""},{"path":"/index.html","id":"one-stop-shop-for-serious-financial-analysis","dir":"","previous_headings":"","what":"One-Stop Shop for Serious Financial Analysis","title":"Tidy Quantitative Financial Analysis","text":"tidyquant benefits add one thing: one-stop shop serious financial analysis!","code":""},{"path":"/index.html","id":"core-functions","dir":"","previous_headings":"One-Stop Shop for Serious Financial Analysis","what":"Core Functions","title":"Tidy Quantitative Financial Analysis","text":"Getting Financial Data web: tq_get(). one-stop shop getting web-based financial data “tidy” data frame format. Get data daily stock prices (historical), key statistics (real-time), key ratios (historical), financial statements, dividends, splits, economic data FRED, FOREX rates Oanda. Manipulating Financial Data: tq_transmute() tq_mutate(). Integration many financial functions xts, zoo, quantmod,TTR PerformanceAnalytics packages. tq_mutate() used add column data frame, tq_transmute() used return new data frame necessary periodicity changes. Performance Analysis Portfolio Analysis: tq_performance() tq_portfolio(). newest additions tidyquant family integrate PerformanceAnalytics functions. tq_performance() converts investment returns performance metrics. tq_portfolio() aggregates group (multiple groups) asset returns one portfolios.","code":""},{"path":"/index.html","id":"comparing-stock-prices","dir":"","previous_headings":"One-Stop Shop for Serious Financial Analysis","what":"Comparing Stock Prices","title":"Tidy Quantitative Financial Analysis","text":"Visualizing stock price volatility four stocks side--side quick easy…","code":""},{"path":"/index.html","id":"evaluating-stock-performance","dir":"","previous_headings":"One-Stop Shop for Serious Financial Analysis","what":"Evaluating Stock Performance","title":"Tidy Quantitative Financial Analysis","text":"stock performance? Quickly visualize $10,000 investment various stocks perform.","code":""},{"path":"/index.html","id":"evaluating-portfolio-performance","dir":"","previous_headings":"One-Stop Shop for Serious Financial Analysis","what":"Evaluating Portfolio Performance","title":"Tidy Quantitative Financial Analysis","text":"Ok, stocks easy. portfolios? PerformanceAnalytics integration, visualizing blended portfolios easy ! Portfolio 1: 50% FB, 25% AMZN, 25% NFLX, 0% GOOG Portfolio 2: 0% FB, 50% AMZN, 25% NFLX, 25% GOOG Portfolio 3: 25% FB, 0% AMZN, 50% NFLX, 25% GOOG Portfolio 4: 25% FB, 25% AMZN, 0% NFLX, 50% GOOG just scratches surface tidyquant. ’s install get started.","code":""},{"path":"/index.html","id":"installation","dir":"","previous_headings":"","what":"Installation","title":"Tidy Quantitative Financial Analysis","text":"Development Version Latest Features: CRAN Approved Version:","code":"# install.packages(\"devtools\") devtools::install_github(\"business-science/tidyquant\") install.packages(\"tidyquant\")"},{"path":"/index.html","id":"further-information","dir":"","previous_headings":"","what":"Further Information","title":"Tidy Quantitative Financial Analysis","text":"tidyquant package includes several vignettes help users get speed quickly: TQ00 - Introduction tidyquant TQ01 - Core Functions tidyquant TQ02 - R Quantitative Analysis Package Integrations tidyquant TQ03 - Scaling Modeling tidyquant TQ04 - Charting tidyquant TQ05 - Performance Analysis tidyquant Blog Article: Excel R - Pivot Tables, VLOOKUPs, !","code":""},{"path":"/index.html","id":"want-to-learn-tidyquant","dir":"","previous_headings":"","what":"Want to Learn tidyquant?","title":"Tidy Quantitative Financial Analysis","text":"Learning Lab #9: Performance Analysis & Portfolio Optimization tidyquant - 1-hour course tidyquant Learning Labs PRO Learning Lab #10: Building API plumber - Build stock optimization API plumber tidyquant Learning Lab #16: Stock Portfolio Optimization Nonlinear Programming - Use ROI package tidyquant calculate optimal minimum variance portfolios develop efficient frontier. Learning Lab #30: Shiny Financial Analysis Tidyquant API & Excel Pivot Tables - Learn use new Excel Functionality make Pivot Tables, VLOOKUPs, Sum-’s, !","code":""},{"path":"/reference/FANG.html","id":null,"dir":"Reference","previous_headings":"","what":"Stock prices for the ","title":"Stock prices for the ","text":"dataset containing daily historical stock prices \"FANG\" tech stocks, \"META\", \"AMZN\", \"NFLX\", \"GOOG\", spanning beginning 2013 end 2016.","code":""},{"path":"/reference/FANG.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Stock prices for the ","text":"","code":"FANG"},{"path":"/reference/FANG.html","id":"format","dir":"Reference","previous_headings":"","what":"Format","title":"Stock prices for the ","text":"\"tibble\" (\"tidy\" data frame) 4,032 rows 8 variables: symbol stock ticker symbol date trade date open stock price open trading, USD high stock price highest point trading, USD low stock price lowest point trading, USD close stock price close trading, USD volume number shares traded adjusted stock price close trading adjusted stock splits, USD","code":""},{"path":"/reference/FANG.html","id":"source","dir":"Reference","previous_headings":"","what":"Source","title":"Stock prices for the ","text":"https://www.investopedia.com/terms/f/fang-stocks-fb-amzn.asp","code":""},{"path":"/reference/av_api_key.html","id":null,"dir":"Reference","previous_headings":"","what":"Set Alpha Vantage API Key — av_api_key","title":"Set Alpha Vantage API Key — av_api_key","text":"Requires alphavantager packager use.","code":""},{"path":"/reference/av_api_key.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Set Alpha Vantage API Key — av_api_key","text":"","code":"av_api_key(api_key)"},{"path":"/reference/av_api_key.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Set Alpha Vantage API Key — av_api_key","text":"api_key Optionally passed parameter set Alpha Vantage api_key.","code":""},{"path":"/reference/av_api_key.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Set Alpha Vantage API Key — av_api_key","text":"Returns invisibly currently set api_key","code":""},{"path":"/reference/av_api_key.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Set Alpha Vantage API Key — av_api_key","text":"wrapper alphavantager::av_api_key()","code":""},{"path":[]},{"path":"/reference/av_api_key.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Set Alpha Vantage API Key — av_api_key","text":"","code":"if (FALSE) { if (rlang::is_installed(\"alphavantager\")) { av_api_key(api_key = \"foobar\") } }"},{"path":"/reference/coord_x_date.html","id":null,"dir":"Reference","previous_headings":"","what":"Zoom in on plot regions using date ranges or date-time ranges — coord_x_date","title":"Zoom in on plot regions using date ranges or date-time ranges — coord_x_date","text":"Zoom plot regions using date ranges date-time ranges","code":""},{"path":"/reference/coord_x_date.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Zoom in on plot regions using date ranges or date-time ranges — coord_x_date","text":"","code":"coord_x_date(xlim = NULL, ylim = NULL, expand = TRUE) coord_x_datetime(xlim = NULL, ylim = NULL, expand = TRUE)"},{"path":"/reference/coord_x_date.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Zoom in on plot regions using date ranges or date-time ranges — coord_x_date","text":"xlim Limits x axis, entered character dates \"YYYY-MM-DD\" format date \"YYYY-MM-DD HH:MM:SS\" date-time. ylim Limits y axis, entered values expand TRUE, default, adds small expansion factor limits ensure data axes overlap. FALSE, limits taken exactly data xlim/ylim.","code":""},{"path":"/reference/coord_x_date.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Zoom in on plot regions using date ranges or date-time ranges — coord_x_date","text":"coord_ functions prevent loss data zooming, necessary zooming plots calculate stats using data outside zoom range (e.g. plotting moving averages geom_ma()). Setting limits using scale_x_date changes underlying data causes moving averages fail. coord_x_date wrapper coord_cartesian enables quickly zooming plot regions using date range. coord_x_datetime wrapper coord_cartesian enables quickly zooming plot regions using date-time range.","code":""},{"path":[]},{"path":"/reference/coord_x_date.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Zoom in on plot regions using date ranges or date-time ranges — coord_x_date","text":"","code":"# Load libraries library(dplyr) #> #> ######################### 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: ‘dplyr’ #> The following objects are masked from ‘package:xts’: #> #> first, last #> The following objects are masked from ‘package:stats’: #> #> filter, lag #> The following objects are masked from ‘package:base’: #> #> intersect, setdiff, setequal, union library(ggplot2) # coord_x_date AAPL <- tq_get(\"AAPL\", from = \"2013-01-01\", to = \"2016-12-31\") AAPL %>% ggplot(aes(x = date, y = adjusted)) + geom_line() + # Plot stock price geom_ma(n = 50) + # Plot 50-day Moving Average geom_ma(n = 200, color = \"red\") + # Plot 200-day Moving Average # Zoom in coord_x_date(xlim = c(\"2016-01-01\", \"2016-12-31\")) # coord_x_datetime time_index <- seq(from = as.POSIXct(\"2012-05-15 07:00\"), to = as.POSIXct(\"2012-05-17 18:00\"), by = \"hour\") set.seed(1) value <- rnorm(n = length(time_index)) hourly_data <- tibble(time.index = time_index, value = value) hourly_data %>% ggplot(aes(x = time.index, y = value)) + geom_point() + coord_x_datetime(xlim = c(\"2012-05-15 07:00:00\", \"2012-05-15 16:00:00\"))"},{"path":"/reference/deprecated.html","id":null,"dir":"Reference","previous_headings":"","what":"Deprecated functions — deprecated","title":"Deprecated functions — deprecated","text":"record functions deprecated.","code":""},{"path":"/reference/deprecated.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Deprecated functions — deprecated","text":"","code":"tq_transform(data, ohlc_fun = OHLCV, mutate_fun, col_rename = NULL, ...) tq_transform_xy(data, x, y = NULL, mutate_fun, col_rename = NULL, ...)"},{"path":"/reference/deprecated.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Deprecated functions — deprecated","text":"data tibble (tidy data frame) data typically tq_get(). ohlc_fun Deprecated. Use select. mutate_fun mutation function either xts, quantmod, TTR package. Execute tq_mutate_fun_options() see full list options package. col_rename string character vector containing names can used quickly rename columns. ... Additional parameters passed appropriate mutatation function. x, y Parameters used _xy consist column names variables passed mutatation function (instead OHLC functions).","code":""},{"path":"/reference/deprecated.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Deprecated functions — deprecated","text":"tq_transform() - use tq_transmute() tq_transform_xy() - use tq_transmute_xy() as_xts() - use timetk::tk_xts() as_tibble() - use timetk::tk_tbl() summarise_by_time() - Moved timetk package. Use timetk::summarise_by_time()","code":""},{"path":"/reference/excel_date_functions.html","id":null,"dir":"Reference","previous_headings":"","what":"Excel Date and Time Functions — excel_date_functions","title":"Excel Date and Time Functions — excel_date_functions","text":"50+ date time functions familiar users coming Excel Background. main benefits : Integration amazing lubridate package handling dates times Integration Holidays timeDate Business Calendars New Date Math Date Sequence Functions factor Business Calendars (e.g. EOMONTH(), NET_WORKDAYS()) functions designed help users coming Excel background. functions replicate behavior Excel: Names cases match Excel function names Functionality replicates Excel default, missing values ignored (Excel)","code":""},{"path":"/reference/excel_date_functions.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Excel Date and Time Functions — excel_date_functions","text":"","code":"AS_DATE(x, ...) AS_DATETIME(x, ...) DATE(year, month, day) DATEVALUE(x, ...) YMD(x, ...) MDY(x, ...) DMY(x, ...) YMD_HMS(x, ...) MDY_HMS(x, ...) DMY_HMS(x, ...) YMD_HM(x, ...) MDY_HM(x, ...) DMY_HM(x, ...) YMD_H(x, ...) MDY_H(x, ...) DMY_H(x, ...) WEEKDAY(x, ..., label = FALSE, abbr = TRUE) WDAY(x, ..., label = FALSE, abbr = TRUE) DOW(x, ..., label = FALSE, abbr = TRUE) MONTHDAY(x, ...) MDAY(x, ...) DOM(x, ...) QUARTERDAY(x, ...) QDAY(x, ...) DAY(x, ...) WEEKNUM(x, ...) WEEK(x, ...) WEEKNUM_ISO(x, ...) MONTH(x, ..., label = FALSE, abbr = TRUE) QUARTER(x, ..., include_year = FALSE, fiscal_start = 1) YEAR(x, ...) YEAR_ISO(x, ...) DATE_TO_NUMERIC(x, ...) DATE_TO_DECIMAL(x, ...) SECOND(x, ...) MINUTE(x, ...) HOUR(x, ...) NOW(...) TODAY(...) EOMONTH(start_date, months = 0) EDATE(start_date, months = 0) NET_WORKDAYS(start_date, end_date, remove_weekends = TRUE, holidays = NULL) COUNT_DAYS(start_date, end_date) YEARFRAC(start_date, end_date) DATE_SEQUENCE(start_date, end_date, by = \"day\") WORKDAY_SEQUENCE(start_date, end_date, remove_weekends = TRUE, holidays = NULL) HOLIDAY_SEQUENCE( start_date, end_date, calendar = c(\"NYSE\", \"LONDON\", \"NERC\", \"TSX\", \"ZURICH\") ) HOLIDAY_TABLE(years, pattern = \".\") FLOOR_DATE(x, ..., by = \"day\") FLOOR_DAY(x, ...) FLOOR_WEEK(x, ...) FLOOR_MONTH(x, ...) FLOOR_QUARTER(x, ...) FLOOR_YEAR(x, ...) CEILING_DATE(x, ..., by = \"day\") CEILING_DAY(x, ...) CEILING_WEEK(x, ...) CEILING_MONTH(x, ...) CEILING_QUARTER(x, ...) CEILING_YEAR(x, ...) ROUND_DATE(x, ..., by = \"day\") ROUND_DAY(x, ...) ROUND_WEEK(x, ...) ROUND_MONTH(x, ...) ROUND_QUARTER(x, ...) ROUND_YEAR(x, ...)"},{"path":"/reference/excel_date_functions.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Excel Date and Time Functions — excel_date_functions","text":"x vector date date-time objects ... Parameters passed underlying lubridate functions. year Used DATE() month Used DATE() day Used DATE() label logical used MONTH() WEEKDAY() Date Extractors decide whether return names (ordered factors) numeric values. abbr logical used MONTH() WEEKDAY(). label = TRUE, used determine full names (e.g. Wednesday) abbreviated names (e.g. Wed) returned. include_year logicial value used QUARTER(). Determines whether return 2020 Q3 3 2020.3. fiscal_start numeric value used QUARTER(). Determines fiscal-year starting quarter. start_date Used Date Math Date Sequence operations. starting date calculation. months Used offset months EOMONTH() EDATE() Date Math calculations end_date Used Date Math Date Sequence operations. ending date calculation. remove_weekends logical value used Date Sequence Date Math calculations. Indicates whether weekends removed calculation. holidays vector dates corresponding holidays removed calculation. Used determine gap Date Sequence calculations value round Date Collapsing operations. Acceptable values : character string, containing one \"day\", \"week\", \"month\", \"quarter\" \"year\". calendar calendar used Date Sequence calculations Holidays timeDate package. Acceptable values : \"NYSE\", \"LONDON\", \"NERC\", \"TSX\", \"ZURICH\" years numeric vector years return Holidays HOLIDAY_TABLE() pattern Used filter Holidays (e.g. pattern = \"Easter\"). \"regular expression\" filtering pattern.","code":""},{"path":"/reference/excel_date_functions.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Excel Date and Time Functions — excel_date_functions","text":"Converters - Date date-time object length x Extractors - Returns information time-stamp. Current Time - Returns current date/date-time based locale. Date Math - Numeric values Date Values depending calculation. Date Sequences - Return vector dates Holiday Table (tibble). Date Collapsers - Date date-time object length x","code":""},{"path":"/reference/excel_date_functions.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Excel Date and Time Functions — excel_date_functions","text":"Converters - Make date date-time text (character data) General String--Date Conversion: AS_DATE(), AS_DATETIME() Format-Specific String--Date Conversion: YMD() (YYYY-MM-DD), MDY() (MM-DD-YYYY), DMY() (DD-MM-YYYY) Hour-Minute-Second Conversion: YMD_HMS(), YMD_HM(), friends. Extractors - Returns information time-stamp. Extractors: SECOND(), MINUTE(), HOUR(), DAY(), WEEK(), MONTH(), QUARTER(), YEAR() Current Time - Returns current date/date-time based locale. NOW(), TODAY() Date Math - Perform popular Excel date calculations EOMONTH() - End Month NET_WORKDAYS(), COUNT_DAYS() - Return number days 2 dates factoring working days holidays YEARFRAC() - Return fractional period year completed 2 dates. Date Sequences - Return vector dates Holiday Table (tibble). DATE_SEQUENCE(), WORKDAY_SEQUENCE(), HOLIDAY_SEQUENCE - Return sequence dates 2 dates factor workdays timeDate holiday calendars popular business calendars including NYSE London stock exchange. Date Collapsers - Collapse date sequence (useful dplyr::group_by() pivot_table()) FLOOR_DATE(), FLOOR_DAY(), FLOOR_WEEK(), FLOOR_MONTH(), FLOOR_QUARTER(), FLOOR_YEAR() Similar functions exist CEILING ROUND. wrappers lubridate functions.","code":""},{"path":"/reference/excel_date_functions.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Excel Date and Time Functions — excel_date_functions","text":"","code":"# Libraries library(lubridate) # --- Basic Usage ---- # Converters --- AS_DATE(\"2011 Jan-01\") # General #> [1] \"2011-01-01\" YMD(\"2011 Jan-01\") # Year, Month-Day Format #> [1] \"2011-01-01\" MDY(\"01-02-20\") # Month-Day, Year Format (January 2nd, 2020) #> [1] \"2020-01-02\" DMY(\"01-02-20\") # Day-Month, Year Format (February 1st, 2020) #> [1] \"2020-02-01\" # Extractors --- WEEKDAY(\"2020-01-01\") # Labelled Day #> [1] 4 WEEKDAY(\"2020-01-01\", label = FALSE) # Numeric Day #> [1] 4 WEEKDAY(\"2020-01-01\", label = FALSE, week_start = 1) # Start at 1 (Monday) vs 7 (Sunday) #> [1] 3 MONTH(\"2020-01-01\") #> [1] 1 QUARTER(\"2020-01-01\") #> [1] 1 YEAR(\"2020-01-01\") #> [1] 2020 # Current Date-Time --- NOW() #> [1] \"2023-10-01 00:11:35 UTC\" TODAY() #> [1] \"2023-10-01\" # Date Math --- EOMONTH(\"2020-01-01\") #> [1] \"2020-01-31\" EOMONTH(\"2020-01-01\", months = 1) #> [1] \"2020-02-29\" NET_WORKDAYS(\"2020-01-01\", \"2020-07-01\") # 131 Skipping Weekends #> [1] 131 NET_WORKDAYS(\"2020-01-01\", \"2020-07-01\", holidays = HOLIDAY_SEQUENCE(\"2020-01-01\", \"2020-07-01\", calendar = \"NYSE\")) # 126 Skipping 5 NYSE Holidays #> [1] 126 # Date Sequences --- DATE_SEQUENCE(\"2020-01-01\", \"2020-07-01\") #> [1] \"2020-01-01\" \"2020-01-02\" \"2020-01-03\" \"2020-01-04\" \"2020-01-05\" #> [6] \"2020-01-06\" \"2020-01-07\" \"2020-01-08\" \"2020-01-09\" \"2020-01-10\" #> [11] \"2020-01-11\" \"2020-01-12\" \"2020-01-13\" \"2020-01-14\" \"2020-01-15\" #> [16] \"2020-01-16\" \"2020-01-17\" \"2020-01-18\" \"2020-01-19\" \"2020-01-20\" #> [21] \"2020-01-21\" \"2020-01-22\" \"2020-01-23\" \"2020-01-24\" \"2020-01-25\" #> [26] \"2020-01-26\" \"2020-01-27\" \"2020-01-28\" \"2020-01-29\" \"2020-01-30\" #> [31] \"2020-01-31\" \"2020-02-01\" \"2020-02-02\" \"2020-02-03\" \"2020-02-04\" #> [36] \"2020-02-05\" \"2020-02-06\" \"2020-02-07\" \"2020-02-08\" \"2020-02-09\" #> [41] \"2020-02-10\" \"2020-02-11\" \"2020-02-12\" \"2020-02-13\" \"2020-02-14\" #> [46] \"2020-02-15\" \"2020-02-16\" \"2020-02-17\" \"2020-02-18\" \"2020-02-19\" #> [51] \"2020-02-20\" \"2020-02-21\" \"2020-02-22\" \"2020-02-23\" \"2020-02-24\" #> [56] \"2020-02-25\" \"2020-02-26\" \"2020-02-27\" \"2020-02-28\" \"2020-02-29\" #> [61] \"2020-03-01\" \"2020-03-02\" \"2020-03-03\" \"2020-03-04\" \"2020-03-05\" #> [66] \"2020-03-06\" \"2020-03-07\" \"2020-03-08\" \"2020-03-09\" \"2020-03-10\" #> [71] \"2020-03-11\" \"2020-03-12\" \"2020-03-13\" \"2020-03-14\" \"2020-03-15\" #> [76] \"2020-03-16\" \"2020-03-17\" \"2020-03-18\" \"2020-03-19\" \"2020-03-20\" #> [81] \"2020-03-21\" \"2020-03-22\" \"2020-03-23\" \"2020-03-24\" \"2020-03-25\" #> [86] \"2020-03-26\" \"2020-03-27\" \"2020-03-28\" \"2020-03-29\" \"2020-03-30\" #> [91] \"2020-03-31\" \"2020-04-01\" \"2020-04-02\" \"2020-04-03\" \"2020-04-04\" #> [96] \"2020-04-05\" \"2020-04-06\" \"2020-04-07\" \"2020-04-08\" \"2020-04-09\" #> [101] \"2020-04-10\" \"2020-04-11\" \"2020-04-12\" \"2020-04-13\" \"2020-04-14\" #> [106] \"2020-04-15\" \"2020-04-16\" \"2020-04-17\" \"2020-04-18\" \"2020-04-19\" #> [111] \"2020-04-20\" \"2020-04-21\" \"2020-04-22\" \"2020-04-23\" \"2020-04-24\" #> [116] \"2020-04-25\" \"2020-04-26\" \"2020-04-27\" \"2020-04-28\" \"2020-04-29\" #> [121] \"2020-04-30\" \"2020-05-01\" \"2020-05-02\" \"2020-05-03\" \"2020-05-04\" #> [126] \"2020-05-05\" \"2020-05-06\" \"2020-05-07\" \"2020-05-08\" \"2020-05-09\" #> [131] \"2020-05-10\" \"2020-05-11\" \"2020-05-12\" \"2020-05-13\" \"2020-05-14\" #> [136] \"2020-05-15\" \"2020-05-16\" \"2020-05-17\" \"2020-05-18\" \"2020-05-19\" #> [141] \"2020-05-20\" \"2020-05-21\" \"2020-05-22\" \"2020-05-23\" \"2020-05-24\" #> [146] \"2020-05-25\" \"2020-05-26\" \"2020-05-27\" \"2020-05-28\" \"2020-05-29\" #> [151] \"2020-05-30\" \"2020-05-31\" \"2020-06-01\" \"2020-06-02\" \"2020-06-03\" #> [156] \"2020-06-04\" \"2020-06-05\" \"2020-06-06\" \"2020-06-07\" \"2020-06-08\" #> [161] \"2020-06-09\" \"2020-06-10\" \"2020-06-11\" \"2020-06-12\" \"2020-06-13\" #> [166] \"2020-06-14\" \"2020-06-15\" \"2020-06-16\" \"2020-06-17\" \"2020-06-18\" #> [171] \"2020-06-19\" \"2020-06-20\" \"2020-06-21\" \"2020-06-22\" \"2020-06-23\" #> [176] \"2020-06-24\" \"2020-06-25\" \"2020-06-26\" \"2020-06-27\" \"2020-06-28\" #> [181] \"2020-06-29\" \"2020-06-30\" \"2020-07-01\" WORKDAY_SEQUENCE(\"2020-01-01\", \"2020-07-01\") #> [1] \"2020-01-01\" \"2020-01-02\" \"2020-01-03\" \"2020-01-06\" \"2020-01-07\" #> [6] \"2020-01-08\" \"2020-01-09\" \"2020-01-10\" \"2020-01-13\" \"2020-01-14\" #> [11] \"2020-01-15\" \"2020-01-16\" \"2020-01-17\" \"2020-01-20\" \"2020-01-21\" #> [16] \"2020-01-22\" \"2020-01-23\" \"2020-01-24\" \"2020-01-27\" \"2020-01-28\" #> [21] \"2020-01-29\" \"2020-01-30\" \"2020-01-31\" \"2020-02-03\" \"2020-02-04\" #> [26] \"2020-02-05\" \"2020-02-06\" \"2020-02-07\" \"2020-02-10\" \"2020-02-11\" #> [31] \"2020-02-12\" \"2020-02-13\" \"2020-02-14\" \"2020-02-17\" \"2020-02-18\" #> [36] \"2020-02-19\" \"2020-02-20\" \"2020-02-21\" \"2020-02-24\" \"2020-02-25\" #> [41] \"2020-02-26\" \"2020-02-27\" \"2020-02-28\" \"2020-03-02\" \"2020-03-03\" #> [46] \"2020-03-04\" \"2020-03-05\" \"2020-03-06\" \"2020-03-09\" \"2020-03-10\" #> [51] \"2020-03-11\" \"2020-03-12\" \"2020-03-13\" \"2020-03-16\" \"2020-03-17\" #> [56] \"2020-03-18\" \"2020-03-19\" \"2020-03-20\" \"2020-03-23\" \"2020-03-24\" #> [61] \"2020-03-25\" \"2020-03-26\" \"2020-03-27\" \"2020-03-30\" \"2020-03-31\" #> [66] \"2020-04-01\" \"2020-04-02\" \"2020-04-03\" \"2020-04-06\" \"2020-04-07\" #> [71] \"2020-04-08\" \"2020-04-09\" \"2020-04-10\" \"2020-04-13\" \"2020-04-14\" #> [76] \"2020-04-15\" \"2020-04-16\" \"2020-04-17\" \"2020-04-20\" \"2020-04-21\" #> [81] \"2020-04-22\" \"2020-04-23\" \"2020-04-24\" \"2020-04-27\" \"2020-04-28\" #> [86] \"2020-04-29\" \"2020-04-30\" \"2020-05-01\" \"2020-05-04\" \"2020-05-05\" #> [91] \"2020-05-06\" \"2020-05-07\" \"2020-05-08\" \"2020-05-11\" \"2020-05-12\" #> [96] \"2020-05-13\" \"2020-05-14\" \"2020-05-15\" \"2020-05-18\" \"2020-05-19\" #> [101] \"2020-05-20\" \"2020-05-21\" \"2020-05-22\" \"2020-05-25\" \"2020-05-26\" #> [106] \"2020-05-27\" \"2020-05-28\" \"2020-05-29\" \"2020-06-01\" \"2020-06-02\" #> [111] \"2020-06-03\" \"2020-06-04\" \"2020-06-05\" \"2020-06-08\" \"2020-06-09\" #> [116] \"2020-06-10\" \"2020-06-11\" \"2020-06-12\" \"2020-06-15\" \"2020-06-16\" #> [121] \"2020-06-17\" \"2020-06-18\" \"2020-06-19\" \"2020-06-22\" \"2020-06-23\" #> [126] \"2020-06-24\" \"2020-06-25\" \"2020-06-26\" \"2020-06-29\" \"2020-06-30\" #> [131] \"2020-07-01\" HOLIDAY_SEQUENCE(\"2020-01-01\", \"2020-07-01\", calendar = \"NYSE\") #> [1] \"2020-01-01\" \"2020-01-20\" \"2020-02-17\" \"2020-04-10\" \"2020-05-25\" WORKDAY_SEQUENCE(\"2020-01-01\", \"2020-07-01\", holidays = HOLIDAY_SEQUENCE(\"2020-01-01\", \"2020-07-01\", calendar = \"NYSE\")) #> [1] \"2020-01-02\" \"2020-01-03\" \"2020-01-06\" \"2020-01-07\" \"2020-01-08\" #> [6] \"2020-01-09\" \"2020-01-10\" \"2020-01-13\" \"2020-01-14\" \"2020-01-15\" #> [11] \"2020-01-16\" \"2020-01-17\" \"2020-01-21\" \"2020-01-22\" \"2020-01-23\" #> [16] \"2020-01-24\" \"2020-01-27\" \"2020-01-28\" \"2020-01-29\" \"2020-01-30\" #> [21] \"2020-01-31\" \"2020-02-03\" \"2020-02-04\" \"2020-02-05\" \"2020-02-06\" #> [26] \"2020-02-07\" \"2020-02-10\" \"2020-02-11\" \"2020-02-12\" \"2020-02-13\" #> [31] \"2020-02-14\" \"2020-02-18\" \"2020-02-19\" \"2020-02-20\" \"2020-02-21\" #> [36] \"2020-02-24\" \"2020-02-25\" \"2020-02-26\" \"2020-02-27\" \"2020-02-28\" #> [41] \"2020-03-02\" \"2020-03-03\" \"2020-03-04\" \"2020-03-05\" \"2020-03-06\" #> [46] \"2020-03-09\" \"2020-03-10\" \"2020-03-11\" \"2020-03-12\" \"2020-03-13\" #> [51] \"2020-03-16\" \"2020-03-17\" \"2020-03-18\" \"2020-03-19\" \"2020-03-20\" #> [56] \"2020-03-23\" \"2020-03-24\" \"2020-03-25\" \"2020-03-26\" \"2020-03-27\" #> [61] \"2020-03-30\" \"2020-03-31\" \"2020-04-01\" \"2020-04-02\" \"2020-04-03\" #> [66] \"2020-04-06\" \"2020-04-07\" \"2020-04-08\" \"2020-04-09\" \"2020-04-13\" #> [71] \"2020-04-14\" \"2020-04-15\" \"2020-04-16\" \"2020-04-17\" \"2020-04-20\" #> [76] \"2020-04-21\" \"2020-04-22\" \"2020-04-23\" \"2020-04-24\" \"2020-04-27\" #> [81] \"2020-04-28\" \"2020-04-29\" \"2020-04-30\" \"2020-05-01\" \"2020-05-04\" #> [86] \"2020-05-05\" \"2020-05-06\" \"2020-05-07\" \"2020-05-08\" \"2020-05-11\" #> [91] \"2020-05-12\" \"2020-05-13\" \"2020-05-14\" \"2020-05-15\" \"2020-05-18\" #> [96] \"2020-05-19\" \"2020-05-20\" \"2020-05-21\" \"2020-05-22\" \"2020-05-26\" #> [101] \"2020-05-27\" \"2020-05-28\" \"2020-05-29\" \"2020-06-01\" \"2020-06-02\" #> [106] \"2020-06-03\" \"2020-06-04\" \"2020-06-05\" \"2020-06-08\" \"2020-06-09\" #> [111] \"2020-06-10\" \"2020-06-11\" \"2020-06-12\" \"2020-06-15\" \"2020-06-16\" #> [116] \"2020-06-17\" \"2020-06-18\" \"2020-06-19\" \"2020-06-22\" \"2020-06-23\" #> [121] \"2020-06-24\" \"2020-06-25\" \"2020-06-26\" \"2020-06-29\" \"2020-06-30\" #> [126] \"2020-07-01\" # Date Collapsers --- FLOOR_DATE(AS_DATE(\"2020-01-15\"), by = \"month\") #> [1] \"2020-01-01\" CEILING_DATE(AS_DATE(\"2020-01-15\"), by = \"month\") #> [1] \"2020-02-01\" CEILING_DATE(AS_DATE(\"2020-01-15\"), by = \"month\") - ddays(1) # EOMONTH using lubridate #> [1] \"2020-01-31\" # --- Usage with tidyverse --- # Calculate returns by symbol/year/quarter FANG %>% pivot_table( .rows = c(symbol, ~ QUARTER(date)), .columns = ~ YEAR(date), .values = ~ PCT_CHANGE_FIRSTLAST(adjusted) ) #> # A tibble: 16 × 6 #> symbol `QUARTER(date)` `2013` `2014` `2015` `2016` #> #> 1 AMZN 1 0.0357 -0.155 0.206 -0.0681 #> 2 AMZN 2 0.0615 -0.0531 0.172 0.196 #> 3 AMZN 3 0.108 -0.0299 0.170 0.154 #> 4 AMZN 4 0.243 -0.0224 0.298 -0.104 #> 5 GOOG 1 0.0981 0.00174 0.0442 0.00419 #> 6 GOOG 2 0.0988 0.0143 -0.0406 -0.0771 #> 7 GOOG 3 -0.0135 -0.00911 0.166 0.112 #> 8 GOOG 4 0.263 -0.0737 0.241 -0.000958 #> 9 META 1 -0.0864 0.101 0.0481 0.116 #> 10 META 2 -0.0255 0.0746 0.0502 -0.0153 #> 11 META 3 1.02 0.161 0.0344 0.123 #> 12 META 4 0.0839 0.0192 0.151 -0.107 #> 13 NFLX 1 1.06 -0.0297 0.194 -0.0703 #> 14 NFLX 2 0.157 0.208 0.590 -0.135 #> 15 NFLX 3 0.379 -0.0463 0.103 0.0194 #> 16 NFLX 4 0.134 -0.221 0.0793 0.206"},{"path":"/reference/excel_financial_math_functions.html","id":null,"dir":"Reference","previous_headings":"","what":"Excel Financial Math Functions — excel_financial_math_functions","title":"Excel Financial Math Functions — excel_financial_math_functions","text":"Excel financial math functions designed easily calculate Net Present Value (NPV()), Future Value cashflow (FV()), Present Value future cashflow (PV()), . functions designed help users coming Excel background. functions replicate behavior Excel: Names similar Excel function names default, missing values ignored (Excel)","code":""},{"path":"/reference/excel_financial_math_functions.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Excel Financial Math Functions — excel_financial_math_functions","text":"","code":"NPV(cashflow, rate, nper = NULL) IRR(cashflow) FV(rate, nper, pv = 0, pmt = 0, type = 0) PV(rate, nper, fv = 0, pmt = 0, type = 0) PMT(rate, nper, pv, fv = 0, type = 0) RATE(nper, pmt, pv, fv = 0, type = 0)"},{"path":"/reference/excel_financial_math_functions.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Excel Financial Math Functions — excel_financial_math_functions","text":"cashflow Cash flow values. one value provided, assumed constant cash flow. rate One rate. one rate provided assumed constant rate. nper Number periods. `nper`` provided, cashflow values rate assumed constant. pv Present value. Initial investments (cash inflows) typcially negative value. pmt Number payments per period. type payments (pmt) occur beginning (type = 0) end (type = 1) period. fv Future value. Cash outflows typically positive value.","code":""},{"path":"/reference/excel_financial_math_functions.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Excel Financial Math Functions — excel_financial_math_functions","text":"Summary functions return single value","code":""},{"path":"/reference/excel_financial_math_functions.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Excel Financial Math Functions — excel_financial_math_functions","text":"Net Present Value (NPV) Net present value (NPV) difference present value cash inflows present value cash outflows period time. NPV used capital budgeting investment planning analyze profitability projected investment project. information, see Investopedia NPV. Internal Rate Return (IRR) internal rate return (IRR) metric used capital budgeting estimate profitability potential investments. internal rate return discount rate makes net present value (NPV) cash flows particular project equal zero. IRR calculations rely formula NPV . information, see Investopedia IRR. Future Value (FV) Future value (FV) value current asset future date based assumed rate growth. future value (FV) important investors financial planners use estimate much investment made today worth future. Knowing future value enables investors make sound investment decisions based anticipated needs. However, external economic factors, inflation, can adversely affect future value asset eroding value. information, see Investopedia FV. Present Value (PV) Present value (PV) current value future sum money stream cash flows given specified rate return. Future cash flows discounted discount rate, higher discount rate, lower present value future cash flows. Determining appropriate discount rate key properly valuing future cash flows, whether earnings obligations. information, see Investopedia PV. Payment (PMT) Payment PMT() function calculates payment loan based constant payments constant interest rate. Rate (RATE) Returns interest rate per period loan investment. example, use 6%/4 quarterly payments 6% APR.","code":""},{"path":"/reference/excel_financial_math_functions.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Excel Financial Math Functions — excel_financial_math_functions","text":"","code":"NPV(c(-1000, 250, 350, 450, 450), rate = 0.05) #> [1] 314.4986 IRR(c(-1000, 250, 350, 450, 450)) #> [1] 0.1656206 FV(rate = 0.05, nper = 5, pv = -100, pmt = 0, type = 0) #> [1] 127.6282 PV(rate = 0.05, nper = 5, fv = -100, pmt = 0, type = 0) #> [1] 78.35262 PMT(nper = 20, rate = 0.05, pv = -100, fv = 0, type = 0) #> [1] 8.024259 RATE(nper = 20, pmt = 8, pv = -100, fv = 0, type = 0) #> [1] 0.04964019"},{"path":"/reference/excel_if_functions.html","id":null,"dir":"Reference","previous_headings":"","what":"Excel Summarising ","title":"Excel Summarising ","text":"\"IFS\" functions filtering versions summarization counterparts. Simply add \"cases\" filter condition true. Multiple cases evaluated \"\" filtering operations. single case | (\"\") bars can created accomplish \"\". See details . functions designed help users coming Excel background. functions replicate behavior Excel: Names similar Excel function names default, missing values ignored (Excel)","code":""},{"path":"/reference/excel_if_functions.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Excel Summarising ","text":"","code":"SUM_IFS(x, ...) COUNT_IFS(x, ...) AVERAGE_IFS(x, ...) MEDIAN_IFS(x, ...) MIN_IFS(x, ...) MAX_IFS(x, ...) CREATE_IFS(.f, ...)"},{"path":"/reference/excel_if_functions.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Excel Summarising ","text":"x vector. functions designed numeric data. functions like COUNT_IFS() handle multiple data types. ... Add cases evaluate. See Details. .f function convert \"IFS\" function. Use ... case provide parameters .f like na.rm = TRUE.","code":""},{"path":"/reference/excel_if_functions.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Excel Summarising ","text":"Summary functions return single value","code":""},{"path":"/reference/excel_if_functions.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Excel Summarising ","text":"\"\" Filtering: Multiple cases evaluated \"\" filtering operations. \"\" Filtering: Compound single cases | (\"\") bars can created accomplish \"\". Simply use statement like x > 10 | x < -10 perform \"\" -statement. Creating New \"Summarizing IFS\" Functions: Users can create new \"IFS\" functions using CREATE_IFS() function factory. requirement output function (.f) must single value (scalar). See examples .","code":""},{"path":"/reference/excel_if_functions.html","id":"useful-functions","dir":"Reference","previous_headings":"","what":"Useful Functions","title":"Excel Summarising ","text":"Summary Functions - Return single value vector Sum: SUM_IFS() Center: AVERAGE_IFS(), MEDIAN_IFS() Count: COUNT_IFS() Range: MIN_IFS(), MAX_IFS() Create summary \"IFS\" function CREATE_IFS(): function factory generates summary \"_IFS\" functions.","code":""},{"path":"/reference/excel_if_functions.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Excel Summarising ","text":"","code":"library(dplyr) library(timetk) #> #> Attaching package: ‘timetk’ #> The following object is masked from ‘package:tidyquant’: #> #> FANG library(stringr) library(lubridate) # --- Basic Usage --- SUM_IFS(x = 1:10, x > 5) #> [1] 40 COUNT_IFS(x = letters, str_detect(x, \"a|b|c\")) #> [1] 3 SUM_IFS(-10:10, x > 8 | x < -5) #> [1] -21 # Create your own IFS function (Mind blowingly simple)! Q75_IFS <- CREATE_IFS(.f = quantile, probs = 0.75, na.rm = TRUE) Q75_IFS(1:10, x > 5) #> 75% #> 9 # --- Usage with tidyverse --- # Using multiple cases IFS cases to count the frequency of days with # high trade volume in a given year FANG %>% group_by(symbol) %>% summarise( high_volume_in_2015 = COUNT_IFS(volume, year(date) == 2015, volume > quantile(volume, 0.75)) ) #> # A tibble: 4 × 2 #> symbol high_volume_in_2015 #> #> 1 AMZN 62 #> 2 FB 15 #> 3 GOOG 19 #> 4 NFLX 54 # Count negative returns by month FANG %>% mutate(symbol = forcats::as_factor(symbol)) %>% group_by(symbol) %>% # Collapse from daily to FIRST value by month summarise_by_time( .date_var = date, .by = \"month\", adjusted = FIRST(adjusted) ) %>% # Calculate monthly returns group_by(symbol) %>% mutate( returns = PCT_CHANGE(adjusted, fill_na = 0) ) %>% # Find returns less than zero and count the frequency summarise( negative_monthly_returns = COUNT_IFS(returns, returns < 0) ) #> # A tibble: 4 × 2 #> symbol negative_monthly_returns #> #> 1 FB 16 #> 2 AMZN 16 #> 3 NFLX 16 #> 4 GOOG 20"},{"path":"/reference/excel_pivot_table.html","id":null,"dir":"Reference","previous_headings":"","what":"Excel Pivot Table — excel_pivot_table","title":"Excel Pivot Table — excel_pivot_table","text":"Pivot Table one Excel's powerful features, now available R! pivot table table statistics summarizes data extensive table (database, spreadsheet, business intelligence program). functions designed help users coming Excel background. functions replicate behavior Excel: Names similar Excel function names Functionality replicates Excel","code":""},{"path":"/reference/excel_pivot_table.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Excel Pivot Table — excel_pivot_table","text":"","code":"pivot_table( .data, .rows, .columns, .values, .filters = NULL, .sort = NULL, fill_na = NA )"},{"path":"/reference/excel_pivot_table.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Excel Pivot Table — excel_pivot_table","text":".data data.frame tibble contains data summarize pivot table .rows Enter one groups assess expressions (e.g. ~ MONTH(date_column)) .columns Enter one groups assess expressions (e.g. ~ YEAR(date_column)) .values Numeric . Enter one summarization expression(s) (e.g. ~ SUM(value_column)) .filters argument yet use .sort argument yet use fill_na value replace missing values . Default NA","code":""},{"path":"/reference/excel_pivot_table.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Excel Pivot Table — excel_pivot_table","text":"Returns tibble pivoted summarize information column row groupings","code":""},{"path":"/reference/excel_pivot_table.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Excel Pivot Table — excel_pivot_table","text":"summary might include sums, averages, statistics, pivot table groups together meaningful way. key parameters : .rows - groups appear row-wise headings summarization, can modify groups applying collapsing functions (e.g. (YEAR()). .columns - groups appear column headings summarization. can modify groups applying collapsing functions (e.g. (YEAR()). .values - numeric data summarized using summary function (e.g. SUM(), AVERAGE(), COUNT(), FIRST(), LAST(), SUM_IFS(), AVERAGE_IFS(), COUNT_IFS()) R implementation details. pivot_table() function powered tidyverse, ecosystem packages designed manipulate data. key parameters can expressed using functional form: Rows Column Groupings can collapsed. Example: .columns = ~ YEAR(order_date) Values can summarized provided single value returned. Example: .values = ~ SUM_IFS(order_volume >= quantile(order_volume, probs = 0.75)) Summarizations Row/Column Groupings can stacked (combined) c(). Example: .rows = c(~ YEAR(order_date), company) Bare columns (e.g. company) don need prefixed ~. grouping summarizing functions MUST prefixed ~. Example: .rows = ~ YEAR(order_date)","code":""},{"path":"/reference/excel_pivot_table.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Excel Pivot Table — excel_pivot_table","text":"","code":"# PIVOT TABLE ---- # Calculate returns by year/quarter FANG %>% pivot_table( .rows = c(symbol, ~ QUARTER(date)), .columns = ~ YEAR(date), .values = ~ PCT_CHANGE_FIRSTLAST(adjusted) ) #> # A tibble: 16 × 6 #> symbol `QUARTER(date)` `2013` `2014` `2015` `2016` #> #> 1 AMZN 1 0.0357 -0.155 0.206 -0.0681 #> 2 AMZN 2 0.0615 -0.0531 0.172 0.196 #> 3 AMZN 3 0.108 -0.0299 0.170 0.154 #> 4 AMZN 4 0.243 -0.0224 0.298 -0.104 #> 5 FB 1 -0.0864 0.101 0.0481 0.116 #> 6 FB 2 -0.0255 0.0746 0.0502 -0.0153 #> 7 FB 3 1.02 0.161 0.0344 0.123 #> 8 FB 4 0.0839 0.0192 0.151 -0.107 #> 9 GOOG 1 0.0981 0.00174 0.0442 0.00419 #> 10 GOOG 2 0.0988 0.0143 -0.0406 -0.0771 #> 11 GOOG 3 -0.0135 -0.00911 0.166 0.112 #> 12 GOOG 4 0.263 -0.0737 0.241 -0.000958 #> 13 NFLX 1 1.06 -0.0297 0.194 -0.0703 #> 14 NFLX 2 0.157 0.208 0.590 -0.135 #> 15 NFLX 3 0.379 -0.0463 0.103 0.0194 #> 16 NFLX 4 0.134 -0.221 0.0793 0.206"},{"path":"/reference/excel_ref_functions.html","id":null,"dir":"Reference","previous_headings":"","what":"Excel Reference Functions — excel_ref_functions","title":"Excel Reference Functions — excel_ref_functions","text":"Excel reference functions used efficiently lookup values data source. popular lookup function \"VLOOKUP\", implemented R. functions designed help users coming Excel background. functions replicate behavior Excel: Names similar Excel function names Functionality replicates Excel","code":""},{"path":"/reference/excel_ref_functions.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Excel Reference Functions — excel_ref_functions","text":"","code":"VLOOKUP(.lookup_values, .data, .lookup_column, .return_column)"},{"path":"/reference/excel_ref_functions.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Excel Reference Functions — excel_ref_functions","text":".lookup_values One lookup values. .data data.frame tibble contains values evaluate return .lookup_column column .data containing exact matching values .lookup_values .return_column column .data containing values return match found","code":""},{"path":"/reference/excel_ref_functions.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Excel Reference Functions — excel_ref_functions","text":"Returns vector length input lookup values","code":""},{"path":"/reference/excel_ref_functions.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Excel Reference Functions — excel_ref_functions","text":"VLOOKUP() Details Performs exact matching . Fuzzy matching implemented. Can return values one column . Use dplyr::left_join() perform table joining.","code":""},{"path":"/reference/excel_ref_functions.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Excel Reference Functions — excel_ref_functions","text":"","code":"library(dplyr) lookup_table <- tibble( stock = c(\"META\", \"AMZN\", \"NFLX\", \"GOOG\"), company = c(\"Facebook\", \"Amazon\", \"Netflix\", \"Google\") ) # --- Basic Usage --- VLOOKUP(\"NFLX\", .data = lookup_table, .lookup_column = stock, .return_column = company) #> [1] \"Netflix\" # --- Usage with tidyverse --- # Add company names to the stock data FANG %>% mutate(company = VLOOKUP(symbol, lookup_table, stock, company)) #> # A tibble: 4,032 × 9 #> symbol date open high low close volume adjusted company #> #> 1 FB 2013-01-02 27.4 28.2 27.4 28 69846400 28 NA #> 2 FB 2013-01-03 27.9 28.5 27.6 27.8 63140600 27.8 NA #> 3 FB 2013-01-04 28.0 28.9 27.8 28.8 72715400 28.8 NA #> 4 FB 2013-01-07 28.7 29.8 28.6 29.4 83781800 29.4 NA #> 5 FB 2013-01-08 29.5 29.6 28.9 29.1 45871300 29.1 NA #> 6 FB 2013-01-09 29.7 30.6 29.5 30.6 104787700 30.6 NA #> 7 FB 2013-01-10 30.6 31.5 30.3 31.3 95316400 31.3 NA #> 8 FB 2013-01-11 31.3 32.0 31.1 31.7 89598000 31.7 NA #> 9 FB 2013-01-14 32.1 32.2 30.6 31.0 98892800 31.0 NA #> 10 FB 2013-01-15 30.6 31.7 29.9 30.1 173242600 30.1 NA #> # ℹ 4,022 more rows"},{"path":"/reference/excel_stat_mutation_functions.html","id":null,"dir":"Reference","previous_headings":"","what":"Excel Statistical Mutation Functions — excel_stat_mutation_functions","title":"Excel Statistical Mutation Functions — excel_stat_mutation_functions","text":"15+ common statistical functions familiar users Excel (e.g. ABS(), SQRT()) modify / transform series values (.e. vector length input returned). functions designed help users coming Excel background. functions replicate behavior Excel: Names cases match Excel function names Functionality replicates Excel default, missing values ignored (Excel)","code":""},{"path":"/reference/excel_stat_mutation_functions.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Excel Statistical Mutation Functions — excel_stat_mutation_functions","text":"","code":"ABS(x) SQRT(x) LOG(x) EXP(x) RETURN(x, n = 1, fill_na = NA) PCT_CHANGE(x, n = 1, fill_na = NA) CHANGE(x, n = 1, fill_na = NA) LAG(x, n = 1, fill_na = NA) LEAD(x, n = 1, fill_na = NA) CUMULATIVE_SUM(x) CUMULATIVE_PRODUCT(x) CUMULATIVE_MAX(x) CUMULATIVE_MIN(x) CUMULATIVE_MEAN(x) CUMULATIVE_MEDIAN(x)"},{"path":"/reference/excel_stat_mutation_functions.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Excel Statistical Mutation Functions — excel_stat_mutation_functions","text":"x vector. functions designed numeric data. n Values offset. Used functions like LAG(), LEAD(), PCT_CHANGE() fill_na Fill missing (NA) values different value. Used offsetting functions.","code":""},{"path":"/reference/excel_stat_mutation_functions.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Excel Statistical Mutation Functions — excel_stat_mutation_functions","text":"Mutation functions return mutated / transformed version vector","code":""},{"path":"/reference/excel_stat_mutation_functions.html","id":"useful-functions","dir":"Reference","previous_headings":"","what":"Useful functions","title":"Excel Statistical Mutation Functions — excel_stat_mutation_functions","text":"Mutation Functions - Transforms vector Transformation: ABS(), SQRT(), LOG(), EXP() Lags & Change (Offsetting Functions): CHANGE(), PCT_CHANGE(), LAG(), LEAD() Cumulative Totals: CUMULATIVE_SUM(), CUMULATIVE_PRODUCT()","code":""},{"path":"/reference/excel_stat_mutation_functions.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Excel Statistical Mutation Functions — excel_stat_mutation_functions","text":"","code":"# Libraries library(timetk) library(dplyr) # --- Basic Usage ---- CUMULATIVE_SUM(1:10) #> [1] 1 3 6 10 15 21 28 36 45 55 PCT_CHANGE(c(21, 24, 22, 25), fill_na = 0) #> [1] 0.00000000 0.14285714 -0.08333333 0.13636364 # --- Usage with tidyverse --- # Go from daily to monthly periodicity, # then calculate returns and growth of $1 USD FANG %>% mutate(symbol = forcats::as_factor(symbol)) %>% group_by(symbol) %>% # Summarization - Collapse from daily to FIRST value by month summarise_by_time( .date_var = date, .by = \"month\", adjusted = FIRST(adjusted) ) %>% # Mutation - Calculate monthly returns and cumulative growth of $1 USD group_by(symbol) %>% mutate( returns = PCT_CHANGE(adjusted, fill_na = 0), growth = CUMULATIVE_SUM(returns) + 1 ) #> # A tibble: 192 × 5 #> # Groups: symbol [4] #> symbol date adjusted returns growth #> #> 1 FB 2013-01-01 28 0 1 #> 2 FB 2013-02-01 29.7 0.0618 1.06 #> 3 FB 2013-03-01 27.8 -0.0656 0.996 #> 4 FB 2013-04-01 25.5 -0.0810 0.915 #> 5 FB 2013-05-01 27.4 0.0744 0.990 #> 6 FB 2013-06-01 23.8 -0.131 0.859 #> 7 FB 2013-07-01 24.8 0.0403 0.899 #> 8 FB 2013-08-01 37.5 0.511 1.41 #> 9 FB 2013-09-01 41.9 0.117 1.53 #> 10 FB 2013-10-01 50.4 0.204 1.73 #> # ℹ 182 more rows"},{"path":"/reference/excel_stat_summary_functions.html","id":null,"dir":"Reference","previous_headings":"","what":"Excel Statistical Summary Functions — excel_stat_summary_functions","title":"Excel Statistical Summary Functions — excel_stat_summary_functions","text":"15+ common statistical functions familiar users Excel (e.g. SUM(), AVERAGE()). functions return single value (.e. vector length 1). functions designed help users coming Excel background. functions replicate behavior Excel: Names cases match Excel function names Functionality replicates Excel default, missing values ignored (Excel)","code":""},{"path":"/reference/excel_stat_summary_functions.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Excel Statistical Summary Functions — excel_stat_summary_functions","text":"","code":"SUM(x) AVERAGE(x) MEDIAN(x) MIN(x) MAX(x) COUNT(x) COUNT_UNIQUE(x) STDEV(x) VAR(x) COR(x, y) COV(x, y) FIRST(x) LAST(x) NTH(x, n = 1) CHANGE_FIRSTLAST(x) PCT_CHANGE_FIRSTLAST(x)"},{"path":"/reference/excel_stat_summary_functions.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Excel Statistical Summary Functions — excel_stat_summary_functions","text":"x vector. functions designed numeric data. functions like COUNT() handle multiple data types. y vector. Used functions requiring 2 inputs. n single value used NTH() select specific element location return.","code":""},{"path":"/reference/excel_stat_summary_functions.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Excel Statistical Summary Functions — excel_stat_summary_functions","text":"Summary functions return single value","code":""},{"path":"/reference/excel_stat_summary_functions.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Excel Statistical Summary Functions — excel_stat_summary_functions","text":"Summary Functions functions remove missing values (NA). behavior Excel commonly desired.","code":""},{"path":"/reference/excel_stat_summary_functions.html","id":"useful-functions","dir":"Reference","previous_headings":"","what":"Useful functions","title":"Excel Statistical Summary Functions — excel_stat_summary_functions","text":"Summary Functions - Return single value vector Sum: SUM() Center: AVERAGE(), MEDIAN() Spread: STDEV(), VAR() Range: MIN(), MAX() Count: COUNT(), COUNT_UNIQUE() Position: FIRST(), LAST(), NTH() Change (Summary): CHANGE_FIRSTLAST(), PCT_CHANGE_FIRSTLAST() Correlation: COR(), COV()","code":""},{"path":"/reference/excel_stat_summary_functions.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Excel Statistical Summary Functions — excel_stat_summary_functions","text":"","code":"# Libraries library(timetk) library(forcats) library(dplyr) # --- Basic Usage ---- SUM(1:10) #> [1] 55 PCT_CHANGE_FIRSTLAST(c(21, 24, 22, 25)) #> [1] 0.1904762 # --- Usage with tidyverse --- # Go from daily to monthly periodicity, # then calculate returns and growth of $1 USD FANG %>% mutate(symbol = forcats::as_factor(symbol)) %>% group_by(symbol) %>% # Summarization - Collapse from daily to FIRST value by month summarise_by_time( .date_var = date, .by = \"month\", adjusted = FIRST(adjusted) ) #> # A tibble: 192 × 3 #> # Groups: symbol [4] #> symbol date adjusted #> #> 1 FB 2013-01-01 28 #> 2 FB 2013-02-01 29.7 #> 3 FB 2013-03-01 27.8 #> 4 FB 2013-04-01 25.5 #> 5 FB 2013-05-01 27.4 #> 6 FB 2013-06-01 23.8 #> 7 FB 2013-07-01 24.8 #> 8 FB 2013-08-01 37.5 #> 9 FB 2013-09-01 41.9 #> 10 FB 2013-10-01 50.4 #> # ℹ 182 more rows"},{"path":"/reference/geom_bbands.html","id":null,"dir":"Reference","previous_headings":"","what":"Plot Bollinger Bands using Moving Averages — geom_bbands","title":"Plot Bollinger Bands using Moving Averages — geom_bbands","text":"Bollinger Bands plot range around moving average typically two standard deviations . geom_bbands() function enables plotting Bollinger Bands quickly using various moving average functions. moving average functions used specified TTR::SMA() TTR package. Use coord_x_date() zoom specific plot regions. following moving averages available: Simple moving averages (SMA): Rolling mean period defined n. Exponential moving averages (EMA): Includes exponentially-weighted mean gives weight recent observations. Uses wilder ratio args. Weighted moving averages (WMA): Uses set weights, wts, weight observations moving average. Double exponential moving averages (DEMA): Uses v volume factor, wilder ratio args. Zero-lag exponential moving averages (ZLEMA): Uses wilder ratio args. Volume-weighted moving averages (VWMA): Requires volume aesthetic. Elastic, volume-weighted moving averages (EVWMA): Requires volume aesthetic.","code":""},{"path":"/reference/geom_bbands.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Plot Bollinger Bands using Moving Averages — geom_bbands","text":"","code":"geom_bbands( mapping = NULL, data = NULL, position = \"identity\", na.rm = TRUE, show.legend = NA, inherit.aes = TRUE, ma_fun = SMA, n = 20, sd = 2, wilder = FALSE, ratio = NULL, v = 1, wts = 1:n, color_ma = \"darkblue\", color_bands = \"red\", alpha = 0.15, fill = \"grey20\", ... ) geom_bbands_( mapping = NULL, data = NULL, position = \"identity\", na.rm = TRUE, show.legend = NA, inherit.aes = TRUE, ma_fun = \"SMA\", n = 10, sd = 2, wilder = FALSE, ratio = NULL, v = 1, wts = 1:n, color_ma = \"darkblue\", color_bands = \"red\", alpha = 0.15, fill = \"grey20\", ... )"},{"path":"/reference/geom_bbands.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Plot Bollinger Bands using Moving Averages — geom_bbands","text":"mapping Set aesthetic mappings created ggplot2::aes() ggplot2::aes_(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot2::ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See ggplot2::fortify() variables created. function called single argument, plot data. return value must data.frame., used layer data. position Position adjustment, either string naming adjustment (e.g. \"jitter\" use position_jitter), result call position adjustment function. Use latter need change settings adjustment. na.rm TRUE, silently removes NA values, typically desired moving averages. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. ggplot2::borders(). ma_fun function used calculate moving average. Seven options available including: SMA, EMA, WMA, DEMA, ZLEMA, VWMA, EVWMA. default SMA. See TTR::SMA() underlying functions. n Number periods average . Must 1 nrow(x), inclusive. sd number standard deviations use. wilder logical; TRUE, Welles Wilder type EMA calculated; see notes. ratio smoothing/decay ratio. ratio overrides wilder EMA, provides additional smoothing VMA. v 'volume factor' (number [0,1]). See Notes. wts Vector weights. Length wts vector must equal length x, n (default). color_ma, color_bands Select line color applied moving average line Bollinger band line. alpha Used adjust alpha transparency BBand ribbon. fill Used adjust fill color BBand ribbon. ... arguments passed ggplot2::layer(). often aesthetics, used set aesthetic fixed value, like color = \"red\" size = 3. may also parameters paired geom/stat.","code":""},{"path":"/reference/geom_bbands.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Plot Bollinger Bands using Moving Averages — geom_bbands","text":"following aesthetics understood (required bold): x, Typically date high, Required high price low, Required low price close, Required close price volume, Required VWMA EVWMA colour, Affects line colors fill, Affects ribbon fill color alpha, Affects ribbon alpha value group linetype size","code":""},{"path":[]},{"path":"/reference/geom_bbands.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Plot Bollinger Bands using Moving Averages — geom_bbands","text":"","code":"library(dplyr) library(ggplot2) AAPL <- tq_get(\"AAPL\", from = \"2013-01-01\", to = \"2016-12-31\") # SMA AAPL %>% ggplot(aes(x = date, y = close)) + geom_line() + # Plot stock price geom_bbands(aes(high = high, low = low, close = close), ma_fun = SMA, n = 50) + coord_x_date(xlim = c(as_date(\"2016-12-31\") - dyears(1), as_date(\"2016-12-31\")), ylim = c(75, 125)) #> Warning: The following aesthetics were dropped during statistical transformation: high, #> low, close, y #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor? #> Warning: The following aesthetics were dropped during statistical transformation: high, #> low, close #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor? # EMA AAPL %>% ggplot(aes(x = date, y = close)) + geom_line() + # Plot stock price geom_bbands(aes(high = high, low = low, close = close), ma_fun = EMA, wilder = TRUE, ratio = NULL, n = 50) + coord_x_date(xlim = c(as_date(\"2016-12-31\") - dyears(1), as_date(\"2016-12-31\")), ylim = c(75, 125)) #> Warning: The following aesthetics were dropped during statistical transformation: high, #> low, close, y #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor? #> Warning: The following aesthetics were dropped during statistical transformation: high, #> low, close #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor? # VWMA AAPL %>% ggplot(aes(x = date, y = close)) + geom_line() + # Plot stock price geom_bbands(aes(high = high, low = low, close = close, volume = volume), ma_fun = VWMA, n = 50) + coord_x_date(xlim = c(as_date(\"2016-12-31\") - dyears(1), as_date(\"2016-12-31\")), ylim = c(75, 125)) #> Warning: The following aesthetics were dropped during statistical transformation: high, #> low, close, volume, y #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor? #> Warning: The following aesthetics were dropped during statistical transformation: high, #> low, close, volume #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor?"},{"path":"/reference/geom_chart.html","id":null,"dir":"Reference","previous_headings":"","what":"Plot Financial Charts in ggplot2 — geom_chart","title":"Plot Financial Charts in ggplot2 — geom_chart","text":"Financial charts provide visual cues open, high, low, close prices. Use coord_x_date() zoom specific plot regions. following financial chart geoms available: Bar Chart Candlestick Chart","code":""},{"path":"/reference/geom_chart.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Plot Financial Charts in ggplot2 — geom_chart","text":"","code":"geom_barchart( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", na.rm = TRUE, show.legend = NA, inherit.aes = TRUE, colour_up = \"darkblue\", colour_down = \"red\", fill_up = \"darkblue\", fill_down = \"red\", ... ) geom_candlestick( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", na.rm = TRUE, show.legend = NA, inherit.aes = TRUE, colour_up = \"darkblue\", colour_down = \"red\", fill_up = \"darkblue\", fill_down = \"red\", ... )"},{"path":"/reference/geom_chart.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Plot Financial Charts in ggplot2 — geom_chart","text":"mapping Set aesthetic mappings created ggplot2::aes() ggplot2::aes_(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot2::ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See ggplot2::fortify() variables created. function called single argument, plot data. return value must data.frame., used layer data. stat statistical transformation use data layer, either ggproto Geom subclass string naming stat stripped stat_ prefix (e.g. \"count\" rather \"stat_count\") position Position adjustment, either string naming adjustment (e.g. \"jitter\" use position_jitter), result call position adjustment function. Use latter need change settings adjustment. na.rm TRUE, silently removes NA values, typically desired moving averages. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. ggplot2::borders(). colour_up, colour_down Select colors applied based price movement open close. close >= open, colour_up used. Otherwise, colour_down used. default \"darkblue\" \"red\", respectively. fill_up, fill_down Select fills applied based price movement open close. close >= open, fill_up used. Otherwise, fill_down used. default \"darkblue\" \"red\", respectively. affects geom_candlestick. ... arguments passed ggplot2::layer(). often aesthetics, used set aesthetic fixed value, like color = \"red\" size = 3. may also parameters paired geom/stat.","code":""},{"path":"/reference/geom_chart.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Plot Financial Charts in ggplot2 — geom_chart","text":"following aesthetics understood (required bold): x, Typically date open, Required open price high, Required high price low, Required low price close, Required close price alpha group linetype size","code":""},{"path":[]},{"path":"/reference/geom_chart.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Plot Financial Charts in ggplot2 — geom_chart","text":"","code":"library(dplyr) library(ggplot2) AAPL <- tq_get(\"AAPL\", from = \"2013-01-01\", to = \"2016-12-31\") # Bar Chart AAPL %>% ggplot(aes(x = date, y = close)) + geom_barchart(aes(open = open, high = high, low = low, close = close)) + geom_ma(color = \"darkgreen\") + coord_x_date(xlim = c(\"2016-01-01\", \"2016-12-31\"), ylim = c(75, 125)) #> Warning: The following aesthetics were dropped during statistical transformation: open, #> high, low, close, y #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor? #> Warning: The following aesthetics were dropped during statistical transformation: open, #> high, low, close #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor? #> Warning: The following aesthetics were dropped during statistical transformation: open, #> high, low, close #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor? # Candlestick Chart AAPL %>% ggplot(aes(x = date, y = close)) + geom_candlestick(aes(open = open, high = high, low = low, close = close)) + geom_ma(color = \"darkgreen\") + coord_x_date(xlim = c(\"2016-01-01\", \"2016-12-31\"), ylim = c(75, 125)) #> Warning: The following aesthetics were dropped during statistical transformation: open, #> high, low, close, y #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor? #> Warning: The following aesthetics were dropped during statistical transformation: x, #> open, high, low, close, y #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor?"},{"path":"/reference/geom_ma.html","id":null,"dir":"Reference","previous_headings":"","what":"Plot moving averages — geom_ma","title":"Plot moving averages — geom_ma","text":"underlying moving average functions used specified TTR::SMA() TTR package. Use coord_x_date() zoom specific plot regions. following moving averages available: Simple moving averages (SMA): Rolling mean period defined n. Exponential moving averages (EMA): Includes exponentially-weighted mean gives weight recent observations. Uses wilder ratio args. Weighted moving averages (WMA): Uses set weights, wts, weight observations moving average. Double exponential moving averages (DEMA): Uses v volume factor, wilder ratio args. Zero-lag exponential moving averages (ZLEMA): Uses wilder ratio args. Volume-weighted moving averages (VWMA): Requires volume aesthetic. Elastic, volume-weighted moving averages (EVWMA): Requires volume aesthetic.","code":""},{"path":"/reference/geom_ma.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Plot moving averages — geom_ma","text":"","code":"geom_ma( mapping = NULL, data = NULL, position = \"identity\", na.rm = TRUE, show.legend = NA, inherit.aes = TRUE, ma_fun = SMA, n = 20, wilder = FALSE, ratio = NULL, v = 1, wts = 1:n, ... ) geom_ma_( mapping = NULL, data = NULL, position = \"identity\", na.rm = TRUE, show.legend = NA, inherit.aes = TRUE, ma_fun = \"SMA\", n = 20, wilder = FALSE, ratio = NULL, v = 1, wts = 1:n, ... )"},{"path":"/reference/geom_ma.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Plot moving averages — geom_ma","text":"mapping Set aesthetic mappings created ggplot2::aes() ggplot2::aes_(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot2::ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See ggplot2::fortify() variables created. function called single argument, plot data. return value must data.frame., used layer data. position Position adjustment, either string naming adjustment (e.g. \"jitter\" use position_jitter), result call position adjustment function. Use latter need change settings adjustment. na.rm TRUE, silently removes NA values, typically desired moving averages. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. ggplot2::borders(). ma_fun function used calculate moving average. Seven options available including: SMA, EMA, WMA, DEMA, ZLEMA, VWMA, EVWMA. default SMA. See TTR::SMA() underlying functions. n Number periods average . Must 1 nrow(x), inclusive. wilder logical; TRUE, Welles Wilder type EMA calculated; see notes. ratio smoothing/decay ratio. ratio overrides wilder EMA, provides additional smoothing VMA. v 'volume factor' (number [0,1]). See Notes. wts Vector weights. Length wts vector must equal length x, n (default). ... arguments passed ggplot2::layer(). often aesthetics, used set aesthetic fixed value, like color = \"red\" size = 3. may also parameters paired geom/stat.","code":""},{"path":"/reference/geom_ma.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Plot moving averages — geom_ma","text":"following aesthetics understood (required bold): x y volume, Required VWMA EVWMA alpha colour group linetype linewidth size","code":""},{"path":[]},{"path":"/reference/geom_ma.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Plot moving averages — geom_ma","text":"","code":"library(dplyr) library(ggplot2) AAPL <- tq_get(\"AAPL\", from = \"2013-01-01\", to = \"2016-12-31\") # SMA AAPL %>% ggplot(aes(x = date, y = adjusted)) + geom_line() + # Plot stock price geom_ma(ma_fun = SMA, n = 50) + # Plot 50-day SMA geom_ma(ma_fun = SMA, n = 200, color = \"red\") + # Plot 200-day SMA coord_x_date(xlim = c(\"2016-01-01\", \"2016-12-31\"), ylim = c(75, 125)) # Zoom in # EVWMA AAPL %>% ggplot(aes(x = date, y = adjusted)) + geom_line() + # Plot stock price geom_ma(aes(volume = volume), ma_fun = EVWMA, n = 50) + # Plot 50-day EVWMA coord_x_date(xlim = c(\"2016-01-01\", \"2016-12-31\"), ylim = c(75, 125)) # Zoom in #> Warning: The following aesthetics were dropped during statistical transformation: volume #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor?"},{"path":"/reference/palette_tq.html","id":null,"dir":"Reference","previous_headings":"","what":"tidyquant palettes for use with scales — palette_tq","title":"tidyquant palettes for use with scales — palette_tq","text":"palettes mainly called internally tidyquant scale_*_tq() functions.","code":""},{"path":"/reference/palette_tq.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"tidyquant palettes for use with scales — palette_tq","text":"","code":"palette_light() palette_dark() palette_green()"},{"path":"/reference/palette_tq.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"tidyquant palettes for use with scales — palette_tq","text":"","code":"library(scales) scales::show_col(palette_light())"},{"path":"/reference/pipe.html","id":null,"dir":"Reference","previous_headings":"","what":"Pipe operator — %>%","title":"Pipe operator — %>%","text":"See magrittr::%>% details.","code":""},{"path":"/reference/pipe.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Pipe operator — %>%","text":"","code":"lhs %>% rhs"},{"path":"/reference/quandl_api_key.html","id":null,"dir":"Reference","previous_headings":"","what":"Query or set Quandl API Key — quandl_api_key","title":"Query or set Quandl API Key — quandl_api_key","text":"Query set Quandl API Key","code":""},{"path":"/reference/quandl_api_key.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Query or set Quandl API Key — quandl_api_key","text":"","code":"quandl_api_key(api_key)"},{"path":"/reference/quandl_api_key.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Query or set Quandl API Key — quandl_api_key","text":"api_key Optionally passed parameter set Quandl api_key.","code":""},{"path":"/reference/quandl_api_key.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Query or set Quandl API Key — quandl_api_key","text":"Returns invisibly currently set api_key","code":""},{"path":"/reference/quandl_api_key.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Query or set Quandl API Key — quandl_api_key","text":"wrapper Quandl::Quandl.api_key()","code":""},{"path":[]},{"path":"/reference/quandl_api_key.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Query or set Quandl API Key — quandl_api_key","text":"","code":"if (FALSE) { if (rlang::is_installed(\"Quandl\")) { quandl_api_key(api_key = \"foobar\") } }"},{"path":"/reference/quandl_search.html","id":null,"dir":"Reference","previous_headings":"","what":"Search the Quandl database — quandl_search","title":"Search the Quandl database — quandl_search","text":"Search Quandl database","code":""},{"path":"/reference/quandl_search.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Search the Quandl database — quandl_search","text":"","code":"quandl_search(query, silent = FALSE, per_page = 10, ...)"},{"path":"/reference/quandl_search.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Search the Quandl database — quandl_search","text":"query Search terms silent Prints results FALSE. per_page Number results returned per page. ... Additional named values interpretted Quandl API parameters.","code":""},{"path":"/reference/quandl_search.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Search the Quandl database — quandl_search","text":"Returns tibble search results.","code":""},{"path":"/reference/quandl_search.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Search the Quandl database — quandl_search","text":"wrapper Quandl::Quandl.search()","code":""},{"path":[]},{"path":"/reference/quandl_search.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Search the Quandl database — quandl_search","text":"","code":"if (FALSE) { quandl_search(query = \"oil\") }"},{"path":"/reference/scale_manual.html","id":null,"dir":"Reference","previous_headings":"","what":"tidyquant colors and fills for ggplot2. — scale_manual","title":"tidyquant colors and fills for ggplot2. — scale_manual","text":"tidyquant scales add colors work nicely theme_tq().","code":""},{"path":"/reference/scale_manual.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"tidyquant colors and fills for ggplot2. — scale_manual","text":"","code":"scale_color_tq(..., theme = \"light\") scale_colour_tq(..., theme = \"light\") scale_fill_tq(..., theme = \"light\")"},{"path":"/reference/scale_manual.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"tidyquant colors and fills for ggplot2. — scale_manual","text":"... common discrete scale parameters: name, breaks, labels, na.value, limits guide. See discrete_scale() details theme one \"light\", \"dark\", \"green\". match theme_tq() used .","code":""},{"path":"/reference/scale_manual.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"tidyquant colors and fills for ggplot2. — scale_manual","text":"scale_color_tq use color specified aes() ggplot. scale_fill_tq use fill specified aes() ggplot.","code":""},{"path":[]},{"path":"/reference/scale_manual.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"tidyquant colors and fills for ggplot2. — scale_manual","text":"","code":"# Load libraries library(dplyr) library(ggplot2) # Get stock prices stocks <- c(\"AAPL\", \"META\", \"NFLX\") %>% tq_get(from = \"2013-01-01\", to = \"2017-01-01\") # Plot for stocks g <- stocks %>% ggplot(aes(date, adjusted, color = symbol)) + geom_line() + labs(title = \"Multi stock example\", xlab = \"Date\", ylab = \"Adjusted Close\") # Plot with tidyquant theme and colors g + theme_tq() + scale_color_tq()"},{"path":"/reference/theme_tq.html","id":null,"dir":"Reference","previous_headings":"","what":"tidyquant themes for ggplot2. — theme_tq","title":"tidyquant themes for ggplot2. — theme_tq","text":"theme_tq() function creates custom theme using tidyquant colors.","code":""},{"path":"/reference/theme_tq.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"tidyquant themes for ggplot2. — theme_tq","text":"","code":"theme_tq(base_size = 11, base_family = \"\") theme_tq_dark(base_size = 11, base_family = \"\") theme_tq_green(base_size = 11, base_family = \"\")"},{"path":"/reference/theme_tq.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"tidyquant themes for ggplot2. — theme_tq","text":"base_size base font size, given pts. base_family base font family","code":""},{"path":[]},{"path":"/reference/theme_tq.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"tidyquant themes for ggplot2. — theme_tq","text":"","code":"# Load libraries library(dplyr) library(ggplot2) # Get stock prices AAPL <- tq_get(\"AAPL\", from = \"2013-01-01\", to = \"2016-12-31\") # Plot using ggplot with theme_tq AAPL %>% ggplot(aes(x = date, y = close)) + geom_line() + geom_bbands(aes(high = high, low = low, close = close), ma_fun = EMA, wilder = TRUE, ratio = NULL, n = 50) + coord_x_date(xlim = c(\"2016-01-01\", \"2016-12-31\"), ylim = c(75, 125)) + labs(title = \"Apple BBands\", x = \"Date\", y = \"Price\") + theme_tq() #> Warning: The following aesthetics were dropped during statistical transformation: high, #> low, close, y #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor? #> Warning: The following aesthetics were dropped during statistical transformation: high, #> low, close #> ℹ This can happen when ggplot fails to infer the correct grouping structure in #> the data. #> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical #> variable into a factor?"},{"path":"/reference/tidyquant-package.html","id":null,"dir":"Reference","previous_headings":"","what":"tidyquant: Integrating quantitative financial analysis tools with the tidyverse — tidyquant-package","title":"tidyquant: Integrating quantitative financial analysis tools with the tidyverse — tidyquant-package","text":"main advantage tidyquant bridge gap best quantitative resources collecting manipulating quantitative data, xts, quantmod TTR, data modeling workflow infrastructure tidyverse.","code":""},{"path":"/reference/tidyquant-package.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"tidyquant: Integrating quantitative financial analysis tools with the tidyverse — tidyquant-package","text":"package, tidyquant functions supporting data sets provided seamlessly combine tidy tools existing quantitative analytics packages. main advantage able use tidy functions purrr mapping tidyr nesting extend modeling many stocks. See tidyquant website information, documentation examples. Users probably interested following: Getting Data Web: tq_get() Manipulating Data: tq_transmute() tq_mutate() Performance Analysis Portfolio Aggregation: tq_performance() tq_portfolio() learn tidyquant, start vignettes: browseVignettes(package = \"tidyquant\")","code":""},{"path":[]},{"path":"/reference/tidyquant-package.html","id":"author","dir":"Reference","previous_headings":"","what":"Author","title":"tidyquant: Integrating quantitative financial analysis tools with the tidyverse — tidyquant-package","text":"Maintainer: Matt Dancho mdancho@business-science.io Authors: Davis Vaughan dvaughan@business-science.io","code":""},{"path":"/reference/tiingo_api_key.html","id":null,"dir":"Reference","previous_headings":"","what":"Set Tiingo API Key — tiingo_api_key","title":"Set Tiingo API Key — tiingo_api_key","text":"Requires riingo package installled.","code":""},{"path":"/reference/tiingo_api_key.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Set Tiingo API Key — tiingo_api_key","text":"","code":"tiingo_api_key(api_key)"},{"path":"/reference/tiingo_api_key.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Set Tiingo API Key — tiingo_api_key","text":"api_key Optionally passed parameter set Tiingo api_key.","code":""},{"path":"/reference/tiingo_api_key.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Set Tiingo API Key — tiingo_api_key","text":"Returns invisibly currently set api_key","code":""},{"path":"/reference/tiingo_api_key.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Set Tiingo API Key — tiingo_api_key","text":"wrapper riingo::ringo_set_token()","code":""},{"path":[]},{"path":"/reference/tiingo_api_key.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Set Tiingo API Key — tiingo_api_key","text":"","code":"if (FALSE) { tiingo_api_key(api_key = \"foobar\") }"},{"path":"/reference/tq_get.html","id":null,"dir":"Reference","previous_headings":"","what":"Get quantitative data in tibble format — tq_get","title":"Get quantitative data in tibble format — tq_get","text":"Get quantitative data tibble format","code":""},{"path":"/reference/tq_get.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get quantitative data in tibble format — tq_get","text":"","code":"tq_get(x, get = \"stock.prices\", complete_cases = TRUE, ...) tq_get_options()"},{"path":"/reference/tq_get.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get quantitative data in tibble format — tq_get","text":"x single character string, character vector tibble representing single (multiple) stock symbol, metal symbol, currency combination, FRED code, etc. get character string representing type data get x. Options include: \"stock.prices\": Get open, high, low, close, volume adjusted stock prices stock symbol Yahoo Finance (https://finance.yahoo.com/). Wrapper quantmod::getSymbols(). \"dividends\": Get dividends stock symbol Yahoo Finance (https://finance.yahoo.com/). Wrapper quantmod::getDividends(). \"splits\": Get split ratio stock symbol Yahoo Finance (https://finance.yahoo.com/). Wrapper quantmod::getSplits(). \"stock.prices.japan\": Get open, high, low, close, volume adjusted stock prices stock symbol Yahoo Finance Japan (https://finance.yahoo.co.jp/). Wrapper quantmod::getSymbols.yahooj(). \"economic.data\": Get economic data FRED. rapper quantmod::getSymbols.FRED(). \"quandl\": Get data sets Quandl. Wrapper Quandl::Quandl(). See also quandl_api_key(). \"quandl.datatable\": Get data tables Quandl. Wrapper Quandl::Quandl.datatable(). See also quandl_api_key(). \"tiingo\": Get data sets Tiingo. Wrapper riingo::riingo_prices(). See also tiingo_api_key(). \"tiingo.iex\": Get data sets Tiingo. Wrapper riingo::riingo_iex_prices(). See also tiingo_api_key(). \"tiingo.crypto\": Get data sets Tiingo. Wrapper riingo::riingo_crypto_prices(). See also tiingo_api_key(). \"alphavantager\": Get data sets Alpha Vantage. Wrapper alphavantager::av_get(). See also av_api_key(). \"rblpapi\": Get data sets Bloomberg. Wrapper Rblpapi. See also Rblpapi::blpConnect() connect Bloomberg terminal (required). Use argument rblpapi_fun set function \"bdh\" (default), \"bds\", \"bdp\". complete_cases Removes symbols return NA value due error get call sending incorrect symbol \"XYZ\" get = \"stock.prices\". useful scaling user need add extra step remove rows. TRUE default, warning message generated rows removed. ... Additional parameters passed \"wrapped\" function. Investigate underlying functions see full list arguments. Common optional parameters include: : Standardized time series functions quantmod, quandl, tiingo, alphavantager packages. character string representing start date YYYY-MM-DD format. : Standardized time series functions quantmod, quandl, tiingo, alphavantager packages. character string representing end date YYYY-MM-DD format.","code":""},{"path":"/reference/tq_get.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Get quantitative data in tibble format — tq_get","text":"Returns data form tibble object.","code":""},{"path":"/reference/tq_get.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Get quantitative data in tibble format — tq_get","text":"tq_get() consolidated function gets data various web sources. function wrapper several quantmod functions, Quandl functions, also gets data websources unavailable packages. results always returned tibble. advantages (1) one function needed data sources (2) function can seemlessly used tidyverse: purrr, tidyr, dplyr verbs. tq_get_options() returns list valid get options can choose . tq_get_stock_index_options() deprecated removed next version. Please use tq_index_options() instead.","code":""},{"path":[]},{"path":"/reference/tq_get.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Get quantitative data in tibble format — tq_get","text":"","code":"# Load libraries # Get the list of `get` options tq_get_options() #> [1] \"stock.prices\" \"stock.prices.japan\" \"dividends\" #> [4] \"splits\" \"economic.data\" \"quandl\" #> [7] \"quandl.datatable\" \"tiingo\" \"tiingo.iex\" #> [10] \"tiingo.crypto\" \"alphavantager\" \"alphavantage\" #> [13] \"rblpapi\" # Get stock prices for a stock from Yahoo aapl_stock_prices <- tq_get(\"AAPL\") # Get stock prices for multiple stocks mult_stocks <- tq_get(c(\"META\", \"AMZN\"), get = \"stock.prices\", from = \"2016-01-01\", to = \"2017-01-01\") if (FALSE) { # --- Quandl --- if (rlang::is_installed(\"quandl\")) { quandl_api_key('') tq_get(\"EIA/PET_MTTIMUS1_M\", get = \"quandl\", from = \"2010-01-01\") } # Energy data from EIA # --- Tiingo --- if (rlang::is_installed(\"riingo\")) { tiingo_api_key('') # Tiingo Prices (Free alternative to Yahoo Finance!) tq_get(c(\"AAPL\", \"GOOG\"), get = \"tiingo\", from = \"2010-01-01\") # Sub-daily prices from IEX ---- tq_get(c(\"AAPL\", \"GOOG\"), get = \"tiingo.iex\", from = \"2020-01-01\", to = \"2020-01-15\", resample_frequency = \"5min\") # Tiingo Bitcoin Prices ---- tq_get(c(\"btcusd\", \"btceur\"), get = \"tiingo.crypto\", from = \"2020-01-01\", to = \"2020-01-15\", resample_frequency = \"5min\") } # --- Alpha Vantage --- if (rlang::is_installed(\"alphavantager\")) { av_api_key('') # Daily Time Series tq_get(\"AAPL\", get = \"alphavantager\", av_fun = \"TIME_SERIES_DAILY_ADJUSTED\", outputsize = \"full\") # Intraday 15 Min Interval tq_get(\"AAPL\", get = \"alphavantage\", av_fun = \"TIME_SERIES_INTRADAY\", interval = \"15min\", outputsize = \"full\") # FX DAILY tq_get(\"USD/EUR\", get = \"alphavantage\", av_fun = \"FX_DAILY\", outputsize = \"full\") # FX REAL-TIME QUOTE tq_get(\"USD/EUR\", get = \"alphavantage\", av_fun = \"CURRENCY_EXCHANGE_RATE\") } }"},{"path":"/reference/tq_index.html","id":null,"dir":"Reference","previous_headings":"","what":"Get all stocks in a stock index or stock exchange in tibble format — tq_index","title":"Get all stocks in a stock index or stock exchange in tibble format — tq_index","text":"Get stocks stock index stock exchange tibble format","code":""},{"path":"/reference/tq_index.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get all stocks in a stock index or stock exchange in tibble format — tq_index","text":"","code":"tq_index(x, use_fallback = FALSE) tq_exchange(x) tq_index_options() tq_exchange_options()"},{"path":"/reference/tq_index.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get all stocks in a stock index or stock exchange in tibble format — tq_index","text":"x single character string, character vector tibble representing single stock index multiple stock indexes. use_fallback boolean can used return fallback data set last downloaded package updated. Useful website . Set FALSE default.","code":""},{"path":"/reference/tq_index.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Get all stocks in a stock index or stock exchange in tibble format — tq_index","text":"Returns data form tibble object.","code":""},{"path":"/reference/tq_index.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Get all stocks in a stock index or stock exchange in tibble format — tq_index","text":"tq_index() returns stock symbol, company name, weight, sector every stock index. source www.ssga.com. tq_index_options() returns list stock indexes can choose . tq_exchange() returns stock symbol, company, last sale price, market capitalization, sector industry every stock exchange. Three stock exchanges available (AMEX, NASDAQ, NYSE). tq_exchange_options() returns list stock exchanges can choose . options AMEX, NASDAQ NYSE.","code":""},{"path":[]},{"path":"/reference/tq_index.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Get all stocks in a stock index or stock exchange in tibble format — tq_index","text":"","code":"# Get the list of stock index options tq_index_options() #> [1] \"DOW\" \"DOWGLOBAL\" \"SP400\" \"SP500\" \"SP600\" # Get all stock symbols in a stock index if (FALSE) { tq_index(\"DOW\") } # Get the list of stock exchange options tq_exchange_options() #> [1] \"AMEX\" \"NASDAQ\" \"NYSE\" # Get all stocks in a stock exchange if (FALSE) { tq_exchange(\"NYSE\") }"},{"path":"/reference/tq_mutate.html","id":null,"dir":"Reference","previous_headings":"","what":"Mutates quantitative data — tq_mutate","title":"Mutates quantitative data — tq_mutate","text":"tq_mutate() adds new variables existing tibble; tq_transmute() returns newly created columns typically used periodicity changes","code":""},{"path":"/reference/tq_mutate.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Mutates quantitative data — tq_mutate","text":"","code":"tq_mutate( data, select = NULL, mutate_fun, col_rename = NULL, ohlc_fun = NULL, ... ) tq_mutate_(data, select = NULL, mutate_fun, col_rename = NULL, ...) tq_mutate_xy(data, x, y = NULL, mutate_fun, col_rename = NULL, ...) tq_mutate_xy_(data, x, y = NULL, mutate_fun, col_rename = NULL, ...) tq_mutate_fun_options() tq_transmute( data, select = NULL, mutate_fun, col_rename = NULL, ohlc_fun = NULL, ... ) tq_transmute_(data, select = NULL, mutate_fun, col_rename = NULL, ...) tq_transmute_xy(data, x, y = NULL, mutate_fun, col_rename = NULL, ...) tq_transmute_xy_(data, x, y = NULL, mutate_fun, col_rename = NULL, ...) tq_transmute_fun_options()"},{"path":"/reference/tq_mutate.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Mutates quantitative data — tq_mutate","text":"data tibble (tidy data frame) data typically tq_get(). select columns send mutation function. mutate_fun mutation function either xts, quantmod, TTR package. Execute tq_mutate_fun_options() see full list options package. col_rename string character vector containing names can used quickly rename columns. ohlc_fun Deprecated. Use select. ... Additional parameters passed appropriate mutatation function. x, y Parameters used _xy consist column names variables passed mutatation function (instead OHLC functions).","code":""},{"path":"/reference/tq_mutate.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Mutates quantitative data — tq_mutate","text":"Returns mutated data form tibble object.","code":""},{"path":"/reference/tq_mutate.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Mutates quantitative data — tq_mutate","text":"tq_mutate tq_transmute flexible wrappers various xts, quantmod TTR functions. main advantage results returned tibble function can used tidyverse. tq_mutate used additional columns added return data frame. tq_transmute works exactly like tq_mutate except returns newly created columns. helpful changing periodicity new columns number rows original tibble. select specifies columns get passed mutation function. Select works flexible version OHLC extractor functions quantmod non-OHLC data works well. select NULL, columns selected. Example 1 , close returns \"close\" price sends mutate function, periodReturn. mutate_fun function performs work. Example 1, periodReturn, calculates period returns. ... additional arguments passed mutate_fun. Think whole operation Example 1 close price, obtained select = close, sent periodReturn function along additional arguments defining perform period return, includes period = \"daily\" type = \"log\". Example 4 shows apply rolling regression. tq_mutate_xy tq_transmute_xy designed enable working mutatation functions require two primary inputs (e.g. EVWMA, VWAP, etc). Example 2 shows benefit action: using EVWMA function uses volume define moving average period. tq_mutate_, tq_mutate_xy_, tq_transmute_, tq_transmute_xy_ setup Non-Standard Evaluation (NSE). enables programatically changing column names modifying text representations. Example 5 shows difference implementation. Note character strings passed variables instead unquoted variable names. See vignette(\"nse\") information. tq_mutate_fun_options tq_transmute_fun_options return list various financial functions compatible tq_mutate tq_transmute, respectively.","code":""},{"path":[]},{"path":"/reference/tq_mutate.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Mutates quantitative data — tq_mutate","text":"","code":"# Load libraries library(dplyr) ##### Basic Functionality fb_stock_prices <- FANG %>% filter(symbol == \"META\") %>% filter( date >= \"2016-01-01\", date <= \"2016-12-31\" ) goog_stock_prices <- FANG %>% filter(symbol == \"GOOG\") %>% filter( date >= \"2016-01-01\", date <= \"2016-12-31\" ) # Example 1: Return logarithmic daily returns using periodReturn() fb_stock_prices %>% tq_mutate(select = close, mutate_fun = periodReturn, period = \"daily\", type = \"log\") #> Error in to_period(xx, period = on.opts[[period]], ...): ‘x’ contains no data # Example 2: Use tq_mutate_xy to use functions with two columns required fb_stock_prices %>% tq_mutate_xy(x = close, y = volume, mutate_fun = EVWMA, col_rename = \"EVWMA\") #> Error in fun_transmute(eval(parse(text = x)), eval(parse(text = y)), ...): n = 10 is outside valid range: [1, 0] # Example 3: Using tq_mutate to work with non-OHLC data tq_get(\"DCOILWTICO\", get = \"economic.data\") %>% tq_mutate(select = price, mutate_fun = lag.xts, k = 1, na.pad = TRUE) #> # A tibble: 2,800 × 4 #> symbol date price lag.xts #> #> 1 DCOILWTICO 2013-01-01 NA NA #> 2 DCOILWTICO 2013-01-02 93.1 NA #> 3 DCOILWTICO 2013-01-03 93.0 93.1 #> 4 DCOILWTICO 2013-01-04 93.1 93.0 #> 5 DCOILWTICO 2013-01-07 93.2 93.1 #> 6 DCOILWTICO 2013-01-08 93.2 93.2 #> 7 DCOILWTICO 2013-01-09 93.1 93.2 #> 8 DCOILWTICO 2013-01-10 93.8 93.1 #> 9 DCOILWTICO 2013-01-11 93.6 93.8 #> 10 DCOILWTICO 2013-01-14 94.3 93.6 #> # ℹ 2,790 more rows # Example 4: Using tq_mutate to apply a rolling regression fb_returns <- fb_stock_prices %>% tq_transmute(adjusted, periodReturn, period = \"monthly\", col_rename = \"fb.returns\") #> Error in to_period(xx, period = on.opts[[period]], ...): ‘x’ contains no data goog_returns <- goog_stock_prices %>% tq_transmute(adjusted, periodReturn, period = \"monthly\", col_rename = \"goog.returns\") returns_combined <- left_join(fb_returns, goog_returns, by = \"date\") #> Error in eval(expr, envir, enclos): object 'fb_returns' not found regr_fun <- function(data) { coef(lm(fb.returns ~ goog.returns, data = as_tibble(data))) } returns_combined %>% tq_mutate(mutate_fun = rollapply, width = 6, FUN = regr_fun, by.column = FALSE, col_rename = c(\"coef.0\", \"coef.1\")) #> Error in eval(expr, envir, enclos): object 'returns_combined' not found # Example 5: Non-standard evaluation: # Programming with tq_mutate_() and tq_mutate_xy_() col_name <- \"adjusted\" mutate <- c(\"MACD\", \"SMA\") tq_mutate_xy_(fb_stock_prices, x = col_name, mutate_fun = mutate[[1]]) #> Error in EMA(structure(logical(0), index = structure(numeric(0), tzone = \"UTC\", tclass = \"Date\"), class = c(\"xts\", \"zoo\"), dim = 0:1, dimnames = list(NULL, \"adjusted\")), n = 12): n = 12 is outside valid range: [1, 0]"},{"path":"/reference/tq_performance.html","id":null,"dir":"Reference","previous_headings":"","what":"Computes a wide variety of summary performance metrics from stock or portfolio returns — tq_performance","title":"Computes a wide variety of summary performance metrics from stock or portfolio returns — tq_performance","text":"Asset portfolio performance analysis deep field wide range theories methods analyzing risk versus reward. PerformanceAnalytics package consolidates many widely used performance metrics functions can applied stock portfolio returns. tq_performance implements performance analysis functions tidy way, enabling scaling analysis using split, apply, combine framework.","code":""},{"path":"/reference/tq_performance.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Computes a wide variety of summary performance metrics from stock or portfolio returns — tq_performance","text":"","code":"tq_performance(data, Ra, Rb = NULL, performance_fun, ...) tq_performance_(data, Ra, Rb = NULL, performance_fun, ...) tq_performance_fun_options()"},{"path":"/reference/tq_performance.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Computes a wide variety of summary performance metrics from stock or portfolio returns — tq_performance","text":"data tibble (tidy data frame) returns tidy format (.e long format). Ra column asset returns Rb column baseline returns (functions require comparison baseline) performance_fun performance function PerformanceAnalytics. See tq_performance_fun_options() complete list integrated functions. ... Additional parameters passed PerformanceAnalytics function.","code":""},{"path":"/reference/tq_performance.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Computes a wide variety of summary performance metrics from stock or portfolio returns — tq_performance","text":"Returns data form tibble object.","code":""},{"path":"/reference/tq_performance.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Computes a wide variety of summary performance metrics from stock or portfolio returns — tq_performance","text":"Important concept: Performance based statistical properties returns, result function uses stock portfolio returns opposed stock prices. tq_performance wrapper various PerformanceAnalytics functions return portfolio statistics. main advantage ability scale tidyverse. Ra Rb columns containing asset baseline returns, respectively. columns mapped PerformanceAnalytics functions. Note Rb always required, instances argument defaults Rb = NULL. user can tell Rb required researching underlying performance function. ... additional arguments passed PerformanceAnalytics function. Search underlying function see arguments can passed . tq_performance_fun_options returns list compatible PerformanceAnalytics functions can supplied performance_fun argument.","code":""},{"path":[]},{"path":"/reference/tq_performance.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Computes a wide variety of summary performance metrics from stock or portfolio returns — tq_performance","text":"","code":"# Load libraries library(dplyr) # Use FANG data set # Get returns for individual stock components grouped by symbol Ra <- FANG %>% group_by(symbol) %>% tq_transmute(adjusted, periodReturn, period = \"monthly\", col_rename = \"Ra\") # Get returns for SP500 as baseline Rb <- \"^GSPC\" %>% tq_get(get = \"stock.prices\", from = \"2010-01-01\", to = \"2015-12-31\") %>% tq_transmute(adjusted, periodReturn, period = \"monthly\", col_rename = \"Rb\") # Merge stock returns with baseline RaRb <- left_join(Ra, Rb, by = c(\"date\" = \"date\")) ##### Performance Metrics ##### # View options tq_performance_fun_options() #> $table.funs #> [1] \"table.AnnualizedReturns\" \"table.Arbitrary\" #> [3] \"table.Autocorrelation\" \"table.CAPM\" #> [5] \"table.CaptureRatios\" \"table.Correlation\" #> [7] \"table.Distributions\" \"table.DownsideRisk\" #> [9] \"table.DownsideRiskRatio\" \"table.DrawdownsRatio\" #> [11] \"table.HigherMoments\" \"table.InformationRatio\" #> [13] \"table.RollingPeriods\" \"table.SFM\" #> [15] \"table.SpecificRisk\" \"table.Stats\" #> [17] \"table.TrailingPeriods\" \"table.UpDownRatios\" #> [19] \"table.Variability\" #> #> $CAPM.funs #> [1] \"CAPM.CML\" \"CAPM.CML.slope\" \"CAPM.RiskPremium\" \"CAPM.SML.slope\" #> [5] \"CAPM.alpha\" \"CAPM.beta\" \"CAPM.beta.bear\" \"CAPM.beta.bull\" #> [9] \"CAPM.dynamic\" \"CAPM.epsilon\" \"CAPM.jensenAlpha\" \"TimingRatio\" #> [13] \"MarketTiming\" #> #> $SFM.funs #> [1] \"SFM.CML\" \"SFM.CML.slope\" \"SFM.alpha\" \"SFM.beta\" #> [5] \"SFM.dynamic\" \"SFM.epsilon\" \"SFM.jensenAlpha\" #> #> $descriptive.funs #> [1] \"mean\" \"sd\" \"min\" \"max\" #> [5] \"cor\" \"mean.geometric\" \"mean.stderr\" \"mean.LCL\" #> [9] \"mean.UCL\" #> #> $annualized.funs #> [1] \"Return.annualized\" \"Return.annualized.excess\" #> [3] \"sd.annualized\" \"SharpeRatio.annualized\" #> #> $VaR.funs #> [1] \"VaR\" \"ES\" \"ETL\" \"CDD\" \"CVaR\" #> #> $moment.funs #> [1] \"var\" \"cov\" \"skewness\" \"kurtosis\" #> [5] \"CoVariance\" \"CoSkewness\" \"CoSkewnessMatrix\" \"CoKurtosis\" #> [9] \"CoKurtosisMatrix\" \"M3.MM\" \"M4.MM\" \"BetaCoVariance\" #> [13] \"BetaCoSkewness\" \"BetaCoKurtosis\" #> #> $drawdown.funs #> [1] \"AverageDrawdown\" \"AverageLength\" \"AverageRecovery\" #> [4] \"DrawdownDeviation\" \"DrawdownPeak\" \"maxDrawdown\" #> #> $Bacon.risk.funs #> [1] \"MeanAbsoluteDeviation\" \"Frequency\" \"SharpeRatio\" #> [4] \"MSquared\" \"MSquaredExcess\" \"HurstIndex\" #> #> $Bacon.regression.funs #> [1] \"CAPM.alpha\" \"CAPM.beta\" \"CAPM.epsilon\" \"CAPM.jensenAlpha\" #> [5] \"SystematicRisk\" \"SpecificRisk\" \"TotalRisk\" \"TreynorRatio\" #> [9] \"AppraisalRatio\" \"FamaBeta\" \"Selectivity\" \"NetSelectivity\" #> #> $Bacon.relative.risk.funs #> [1] \"ActivePremium\" \"ActiveReturn\" \"TrackingError\" \"InformationRatio\" #> #> $Bacon.drawdown.funs #> [1] \"PainIndex\" \"PainRatio\" \"CalmarRatio\" \"SterlingRatio\" #> [5] \"BurkeRatio\" \"MartinRatio\" \"UlcerIndex\" #> #> $Bacon.downside.risk.funs #> [1] \"DownsideDeviation\" \"DownsidePotential\" \"DownsideFrequency\" #> [4] \"SemiDeviation\" \"SemiVariance\" \"UpsideRisk\" #> [7] \"UpsidePotentialRatio\" \"UpsideFrequency\" \"BernardoLedoitRatio\" #> [10] \"DRatio\" \"Omega\" \"OmegaSharpeRatio\" #> [13] \"OmegaExcessReturn\" \"SortinoRatio\" \"M2Sortino\" #> [16] \"Kappa\" \"VolatilitySkewness\" \"AdjustedSharpeRatio\" #> [19] \"SkewnessKurtosisRatio\" \"ProspectRatio\" #> #> $misc.funs #> [1] \"KellyRatio\" \"Modigliani\" \"UpDownRatios\" #> # Get performance metrics RaRb %>% tq_performance(Ra = Ra, performance_fun = SharpeRatio, p = 0.95) #> # A tibble: 4 × 4 #> # Groups: symbol [4] #> symbol `ESSharpe(Rf=0%,p=95%)` StdDevSharpe(Rf=0%,p=9…¹ VaRSharpe(Rf=0%,p=95…² #> #> 1 FB 0.193 0.345 0.605 #> 2 AMZN 0.215 0.314 0.265 #> 3 NFLX 0.199 0.355 0.606 #> 4 GOOG 0.213 0.296 0.310 #> # ℹ abbreviated names: ¹​`StdDevSharpe(Rf=0%,p=95%)`, ²​`VaRSharpe(Rf=0%,p=95%)` RaRb %>% tq_performance(Ra = Ra, Rb = Rb, performance_fun = table.CAPM) #> # A tibble: 4 × 13 #> # Groups: symbol [4] #> symbol ActivePremium Alpha AnnualizedAlpha Beta `Beta+` `Beta-` Correlation #> #> 1 FB 0.431 0.034 0.493 0.846 3.00 0.819 0.234 #> 2 AMZN 0.246 0.0144 0.187 1.46 2.04 -0.0442 0.524 #> 3 NFLX 1.02 0.0632 1.09 1.35 1.90 -2.78 0.234 #> 4 GOOG 0.142 0.0123 0.158 0.901 1.56 -0.247 0.451 #> # ℹ 5 more variables: `Correlationp-value` , InformationRatio , #> # `R-squared` , TrackingError , TreynorRatio "},{"path":"/reference/tq_portfolio.html","id":null,"dir":"Reference","previous_headings":"","what":"Aggregates a group of returns by asset into portfolio returns — tq_portfolio","title":"Aggregates a group of returns by asset into portfolio returns — tq_portfolio","text":"Aggregates group returns asset portfolio returns","code":""},{"path":"/reference/tq_portfolio.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Aggregates a group of returns by asset into portfolio returns — tq_portfolio","text":"","code":"tq_portfolio( data, assets_col, returns_col, weights = NULL, col_rename = NULL, ... ) tq_portfolio_( data, assets_col, returns_col, weights = NULL, col_rename = NULL, ... ) tq_repeat_df(data, n, index_col_name = \"portfolio\")"},{"path":"/reference/tq_portfolio.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Aggregates a group of returns by asset into portfolio returns — tq_portfolio","text":"data tibble (tidy data frame) returns tidy format (.e long format). assets_col column assets (securities) returns_col column returns weights Optional parameter asset weights, can passed numeric vector length number assets two column tibble asset names first column weights second column. col_rename string character vector containing names can used quickly rename columns. ... Additional parameters passed PerformanceAnalytics::Return.portfolio n Number times repeat data frame row-wise. index_col_name renaming function \"index\" column, used repeating data frames.","code":""},{"path":"/reference/tq_portfolio.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Aggregates a group of returns by asset into portfolio returns — tq_portfolio","text":"Returns data form tibble object.","code":""},{"path":"/reference/tq_portfolio.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Aggregates a group of returns by asset into portfolio returns — tq_portfolio","text":"tq_portfolio wrapper PerformanceAnalytics::Return.portfolio. main advantage results returned tibble function can used tidyverse. assets_col returns_col columns within data used compute returns portfolio. columns \"long\" format (\"tidy\" format) meaning one column containing assets one column containing return values (.e. \"wide\" format returns spread asset). weights weights applied asset returns. Weights can input one three options: Single Portfolio: numeric vector weights length unique number assets. weights applied order assets. Single Portfolio: two column tibble assets first column weights second column. advantage method weights mapped assets unlisted assets default weight zero. Multiple Portfolios: three column tibble portfolio index first column, assets second column, weights third column. tibble must grouped portfolio index. tq_repeat_df simple function repeats data frame n times row-wise (long-wise), adds new column portfolio index. function used assist Multiple Portfolio analyses, useful precursor tq_portfolio.","code":""},{"path":[]},{"path":"/reference/tq_portfolio.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Aggregates a group of returns by asset into portfolio returns — tq_portfolio","text":"","code":"# Load libraries library(dplyr) # Use FANG data set # Get returns for individual stock components monthly_returns_stocks <- FANG %>% group_by(symbol) %>% tq_transmute(adjusted, periodReturn, period = \"monthly\") ##### Portfolio Aggregation Methods ##### # Method 1: Use tq_portfolio with numeric vector of weights weights <- c(0.50, 0.25, 0.25, 0) tq_portfolio(data = monthly_returns_stocks, assets_col = symbol, returns_col = monthly.returns, weights = weights, col_rename = NULL, wealth.index = FALSE) #> # A tibble: 48 × 2 #> date portfolio.returns #> #> 1 2013-01-31 0.260 #> 2 2013-02-28 -0.00456 #> 3 2013-03-28 -0.0195 #> 4 2013-04-30 0.0810 #> 5 2013-05-31 -0.0139 #> 6 2013-06-28 -0.0179 #> 7 2013-07-31 0.254 #> 8 2013-08-30 0.104 #> 9 2013-09-30 0.145 #> 10 2013-10-31 0.0420 #> # ℹ 38 more rows # Method 2: Use tq_portfolio with two column tibble and map weights # Note that GOOG's weighting is zero in Method 1. In Method 2, # GOOG is not added and same result is achieved. weights_df <- tibble(symbol = c(\"META\", \"AMZN\", \"NFLX\"), weights = c(0.50, 0.25, 0.25)) tq_portfolio(data = monthly_returns_stocks, assets_col = symbol, returns_col = monthly.returns, weights = weights_df, col_rename = NULL, wealth.index = FALSE) #> Warning: The assets in weights does not match the assets in data. #> Warning: The weights for one or more periods do not sum up to 1: assuming a return of 0 for the residual weights #> # A tibble: 48 × 2 #> date portfolio.returns #> #> 1 2013-01-31 0.207 #> 2 2013-02-28 0.0504 #> 3 2013-03-28 0.00427 #> 4 2013-04-30 0.0475 #> 5 2013-05-31 0.0320 #> 6 2013-06-28 -0.0239 #> 7 2013-07-31 0.0846 #> 8 2013-08-30 0.0600 #> 9 2013-09-30 0.0644 #> 10 2013-10-31 0.0523 #> # ℹ 38 more rows # Method 3: Working with multiple portfolios # 3A: Duplicate monthly_returns_stocks multiple times mult_monthly_returns_stocks <- tq_repeat_df(monthly_returns_stocks, n = 4) #> Ungrouping data frame groups: symbol # 3B: Create weights table grouped by portfolio id weights <- c(0.50, 0.25, 0.25, 0.00, 0.00, 0.50, 0.25, 0.25, 0.25, 0.00, 0.50, 0.25, 0.25, 0.25, 0.00, 0.50) stocks <- c(\"META\", \"AMZN\", \"NFLX\", \"GOOG\") weights_table <- tibble(stocks) %>% tq_repeat_df(n = 4) %>% bind_cols(tibble(weights)) %>% group_by(portfolio) # 3C: Scale to multiple portfolios tq_portfolio(data = mult_monthly_returns_stocks, assets_col = symbol, returns_col = monthly.returns, weights = weights_table, col_rename = NULL, wealth.index = FALSE) #> Warning: There were 7 warnings in `dplyr::mutate()`. #> The first warning was: #> ℹ In argument: `portfolio.. = purrr::pmap(list(returns.., weights.., #> portfolio), custom_function)`. #> ℹ In group 1: `portfolio = 1`. #> Caused by warning in `check_weights()`: #> ! The assets in weights does not match the assets in data. #> ℹ Run `dplyr::last_dplyr_warnings()` to see the 6 remaining warnings. #> # A tibble: 192 × 3 #> # Groups: portfolio [4] #> portfolio date portfolio.returns #> #> 1 1 2013-01-31 0.207 #> 2 1 2013-02-28 0.0504 #> 3 1 2013-03-28 0.00427 #> 4 1 2013-04-30 0.0475 #> 5 1 2013-05-31 0.0320 #> 6 1 2013-06-28 -0.0239 #> 7 1 2013-07-31 0.0846 #> 8 1 2013-08-30 0.0600 #> 9 1 2013-09-30 0.0644 #> 10 1 2013-10-31 0.0523 #> # ℹ 182 more rows"},{"path":"/news/index.html","id":"tidyquant-development-version","dir":"Changelog","previous_headings":"","what":"tidyquant (development version)","title":"tidyquant (development version)","text":"Remove dependency tidyverse tidyquant longer loads lubridate tidyverse 2.0 now loads lubridate Changed size argument linewidth ggplot2 3.4.0 Removed last tidyr dplyr deprecated functions Add linewidth = geom_ma() Move Quandl, riingo, alphavantager Suggests. tidyquant explictly install , can install CRAN. Fixed CRAN alias FB META change FANG","code":""},{"path":"/news/index.html","id":"tidyquant-107","dir":"Changelog","previous_headings":"","what":"tidyquant 1.0.7","title":"tidyquant 1.0.7","text":"CRAN release: 2023-03-31 Moved tidyverse suggest imports pass cran tests","code":""},{"path":"/news/index.html","id":"tidyquant-106","dir":"Changelog","previous_headings":"","what":"tidyquant 1.0.6","title":"tidyquant 1.0.6","text":"CRAN release: 2022-11-16 Fix tq_performance test failure PerformanceAnalytics 2.0.6 #223 Fix failed r-devel test identified CRAN Remove deprecated spread_() function Move readxl imports. #222","code":""},{"path":"/news/index.html","id":"tidyquant-105","dir":"Changelog","previous_headings":"","what":"tidyquant 1.0.5","title":"tidyquant 1.0.5","text":"CRAN release: 2022-09-08 FIX: FB META name change IMPROVEMENT: sp_index() convert symbols “BRK.B” “BRK-B” work Yahoo Finance","code":""},{"path":"/news/index.html","id":"tidyquant-104","dir":"Changelog","previous_headings":"","what":"tidyquant 1.0.4","title":"tidyquant 1.0.4","text":"CRAN release: 2022-05-20 CRAN requested fixes: Moved janitor suggests Reduced file size removing vignettes CRAN version. changes: Removed package start-message","code":""},{"path":"/news/index.html","id":"tidyquant-103","dir":"Changelog","previous_headings":"","what":"tidyquant 1.0.3","title":"tidyquant 1.0.3","text":"CRAN release: 2021-03-05","code":""},{"path":"/news/index.html","id":"fixes-1-0-3","dir":"Changelog","previous_headings":"","what":"Fixes","title":"tidyquant 1.0.3","text":"tq_exchange(): Switch new NASDAQ website.","code":""},{"path":"/news/index.html","id":"tidyquant-102","dir":"Changelog","previous_headings":"","what":"tidyquant 1.0.2","title":"tidyquant 1.0.2","text":"CRAN release: 2020-10-21","code":""},{"path":"/news/index.html","id":"fixes-1-0-2","dir":"Changelog","previous_headings":"","what":"Fixes","title":"tidyquant 1.0.2","text":"tq_exchange(): Fix issue NASDAQ changes website. theme_tq(): Fix issues %+replace%, theme_gray, rel found.","code":""},{"path":"/news/index.html","id":"tidyquant-101","dir":"Changelog","previous_headings":"","what":"tidyquant 1.0.1","title":"tidyquant 1.0.1","text":"CRAN release: 2020-07-02","code":""},{"path":"/news/index.html","id":"improvements-1-0-1","dir":"Changelog","previous_headings":"","what":"Improvements","title":"tidyquant 1.0.1","text":"tq_get() - Add \"dividends\" \"splits\" get options, fixed quantmod 0.4-16. Issue 150.","code":""},{"path":"/news/index.html","id":"bug-fixes-1-0-1","dir":"Changelog","previous_headings":"","what":"Bug Fixes","title":"tidyquant 1.0.1","text":"Issue 157 - Error package load rstudioapi::getThemeInfo() returns NULL. pivot_table - Fix issues tidyverse functions found.","code":""},{"path":"/news/index.html","id":"deprecation-1-0-1","dir":"Changelog","previous_headings":"","what":"Deprecation","title":"tidyquant 1.0.1","text":"summarise_by_time() - function moved timetk::summarise_by_time()","code":""},{"path":"/news/index.html","id":"tidyquant-100","dir":"Changelog","previous_headings":"","what":"tidyquant 1.0.0","title":"tidyquant 1.0.0","text":"CRAN release: 2020-03-04 “R Excel Users” release. aim build functionality helps users coming Excel Background (background came ). ’s important users feel home. full suite functionality accomplish Excel--R transition. -Matt Excel Functions Excel functions? Designed help users coming Excel Background easily transition tidyverse “tidy- finance / business analysis” R. pivot_table() - tidyverse-style function perform data summarizations just like popular Excel Pivot Table. Enables stacking calculations using tidy-esque syntax: .rows = ~ YEAR(order_date). VLOOKUP() - Performs classic Excel VLOOKUP. Excel user’s: rejoice. Summarising “IFS” Functions - Filtering versions Excel summarization counterparts. Simply add “cases” filter condition true. SUM_IFS(), COUNT_IFS(), AVERAGE_IFS() Create “IFS” functions - idea new “IFS” function hasn’t made yet? Use CREATE_IFS() make supplying summarization function. 100+ Excel-based statistical, date, financial math functions. Names similar Excel function names. default, missing values ignored (Excel). Summarizations Functions - SUM(), AVERAGE(), COUNT(), friends. Transformation Functions - CHANGE(), PCT_CHANGE(), LAG(), CUMULATIVE_SUM(), friends. Integrated date calculations lubridate() (e.g. AS_DATE(), YEAR()) Holidays business calendars timeDate (e.g. HOLIDAY_SEQUENCE(), HOLIDAY_LIST()) Excel Date Math functions: NET_WORKDAYS(), EOMONTH() Financial Math Functions - NPV(), IRR(), FV(), PV(), PMT(), RATE() NEW Tidyverse Functionality summarise_by_time() - new time-based variant summarise() allows collapsing time-series “day”, “week”, “month”, “quarter”, “year”, . Note: evaluate need summarise_at_by_time(), summarise_all_by_time(), summarise_if_by_time() release dplyr v1.0.0. NEW API Integrations Tiingo API - popular Open-Source stock prices, cryptocurrencies, intraday feeds IEX (Investors Exchange). can serve alternate source data Yahoo Finance. Integrated via riingo package. Bug Fixes & Improvements theme_tq() - Fix issues collisions dials::margin() ggplot2::margin(). Similar potential ggplot2 collisions fixed. theme_tq() - Increased default top/bottom text margin facet strips Deprecation & Breaking Changes Potential Breaking Change - Single values now return symbol column (.e. tq_get(\"AAPL\") returns symbol = “AAPL” 1st column). Google Finance Morningstar Key Ratios & Financials (Fundamentals) Data Yahoo Dividends Splits Oanda FX Metal Prices Deprecated Compound Getters - Stacking multiple get options (tq_get(\"AAPL\", get = c(\"stock.prices\", \"stock.prices.japan\"))) longer available. Solution: Split two calls tq_get().","code":""},{"path":"/news/index.html","id":"tidyquant-0510","dir":"Changelog","previous_headings":"","what":"tidyquant 0.5.10","title":"tidyquant 0.5.10","text":"CRAN release: 2020-01-27 tq_get() - Temporarily adjust tests tq_get(get = \"dividends\") tq_get(get = \"splits\") API stabilizes. Yahoo! Dividends Splits intermitently returns errors. Fix documentation warnings package build checks. Documentation moved tq_stocklist ?tq_index.","code":""},{"path":"/news/index.html","id":"tidyquant-059","dir":"Changelog","previous_headings":"","what":"tidyquant 0.5.9","title":"tidyquant 0.5.9","text":"CRAN release: 2019-12-15 Fix issue #144 - tq_index() download issue. Note “RUSSEL1000”, “RUSSELL2000”, “RUSSELL3000”, “SP1000” longer available due changes www.us.spdrs.com. Update Stock Index Fallback.","code":""},{"path":"/news/index.html","id":"tidyquant-058","dir":"Changelog","previous_headings":"","what":"tidyquant 0.5.8","title":"tidyquant 0.5.8","text":"CRAN release: 2019-10-11 tq_index() - Fix naming issue stock index data downloaded www.us.spdrs.com.","code":""},{"path":"/news/index.html","id":"tidyquant-057","dir":"Changelog","previous_headings":"","what":"tidyquant 0.5.7","title":"tidyquant 0.5.7","text":"CRAN release: 2019-09-20 Stock Index & Exchanges tq_exchange() - Fix NASDAQ URL change Issue #138. Visualizations & Color Palettes geom_candlestick geom_barchart - Issue #112. Added color names theme_tq palettes (palette_light, palette_dark, palette_green) easier identification. Compatability tidyr v1.0.0 Improvements ensure compatability tidyr v1.0.0 [Potential Breaking Change] Move tidyverse suggests actually potentially “breaking change” (although users see difference since likely load tidyverse scripts) - load tidyverse, now need . Previously tidyquant loaded tidyverse behind scenes.","code":""},{"path":"/news/index.html","id":"tidyquant-056","dir":"Changelog","previous_headings":"","what":"tidyquant 0.5.6","title":"tidyquant 0.5.6","text":"CRAN release: 2019-04-22 Morningstar Key Ratios: tq_get() argument get = \"key.ratios\" deprecated due change Morningstar’s website. (Help Wanted - Ref. Issue #125) Remove dependency XLConnect. Replace readxl. Issue #119.","code":""},{"path":"/news/index.html","id":"tidyquant-055","dir":"Changelog","previous_headings":"","what":"tidyquant 0.5.5","title":"tidyquant 0.5.5","text":"CRAN release: 2018-05-09 Bux fix tq_get() get = \"financials\" now returns warning NA Google Finance longer provides data. actively looking alternative data sources. tq_get() get = \"stock.prices.google\" now returns warning NA Google Finance longer provides data. Use get = \"stock.prices\" instead use Yahoo Finance, use riingo package download Tiingo. Catch duplicate names col_rename renaming 1 column. Duplicate names allowed return error. Fix duplicate name collision issue original name already includes .. Duplicate names now get ..1, ..2, etc. opposed .1, .2.","code":""},{"path":"/news/index.html","id":"tidyquant-054","dir":"Changelog","previous_headings":"","what":"tidyquant 0.5.4","title":"tidyquant 0.5.4","text":"CRAN release: 2018-02-19 Incorporate alphavantager, lightweight API Alpha Vantage financial data provider. Integrate Rblpapi, R interface “Bloomberg”. must Bloomberg account use . Add Google Finance source tq_get(get = \"stock.prices.google\") Remove Key Statistics tq_get(get = \"key.stats\"). Yahoo Finance longer supports Key Statistics CSV API. Completed deprecation tidyquant::as_tibble() tidyquant::as_xts(). Use timetk::tk_tbl() timetk::tk_xts() instead. tibbletime support added tidyquant functions play nicely tbl_time objects. hard dependency XLConnect removed. ease use package, especially Mac users. tests failed testthat 2.0. updated.","code":""},{"path":"/news/index.html","id":"tidyquant-053","dir":"Changelog","previous_headings":"","what":"tidyquant 0.5.3","title":"tidyquant 0.5.3","text":"CRAN release: 2017-08-03 Fixes compatibility purrr v0.2.3.","code":""},{"path":"/news/index.html","id":"tidyquant-052","dir":"Changelog","previous_headings":"","what":"tidyquant 0.5.2","title":"tidyquant 0.5.2","text":"CRAN release: 2017-07-27 Incorporated robust timetk coercion functions. Deprecated tidyquant::as_xts() tidyquant::as_tibble(). Use timetk::tk_xts() timetk::tk_tbl() instead. tq_index() longer pulls marketvolume. Instead, 9 indices available SPDR. indices reliable, include weights stock index. Fixed 2 tests results tq_get(get = \"stock.prices\") 1 2 rows tests expected. likely new yahoo finance API.","code":""},{"path":"/news/index.html","id":"tidyquant-051","dir":"Changelog","previous_headings":"","what":"tidyquant 0.5.1","title":"tidyquant 0.5.1","text":"CRAN release: 2017-04-24 Added pkgdown integration. Require new quantmod version 0.4-8 fix Oanda Yahoo bugs. Quandl data returned newest oldest. consistency tq_get() data, now returns oldest newest. Oanda returns 180 days FX Metals data now. Updated tests account . Also added error handling check valid date ranges. Fixed bug tq_portfolio() weights = NULL execute equal weighting scheme. Added error handling dollar percent conversion get = “key.ratios” get = “key.stats”.","code":""},{"path":"/news/index.html","id":"tidyquant-050","dir":"Changelog","previous_headings":"","what":"tidyquant 0.5.0","title":"tidyquant 0.5.0","text":"CRAN release: 2017-04-03 tq_get(get = \"quandl\") wrapper Quandl::Quandl() pulls multiple Quandl Codes “tidy” fashion. tq_get(get = \"quandl.datatable\") wrapper Quandl::Quandl.datable() pulls Quandl datatables. quandl_api_key() wrapper Quandl::Quandl.api_key(). quandl_search wrapper Quandl::Quandl.search(). Yahoo Japan Integration: tq_get(get = \"stock.prices.japan\") wrapper quantmod::getSymbols(src = \"yahooj\") enables getting stocks Yahoo Finance Japan. tq_mutate() tq_transmute() now accept non-OHLC data select argument. also now work rollapply. tq_mutate() tq_transmute() now accept PerformanceAnalytics functions work clean transform asset returns. Deprecated ohlc_fun argument instead use select tq_mutate() tq_transmute .Deprecated -> .Defunct tq_transform() tq_transform_xy(). Use tq_transmute() tq_transmute_xy(). Move sign post functions deprecated.R Remove previously deprecated argument, transform_fun tq_transmute(). Use mutate_fun instead. Fix issue tq_mutate returning rows incorrectly sorted Fix issue tq_get returning data frames nested Fix tq_get error return full error issues present.","code":""},{"path":"/news/index.html","id":"tidyquant-040","dir":"Changelog","previous_headings":"","what":"tidyquant 0.4.0","title":"tidyquant 0.4.0","text":"CRAN release: 2017-03-03 tq_transmute() replaces tq_transform() consistency dplyr. tq_performance() integrates performance analysis functions PerformanceAnalytics. tq_portfolio() enables aggregating portfolios individual stock returns. tq_tranform(): Added NA-handling functions zoo list compatible, provide number useful methods handling NA values data sets. Added Return.calculate Return.excess calculating returns returns excess risk-free rate, respectively. tq_mutate() tq_transmute() help pages combined. Split introduction four separate vignettes, improves flow enables readers easily get needed documentation. Now five docs total covering primary needs tidyquant users! tq_exchange() gets stock list NASDAQ, NYSE, AMEX exchanges. Use tq_exchange_options() exchange options. FANG data set palette_() functions used create scales exported. theme_tq() creates light, dark, green themes tidyquant visualizations. scale_color_tq() scale_fill_tq() add color/fill scales data used tidyquant visualizations. transform_fun argument tq_transmute() replaced mutate_fun consistency tq_mutate(). Core functions now generics allow extendability. Issue #11: Part 2. Fix multiple stocks return 110 lines. Handle stocks return csv “’re sorry” message. Issue #11: Part 1. Fix instability get = key.ratios failing HTTP 500 error download. Use httr RETRY case failure. Fixed issue get = \"key.ratios\" stocks listed AMEX exchange able return key ratios. Issue #9: Fix problem get = \"key.stats\" NA’s multiple x (e.g. c(\"AAPL\", \"GOOG\")) cause call fail coercion. Issue #8, Part 2: Enable compound gets (e.g. tq_get(\"AAPL\", get = c(\"stock.prices\", \"financials\"))). Issue #8, Part 1: Create tq_index() function return stock index. tq_get(get = \"stock.index\") deprecated removed next version 0.4.0. Use tq_index_options() index options. Issue #7: Fixed issue date column inadvertently coerced dttm.","code":""},{"path":"/news/index.html","id":"tidyquant-030","dir":"Changelog","previous_headings":"","what":"tidyquant 0.3.0","title":"tidyquant 0.3.0","text":"CRAN release: 2017-01-21 New tq_get option get = \"key.stats\", retrieves current key statistics (55 total) www.finance.yahoo.com/. include various current data Ask, Bid, Day’s High, Day’s Low, Last Trade Price, current P/E Ratio, EPS, Current Market Cap, EPS Projected Current Year, EPS Projected Next Year many . Example: tq_get(\"AAPL\", get = \"key.stats\"). Chart geoms: Bar charts (geom_barchart) candlestick charts (geom_candlestick) can quickly created new geoms. Moving Averages: Seven moving averages can quickly visualized / prototyped using geom_ma. geom wraps TTR::SMA functions. Bollinger bands can visualized geom_bbands. seven moving averages compatible geom. Zooming Chart Sections: Two functions (coord_x_date coord_x_datetime) added enable zooming chart sections using dates --bounds data loss (e.g. --bounds data loss scale_x_ functions). New Vignette: Covers “Charting tidyquant”. Issue #5: tq_get can now accept character vectors data frames x arg, addition single character input. streamlines getting data multiple inputs (e.g. stock symbols, stock indexes, etc). Issue #4: Added col_rename arg tq_mutate tq_transform, enables fast easy renaming operation. Issue #3: Integrated dplyr::group_by() tq_mutate() tq_transform(). transform mutate functions now work properly grouped data frames. Issue #2: Fixed bug tq_get(), get = \"key.ratios\", key ratios stocks NYSE returned NA. Removed support deprecated arguments: x_fun, .x, .y respective transform mutate functions.","code":""},{"path":"/news/index.html","id":"tidyquant-020","dir":"Changelog","previous_headings":"","what":"tidyquant 0.2.0","title":"tidyquant 0.2.0","text":"CRAN release: 2017-01-08 New get = \"key.ratios\" option tq_get(), retrieves 10-years key performance ratios (89 total) www.morningstar.com. include various historical measures financial performance including profitability, growth, cash flow, financial health, efficiency, valuation ratios. Example: tq_get(\"AAPL\", get = \"key.ratios\"). Added zoo rollapply() functions list compatible / integrated functions used tq_transform() tq_mutate(). See tq_transform_fun_options() full list. x_fun now ohlc_fun tq_mutate() tq_transform() .x now x .y now y tq_mutate_xy() tq_transform_xy() Fixed duplication column names tq_mutate. Names now sequentually indexed duplicate names starting .1 suffix.","code":""},{"path":"/news/index.html","id":"tidyquant-010","dir":"Changelog","previous_headings":"","what":"tidyquant 0.1.0","title":"tidyquant 0.1.0","text":"CRAN release: 2016-12-31 Initial release tidyquant, seamless quantitative financial analysis (xts, quantmod, TTR) package integration tidyverse.","code":""}]