Details
-
tq_portfolio
is a wrapper for PerformanceAnalytics::Returns.portfolio
.
+
tq_portfolio
is a wrapper for PerformanceAnalytics::Return.portfolio
.
The main advantage is the results are returned as a tibble
and the
function can be used with the tidyverse
.
assets_col
and returns_col
are columns within data
that are used
diff --git a/search.json b/search.json
index 59277a35..baf3e99b 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.0269573 -0.0039657 0.0002148 0.0039655 0.0289460 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 0.0001130 0.0003097 0.365 0.715 ## V 0.8133642 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.00647 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.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,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 ##