### Install tidyquant Development Version Source: https://github.com/business-science/tidyquant/blob/master/README.md Install the development version of tidyquant to access the latest features. Requires the devtools package. ```r # install.packages("devtools") devtools::install_github("business-science/tidyquant") ``` -------------------------------- ### Get Stock Index with tidyquant Source: https://github.com/business-science/tidyquant/blob/master/NEWS.md Create a stock index using the `tq_index()` function. The previously deprecated `tq_get(get = "stock.index")` should be replaced with this function. ```r tq_index() ``` -------------------------------- ### Install tidyquant CRAN Version Source: https://github.com/business-science/tidyquant/blob/master/README.md Install the stable version of tidyquant from CRAN. ```r install.packages("tidyquant") ``` -------------------------------- ### List Available Data Sources with tq_get_options() Source: https://context7.com/business-science/tidyquant/llms.txt Returns a character vector of all valid `get` argument values that can be used with the `tq_get()` function. This helps in identifying the available data sources. ```r 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" ``` -------------------------------- ### Retrieve Key Ratios with tq_get Source: https://github.com/business-science/tidyquant/blob/master/NEWS.md Use `tq_get` with `get = "key.ratios"` to retrieve 10 years of key performance ratios from Morningstar. Supports multiple symbols. ```r tq_get("AAPL", get = "key.ratios") ``` -------------------------------- ### Get Financial Data with tq_get() Source: https://context7.com/business-science/tidyquant/llms.txt Retrieves various types of financial and economic data from multiple sources. Ensure API keys are set for services like Quandl, Tiingo, and Alpha Vantage. Data can be fetched for single or multiple tickers, with options for date ranges and specific data types. ```r library(tidyquant) library(dplyr) # List all available data sources tq_get_options() # [1] "stock.prices" "stock.prices.japan" "dividends" # [4] "splits" "economic.data" "quandl" ... # Single stock — last 10 years of daily OHLCV from Yahoo Finance aapl <- tq_get("AAPL") # # A tibble: 2,519 × 8 # symbol date open high low close volume adjusted # # 1 AAPL 2014-01-02 79.4 79.6 78.9 79.0 58671200 68.2 # ... # Multiple stocks with a date range stocks <- tq_get(c("META", "AMZN", "NFLX", "GOOG"), get = "stock.prices", from = "2020-01-01", to = "2023-12-31") # Dividends tq_get("AAPL", get = "dividends", from = "2010-01-01") # Stock splits tq_get("TSLA", get = "splits") # FRED economic data (e.g. WTI crude oil price) wti <- tq_get("DCOILWTICO", get = "economic.data", from = "2015-01-01") # Nasdaq Data Link / Quandl (API key required) quandl_api_key("YOUR_KEY") tq_get("EIA/PET_MTTIMUS1_M", get = "quandl", from = "2010-01-01") # Tiingo (API key required) tiingo_api_key("YOUR_KEY") tq_get(c("AAPL", "GOOG"), get = "tiingo", from = "2020-01-01", to = "2023-12-31") # Tiingo sub-daily IEX prices (5-min bars) tq_get("AAPL", get = "tiingo.iex", from = "2023-01-03", to = "2023-01-06", resample_frequency = "5min") # Tiingo cryptocurrency prices tq_get(c("btcusd", "ethusd"), get = "tiingo.crypto", from = "2023-01-01", to = "2023-03-01", resample_frequency = "1day") # Alpha Vantage (API key required) av_api_key("YOUR_KEY") tq_get("AAPL", get = "alphavantager", av_fun = "TIME_SERIES_DAILY_ADJUSTED", outputsize = "full") # Scale to a data frame of tickers tibble(symbol = c("AAPL", "MSFT", "TSLA")) %>% tq_get(get = "stock.prices", from = "2022-01-01", to = "2022-12-31") ``` -------------------------------- ### Get Quandl Data with tidyquant Source: https://github.com/business-science/tidyquant/blob/master/NEWS.md Use `tq_get` with `get = "quandl"` as a wrapper for Quandl::Quandl() to pull multiple Quandl codes. For datatables, use `get = "quandl.datatable"`. ```r tq_get(get = "quandl") ``` ```r tq_get(get = "quandl.datatable") ``` -------------------------------- ### Compound Data Gets with tidyquant Source: https://github.com/business-science/tidyquant/blob/master/NEWS.md Enable compound data retrieval by passing a vector of `get` arguments to `tq_get()`, such as `tq_get("AAPL", get = c("stock.prices", "financials"))`. ```r tq_get("AAPL", get = c("stock.prices", "financials")) ``` -------------------------------- ### tq_get_options() Source: https://context7.com/business-science/tidyquant/llms.txt Returns the character vector of valid `get` argument values that can be passed to `tq_get()`. ```APIDOC ## tq_get_options() ### Description Returns the character vector of valid `get` argument values that can be passed to `tq_get()`. ### Method GET ### Endpoint N/A (R function) ### Parameters None ### Request Example ```r tq_get_options() ``` ### Response #### Success Response (200) Returns a character vector of available data sources. #### Response Example ```r # [1] "stock.prices" "stock.prices.japan" "dividends" # [4] "splits" "economic.data" "quandl" # [7] "quandl.datatable" "tiingo" "tiingo.iex" # [10] "tiingo.crypto" "alphavantager" "alphavantage" # [13] "rblpapi" ``` ``` -------------------------------- ### Get Index Constituents with tq_index() Source: https://context7.com/business-science/tidyquant/llms.txt Downloads the current constituent list for major US stock indexes. Use `use_fallback = TRUE` to access bundled data when network is unavailable. The output includes symbol, company name, weight, and sector. ```r # Available indexes tq_index_options() # [1] "DOW" "DOWGLOBAL" "SP400" "SP500" "SP600" # Get S&P 500 constituents sp500 <- tq_index("SP500") # # A tibble: 503 × 5 # symbol company weight sector # # 1 MSFT Microsoft Corp 0.0722 Information Technology # ... # Use bundled fallback data sp500_fallback <- tq_index("SP500", use_fallback = TRUE) # Combine with tq_get to get prices for all index members sp500 %>% slice(1:5) %>% tq_get(get = "stock.prices", from = "2023-01-01", to = "2023-12-31") ``` -------------------------------- ### Retrieve Key Statistics with tq_get Source: https://github.com/business-science/tidyquant/blob/master/NEWS.md Use `tq_get` with `get = "key.stats"` to fetch current key statistics for a given symbol from Yahoo Finance. Supports multiple symbols. ```r tq_get("AAPL", get = "key.stats") ``` -------------------------------- ### Get Yahoo Japan Stock Prices with tidyquant Source: https://github.com/business-science/tidyquant/blob/master/NEWS.md Fetch stock prices from Yahoo Finance Japan using `tq_get(get = "stock.prices.japan")`, which wraps quantmod::getSymbols(src = "yahooj"). ```r tq_get(get = "stock.prices.japan") ``` -------------------------------- ### Get Index Data with tq_index() Source: https://github.com/business-science/tidyquant/blob/master/NEWS.md Use `tq_index()` to retrieve index data. This function has been fixed to address broken API calls. ```R tq_index("SP500") ``` -------------------------------- ### Handle HTTP Errors in tidyquant Source: https://github.com/business-science/tidyquant/blob/master/NEWS.md The `get = "key.ratios"` functionality now uses `httr::RETRY` to handle potential HTTP 500 errors during download, improving stability. ```r get = "key.ratios" ``` -------------------------------- ### Get Exchange Data with tq_exchange() Source: https://github.com/business-science/tidyquant/blob/master/NEWS.md Use `tq_exchange()` to retrieve exchange data. This function has been updated to work with changes to the NASDAQ website. ```R tq_exchange("NASDAQ") ``` -------------------------------- ### Retrieve Fund Holdings with tq_fund_holdings() Source: https://github.com/business-science/tidyquant/blob/master/NEWS.md Use `tq_fund_holdings()` to get fund holdings and compositions. Specify the fund symbol and the data source. ```R tq_fund_holdings("SPY", source = "SSGA") ``` -------------------------------- ### Get Exchange Stock Lists with tidyquant Source: https://github.com/business-science/tidyquant/blob/master/NEWS.md Retrieve stock lists for NASDAQ, NYSE, and AMEX exchanges using `tq_exchange()`. Use `tq_exchange_options()` to view available exchange options. ```r tq_exchange() ``` ```r tq_exchange_options() ``` -------------------------------- ### Download Exchange Stock Options Source: https://context7.com/business-science/tidyquant/llms.txt Use `tq_exchange_options()` to see available exchanges. Download all stocks for a specific exchange using `tq_exchange()`. The output includes symbol, company name, last sale price, market cap, country, IPO year, sector, and industry. ```r tq_exchange_options() # [1] "AMEX" "NASDAQ" "NYSE" nasdaq_stocks <- tq_exchange("NASDAQ") # # A tibble: 4,157 × 8 # symbol company last.sale.price market.cap country ipo.year sector industry # # 1 AACG ATA Creativity … 1.18 19561912 China 2008 … … # ... # Filter by sector and retrieve prices nasdaq_stocks %>% filter(sector == "Technology", market.cap > 1e10) %>% slice(1:3) %>% select(symbol) %>% tq_get(from = "2023-01-01", to = "2023-06-30") ``` -------------------------------- ### Build and Apply Portfolio Weights Source: https://context7.com/business-science/tidyquant/llms.txt Constructs a tibble of portfolio weights and applies them to financial return data using tq_portfolio. Ensure weights sum to 1 for each portfolio. ```r weights_tbl <- tibble( portfolio = rep(1:3, each = 4), symbol = rep(c("META","AMZN","NFLX","GOOG"), 3), weights = c(0.25, 0.25, 0.25, 0.25, # equal weight 0.40, 0.30, 0.20, 0.10, # tilted META/AMZN 0.10, 0.20, 0.30, 0.40) # tilted NFLX/GOOG ) %>% group_by(portfolio) tq_portfolio(data = mult_returns, assets_col = symbol, returns_col = monthly.returns, weights = weights_tbl) ``` -------------------------------- ### Create Portfolio with Tibble Weights Source: https://context7.com/business-science/tidyquant/llms.txt Constructs a portfolio using a tibble for asset weights. Assets not specified in the tibble will have a default weight of zero. ```r weights_tbl <- tibble( symbol = c("META", "AMZN", "NFLX"), weights = c(0.50, 0.25, 0.25) ) tq_portfolio(data = monthly_returns, assets_col = symbol, returns_col = monthly.returns, weights = weights_tbl) ``` -------------------------------- ### Create Portfolio with Numeric Weights Source: https://context7.com/business-science/tidyquant/llms.txt Constructs a portfolio using a numeric vector for asset weights. The order of weights must match the alphabetical order of assets. ```r weights <- c(0.50, 0.25, 0.25, 0.00) # META, AMZN, NFLX, GOOG tq_portfolio(data = monthly_returns, assets_col = symbol, returns_col = monthly.returns, weights = weights, col_rename = "portfolio.returns", wealth.index = FALSE) ``` -------------------------------- ### R: Store API Keys for Quandl, Tiingo, and Alpha Vantage Source: https://context7.com/business-science/tidyquant/llms.txt Store provider API keys in the R session, which are automatically used by tq_get(). Keys can be persisted in .Renviron when set via underlying packages. ```r # Nasdaq Data Link (formerly Quandl) quandl_api_key("YOUR_QUANDL_KEY") quandl_api_key() # returns current key # Tiingo tiingo_api_key("YOUR_TIINGO_KEY") tiingo_api_key() # Alpha Vantage av_api_key("YOUR_ALPHAVANTAGE_KEY") av_api_key() # After setting keys, use tq_get normally tq_get("EIA/PET_MTTIMUS1_M", get = "quandl", from = "2015-01-01") tq_get("AAPL", get = "tiingo", from = "2020-01-01") tq_get("AAPL", get = "alphavantager", av_fun = "TIME_SERIES_DAILY_ADJUSTED", outputsize = "compact") ``` -------------------------------- ### tq_index() / tq_index_options() Source: https://context7.com/business-science/tidyquant/llms.txt Downloads the current constituent list for a major US stock index and returns symbol, company name, weight, and sector. `tq_index_options()` lists available indexes. ```APIDOC ## tq_index() / tq_index_options() ### Description Downloads the current constituent list for a major US stock index (S&P 500, S&P 400, S&P 600, Dow Jones, Dow Jones Global) from State Street Global Advisors. Returns symbol, company name, weight, and sector. Use `use_fallback = TRUE` to return the bundled snapshot when the network is unavailable. `tq_index_options()` lists available indexes. ### Parameters #### Path Parameters None #### Query Parameters - **index** (string) - The stock index to retrieve constituents for. Options include "DOW", "DOWGLOBAL", "SP400", "SP500", "SP600". - **use_fallback** (boolean, optional) - If TRUE, uses bundled fallback data when network is unavailable. Defaults to FALSE. ### Request Example ```r # Available indexes tq_index_options() # Get S&P 500 constituents sp500 <- tq_index("SP500") # Use bundled fallback data sp500_fallback <- tq_index("SP500", use_fallback = TRUE) # Combine with tq_get to get prices for all index members sp500 %>% slice(1:5) %>% tq_get(get = "stock.prices", from = "2023-01-01", to = "2023-12-31") ``` ### Response #### Success Response (200) Returns a tibble containing the index constituents with columns: `symbol`, `company`, `weight`, and `sector`. #### Response Example ```r # Example for sp500 <- tq_index("SP500") # A tibble: 503 × 5 # symbol company weight sector # # 1 MSFT Microsoft Corp 0.0722 Information Technology # ... ``` ``` -------------------------------- ### Add Dividends and Splits to tq_get() Source: https://github.com/business-science/tidyquant/blob/master/NEWS.md The `tq_get()` function now supports 'dividends' and 'splits' options, leveraging fixes in the `quantmod` package. ```R tq_get() - Add "dividends" and "splits" get options ``` -------------------------------- ### Fix theme_tq() issues Source: https://github.com/business-science/tidyquant/blob/master/NEWS.md Resolved issues in `theme_tq()` related to `%+replace%`, `theme_gray`, and `rel` not being found. ```R theme_tq() ``` -------------------------------- ### Download Fund Holdings Source: https://context7.com/business-science/tidyquant/llms.txt Use `tq_fund_source_options()` to see supported fund providers. Download holdings for a specific fund ticker and source using `tq_fund_holdings()`. Returns symbol, company, weight, and sector for each holding. ```r tq_fund_source_options() # [1] "SSGA" # Holdings of the SPDR S&P 500 ETF spy_holdings <- tq_fund_holdings("SPY", source = "SSGA") # # A tibble: 503 × 5 # symbol company weight sector # # 1 MSFT Microsoft Corp 0.0722 Information Technology # ... # Holdings of the Technology Select Sector SPDR Fund xlk_holdings <- tq_fund_holdings("XLK", source = "SSGA") ``` -------------------------------- ### Calculate Portfolio Returns with tidyquant Source: https://github.com/business-science/tidyquant/blob/master/NEWS.md Use `tq_portfolio()` to aggregate portfolios from individual stock returns, integrating with PerformanceAnalytics functions. ```r tq_portfolio() ``` -------------------------------- ### Manage Quandl API Key with tidyquant Source: https://github.com/business-science/tidyquant/blob/master/NEWS.md Utilize `quandl_api_key()` as a wrapper for Quandl::Quandl.api_key() to manage your Quandl API key. ```r quandl_api_key() ``` -------------------------------- ### Streamline Data Retrieval with tq_get (Multiple Inputs) Source: https://github.com/business-science/tidyquant/blob/master/NEWS.md The `tq_get` function now accepts character vectors and data frames for the `x` argument, allowing for efficient retrieval of data for multiple symbols. ```r tq_get(x = c("AAPL", "MSFT"), get = "stock.prices") ``` -------------------------------- ### tq_portfolio() Source: https://context7.com/business-science/tidyquant/llms.txt Aggregates individual asset returns into a single portfolio return series using PerformanceAnalytics::Return.portfolio, supporting various weighting methods. ```APIDOC ## tq_portfolio() Aggregates individual asset returns (in long/tidy format) into a single portfolio return series using `PerformanceAnalytics::Return.portfolio()`. Supports three weighting methods: numeric vector, two-column tibble mapping asset → weight, or a grouped three-column tibble for multi-portfolio analysis. ### Usage ```r tq_portfolio(data, weights, col_rename = NULL, ...) # Parameters: # data: A tibble in long/tidy format with columns for date, symbol, and returns. # weights: Method for weighting assets. Can be: # - A numeric vector of weights (must sum to 1). # - A two-column tibble mapping asset symbols to weights. # - A grouped tibble with columns for date, symbol, and weight. # col_rename: Optional. Name for the resulting portfolio return column. # ...: Additional arguments passed to PerformanceAnalytics::Return.portfolio(). ``` ### Example ```r library(dplyr) # Example usage would typically follow, demonstrating different weighting methods. # For instance, creating a simple equally-weighted portfolio: # returns_data <- ... # Tibble with date, symbol, returns # portfolio_returns <- tq_portfolio(data = returns_data, weights = "equal", col_rename = "portfolio") ``` ``` -------------------------------- ### API Key Management Source: https://context7.com/business-science/tidyquant/llms.txt Functions to store API keys for financial data providers like Quandl, Tiingo, and Alpha Vantage within the R session. These keys are automatically utilized by `tq_get()`. ```APIDOC ## quandl_api_key() / tiingo_api_key() / av_api_key() Stores provider API keys in the R session (persisted in `.Renviron` when set via the underlying packages). These keys are then automatically used by `tq_get()` with the corresponding `get` option. ### Functions - `quandl_api_key("YOUR_QUANDL_KEY")`: Sets the Nasdaq Data Link (formerly Quandl) API key. - `quandl_api_key()`: Retrieves the currently set Quandl API key. - `tiingo_api_key("YOUR_TIINGO_KEY")`: Sets the Tiingo API key. - `tiingo_api_key()`: Retrieves the currently set Tiingo API key. - `av_api_key("YOUR_ALPHAVANTAGE_KEY")`: Sets the Alpha Vantage API key. - `av_api_key()`: Retrieves the currently set Alpha Vantage API key. ### Usage with tq_get After setting the API keys, `tq_get()` can be used with the respective `get` options (`quandl`, `tiingo`, `alphavantager`) to fetch data without explicitly passing the key each time. ``` -------------------------------- ### Create Multiple Portfolios Simultaneously Source: https://context7.com/business-science/tidyquant/llms.txt Constructs multiple portfolios simultaneously using repeated data and a structured weights table. Requires `dplyr`. ```r mult_returns <- tq_repeat_df(monthly_returns, n = 4) weights_vec <- c(0.50, 0.25, 0.25, 0.00, 0.00, 0.50, 0.25, 0.25, 0.25, 0.00, 0.50, 0.25, 0.25, 0.25, 0.00, 0.50) stocks <- c("META", "AMZN", "NFLX", "GOOG") weights_table <- tibble(stocks) %>% tq_repeat_df(n = 4) %>% bind_cols(tibble(weights = weights_vec)) %>% group_by(portfolio) tq_portfolio(data = mult_returns, assets_col = symbol, returns_col = monthly.returns, weights = weights_table) ``` -------------------------------- ### tq_fund_holdings() / tq_fund_source_options() Source: https://context7.com/business-science/tidyquant/llms.txt Downloads ETF or mutual fund holdings from a specified provider (currently SSGA) and lists available fund sources. ```APIDOC ## tq_fund_holdings() / tq_fund_source_options() Downloads current ETF or mutual fund holdings from a fund provider. Currently supports SSGA (State Street Global Advisors). Returns symbol, company, weight, and sector for every holding in the specified fund ticker. ### Usage ```r tq_fund_source_options() # Returns: Character vector of available fund sources (e.g., "SSGA") tq_fund_holdings(fund_ticker, source) # Parameters: # fund_ticker: Character string, the ticker symbol of the fund (e.g., "SPY") # source: Character string, the fund provider (e.g., "SSGA") # Returns: A tibble containing holdings data (symbol, company, weight, sector). ``` ### Example ```r # Get available fund sources tq_fund_source_options() # Holdings of the SPDR S&P 500 ETF spy_holdings <- tq_fund_holdings("SPY", source = "SSGA") # Holdings of the Technology Select Sector SPDR Fund xlk_holdings <- tq_fund_holdings("XLK", source = "SSGA") ``` ``` -------------------------------- ### Creating a Pivot Table for Monthly Average Volume Source: https://context7.com/business-science/tidyquant/llms.txt Generate a pivot table to show the monthly average volume by stock symbol and year. This demonstrates grouping by month and year and summarizing volume. ```R FANG %>$ pivot_table( .rows = c(symbol, ~ MONTH(date, label = TRUE)), .columns = ~ YEAR(date), .values = ~ AVERAGE(volume) ) ``` -------------------------------- ### tq_get() Source: https://context7.com/business-science/tidyquant/llms.txt Retrieves financial and economic data from multiple web sources and returns results as a tidy tibble. Accepts a single ticker string, a character vector of tickers, or a data frame whose first column contains tickers. ```APIDOC ## tq_get() ### Description Retrieves financial and economic data from multiple web sources (Yahoo Finance, FRED, Nasdaq Data Link / Quandl, Tiingo, Alpha Vantage, Bloomberg) and returns results as a tidy `tibble`. The `get` argument selects the data source; additional `...` arguments are forwarded to the underlying provider function. Accepts a single ticker string, a character vector of tickers, or a data frame whose first column contains tickers. ### Parameters #### Path Parameters None #### Query Parameters - **symbol** (string or character vector or data frame) - The ticker symbol(s) or data frame containing tickers. - **get** (string) - The data source to retrieve data from. Options include "stock.prices", "stock.prices.japan", "dividends", "splits", "economic.data", "quandl", "quandl.datatable", "tiingo", "tiingo.iex", "tiingo.crypto", "alphavantager", "alphavantage", "rblpapi". - **from** (string, optional) - The start date for the data retrieval. - **to** (string, optional) - The end date for the data retrieval. - **resample_frequency** (string, optional) - For Tiingo sub-daily data, specifies the resampling frequency (e.g., "5min", "1day"). - **av_fun** (string, optional) - For Alpha Vantage, specifies the Alpha Vantage function to use (e.g., "TIME_SERIES_DAILY_ADJUSTED"). - **outputsize** (string, optional) - For Alpha Vantage, specifies the output size (e.g., "full", "compact"). ### Request Example ```r library(tidyquant) library(dplyr) # Single stock — last 10 years of daily OHLCV from Yahoo Finance aapl <- tq_get("AAPL") # Multiple stocks with a date range stocks <- tq_get(c("META", "AMZN", "NFLX", "GOOG"), get = "stock.prices", from = "2020-01-01", to = "2023-12-31") # FRED economic data wti <- tq_get("DCOILWTICO", get = "economic.data", from = "2015-01-01") # Scale to a data frame of tickers tibble(symbol = c("AAPL", "MSFT", "TSLA")) %>% tq_get(get = "stock.prices", from = "2022-01-01", to = "2022-12-31") ``` ### Response #### Success Response (200) Returns a tibble containing the requested financial or economic data. The columns will vary depending on the `get` argument and the data source, but typically include columns like `symbol`, `date`, `open`, `high`, `low`, `close`, `volume`, `adjusted`, `dividend`, `split`, etc. #### Response Example ```r # Example for aapl <- tq_get("AAPL") # A tibble: 2,519 × 8 # symbol date open high low close volume adjusted # # 1 AAPL 2014-01-02 79.4 79.6 78.9 79.0 58671200 68.2 # ... ``` ``` -------------------------------- ### Creating a Pivot Table for Quarterly Returns Source: https://context7.com/business-science/tidyquant/llms.txt Generate a pivot table to summarize quarterly returns by stock symbol and year. This function groups data and applies summary functions, similar to Excel's pivot tables. ```R FANG %>$ pivot_table( .rows = c(symbol, ~ QUARTER(date)), .columns = ~ YEAR(date), .values = ~ PCT_CHANGE_FIRSTLAST(adjusted) ) ``` -------------------------------- ### Create tidyquant Themes with ggplot2 Source: https://github.com/business-science/tidyquant/blob/master/NEWS.md Use `theme_tq()` to create light, dark, and green themes for tidyquant visualizations integrated with ggplot2. Exported `palette_()` functions are used to create scales. ```r theme_tq() ``` ```r palette_() ``` -------------------------------- ### tq_exchange() / tq_exchange_options() Source: https://context7.com/business-science/tidyquant/llms.txt Downloads stock data from a specified exchange (AMEX, NASDAQ, NYSE) and provides options for exchange names. ```APIDOC ## tq_exchange() / tq_exchange_options() Downloads all stocks listed on a named exchange (AMEX, NASDAQ, or NYSE) from the Nasdaq stock screener API. Returns symbol, company name, last sale price, market cap, country, IPO year, sector, and industry. ### Usage ```r tq_exchange_options() # Returns: Character vector of available exchange options (e.g., "AMEX", "NASDAQ", "NYSE") tq_exchange("NASDAQ") # Returns: A tibble containing stock data for the NASDAQ exchange. ``` ### Example ```r # Get available exchange options tq_exchange_options() # Download NASDAQ stocks nasdaq_stocks <- tq_exchange("NASDAQ") # Filter and retrieve prices for technology stocks with market cap > 10 billion nasdaq_stocks %>% filter(sector == "Technology", market.cap > 1e10) %>% slice(1:3) %>% select(symbol) %>% tq_get(from = "2023-01-01", to = "2023-06-30") ``` ``` -------------------------------- ### Apply zoo rollapply Functions with tq_transform Source: https://github.com/business-science/tidyquant/blob/master/NEWS.md Integrates `zoo::rollapply()` functions for use with `tq_transform`. Use `tq_transform_fun_options()` to see the full list of compatible functions. ```r tq_transform(data, "SMA", n = 5) ``` -------------------------------- ### Calculate Monthly Returns for Stocks Source: https://context7.com/business-science/tidyquant/llms.txt Calculates monthly returns for each stock in a dataset. Requires the `dplyr` and `tidyquant` packages. ```r monthly_returns <- FANG %>% group_by(symbol) %>% tq_transmute(adjusted, periodReturn, period = "monthly", col_rename = "monthly.returns") ``` -------------------------------- ### Compute Portfolio Performance Statistics Source: https://context7.com/business-science/tidyquant/llms.txt Computes portfolio and asset performance statistics using functions from the `PerformanceAnalytics` package. Requires `dplyr` and `tidyquant`. Compatible `PerformanceAnalytics` functions can be viewed with `tq_performance_fun_options()`. ```r library(dplyr) # Get individual stock monthly returns Ra <- FANG %>% group_by(symbol) %>% tq_transmute(adjusted, periodReturn, period = "monthly", col_rename = "Ra") # Get S&P 500 baseline monthly returns Rb <- tq_get("^GSPC", get = "stock.prices", from = "2013-01-01", to = "2016-12-31") %>% tq_transmute(adjusted, periodReturn, period = "monthly", col_rename = "Rb") RaRb <- left_join(Ra, Rb, by = "date") # View compatible performance functions tq_performance_fun_options() %>% str(list.len = 5) # Sharpe Ratio (no baseline needed) RaRb %>% tq_performance(Ra = Ra, performance_fun = SharpeRatio, p = 0.95) # # A tibble: 4 × 4 # symbol `SharpeRatio(EtaDS)` `SharpeRatio(modVaR)` `SharpeRatio(VaR)` # # 1 AMZN 0.228 0.183 0.167 # CAPM table (baseline required) RaRb %>% tq_performance(Ra = Ra, Rb = Rb, performance_fun = table.CAPM) # Annualized returns RaRb %>% tq_performance(Ra = Ra, performance_fun = Return.annualized) ``` -------------------------------- ### Aggregate Asset Returns with tq_portfolio Source: https://context7.com/business-science/tidyquant/llms.txt Use `tq_portfolio()` to aggregate individual asset returns into a single portfolio return series. It supports numeric vectors, two-column tibbles (asset → weight), or grouped three-column tibbles for multi-portfolio analysis. Requires `dplyr` for data manipulation. ```r library(dplyr) ``` -------------------------------- ### Mutate and Transmute Data with tidyquant Source: https://github.com/business-science/tidyquant/blob/master/NEWS.md Use `tq_mutate()` and `tq_transmute()` to transform data. These functions now accept non-OHLC data via the `select` argument and work with `rollapply`. They also support PerformanceAnalytics functions for asset returns. ```r tq_mutate() ``` ```r tq_transmute() ``` -------------------------------- ### Apply zoo rollapply Functions with tq_mutate Source: https://github.com/business-science/tidyquant/blob/master/NEWS.md Integrates `zoo::rollapply()` functions for use with `tq_mutate`. Use `tq_transform_fun_options()` to see the full list of compatible functions. ```r tq_mutate(data, "SMA", n = 5) ``` -------------------------------- ### Plotting 50-day and 200-day Simple Moving Averages Source: https://context7.com/business-science/tidyquant/llms.txt Visualize 50-day and 200-day Simple Moving Averages (SMA) on a stock's adjusted closing price. Requires the tidyquant package and a data frame with 'date' and 'adjusted' columns. ```R aapl %>$ ggplot(aes(x = date, y = adjusted)) + geom_line(alpha = 0.5) + geom_ma(ma_fun = SMA, n = 50, color = "blue", linetype = "solid") + geom_ma(ma_fun = SMA, n = 200, color = "red", linetype = "solid") + coord_x_date(xlim = c("2016-01-01", "2016-12-31"), ylim = c(90, 130)) + labs(title = "AAPL: 50-day vs 200-day SMA") + theme_tq() ``` -------------------------------- ### Search Quandl Data with tidyquant Source: https://github.com/business-science/tidyquant/blob/master/NEWS.md Use `quandl_search` as a wrapper for Quandl::Quandl.search() to search for Quandl data. ```r quandl_search ``` -------------------------------- ### R: Duplicate Data Frame for Multi-Portfolio Analysis Source: https://context7.com/business-science/tidyquant/llms.txt Use tq_repeat_df() to duplicate a data frame 'n' times row-wise and add a 'portfolio' index column. This is a preprocessing step for multi-portfolio analysis with tq_portfolio(). ```r library(dplyr) monthly_returns <- FANG %>% group_by(symbol) %>% tq_transmute(adjusted, periodReturn, period = "monthly", col_rename = "monthly.returns") # Duplicate for 3 portfolio scenarios mult_returns <- tq_repeat_df(monthly_returns, n = 3) # # A tibble: 720 × 4 # # Groups: portfolio [3] # portfolio symbol date monthly.returns # # 1 1 AMZN 2013-01-31 0.126 # ... ``` -------------------------------- ### Applying tidyquant Green Theme (theme_tq_green) Source: https://context7.com/business-science/tidyquant/llms.txt Apply a green-themed ggplot2 theme from tidyquant. This provides an alternative color scheme for financial visualizations. ```R aapl %>$ ggplot(aes(x = date, y = adjusted)) + geom_line() + theme_tq_green() ``` -------------------------------- ### Creating Bollinger Bands with SMA Source: https://context7.com/business-science/tidyquant/llms.txt Generate Bollinger Bands using a 50-day Simple Moving Average (SMA) and a standard deviation multiplier of 2. Requires 'high', 'low', and 'close' aesthetics. ```R aapl %>$ ggplot(aes(x = date, y = close)) + geom_line(alpha = 0.5) + geom_bbands(aes(high = high, low = low, close = close), ma_fun = SMA, n = 50, sd = 2, color_ma = "darkblue", color_bands = "red", fill = "lightblue", alpha = 0.2) + coord_x_date(xlim = c(as_date("2016-12-31") - dyears(1), as_date("2016-12-31")), ylim = c(85, 135)) + labs(title = "AAPL Bollinger Bands (50-day SMA, 2σ)") + theme_tq() ``` -------------------------------- ### Applying tidyquant Light Theme (theme_tq) Source: https://context7.com/business-science/tidyquant/llms.txt Apply the default light ggplot2 theme provided by tidyquant. This theme uses the package's navy-and-teal color palette and is a drop-in replacement for theme_grey(). ```R aapl %>$ ggplot(aes(x = date, y = adjusted)) + geom_line(color = "#2c3e50") + geom_ma(n = 50) + labs(title = "AAPL Adjusted Close", subtitle = "50-day SMA") + theme_tq() ``` -------------------------------- ### Visualize Bollinger Bands with geom_bbands Source: https://github.com/business-science/tidyquant/blob/master/NEWS.md Visualizes Bollinger Bands, compatible with ggplot2 and supports the same moving averages as geom_ma. ```r geom_bbands() ``` -------------------------------- ### Create Bar Chart of Stock Prices Source: https://context7.com/business-science/tidyquant/llms.txt Generates a bar chart for stock prices using OHLC data. Requires `dplyr`, `ggplot2`, and `tidyquant`. This variant uses `geom_barchart`. ```r library(dplyr) library(ggplot2) aapl <- tq_get("AAPL", from = "2016-01-01", to = "2016-12-31") # Bar chart variant aapl %>% ggplot(aes(x = date, y = close)) + geom_barchart(aes(open = open, high = high, low = low, close = close)) + coord_x_date(xlim = c("2016-09-01", "2016-12-31")) + theme_tq_dark() ``` -------------------------------- ### Creating Bollinger Bands with EMA Source: https://context7.com/business-science/tidyquant/llms.txt Generate Bollinger Bands using an Exponential Moving Average (EMA). The 'wilder' argument can be set to TRUE for Wilder's smoothing method. ```R aapl %>$ ggplot(aes(x = date, y = close)) + geom_line() + geom_bbands(aes(high = high, low = low, close = close), ma_fun = EMA, wilder = TRUE, n = 20) + coord_x_date(xlim = c("2016-01-01", "2016-12-31"), ylim = c(85, 135)) + theme_tq() ``` -------------------------------- ### Convert Symbols with sp_index() Source: https://github.com/business-science/tidyquant/blob/master/NEWS.md The `sp_index()` function can convert symbols like "BRK.B" to "BRK-B" for compatibility with Yahoo Finance. ```R sp_index() ``` -------------------------------- ### Create Candlestick Chart with SMA Overlay Source: https://context7.com/business-science/tidyquant/llms.txt Generates a candlestick chart for stock prices with a Simple Moving Average (SMA) overlay. Requires `dplyr`, `ggplot2`, and `tidyquant`. The chart displays OHLC data and a 50-day SMA. ```r library(dplyr) library(ggplot2) aapl <- tq_get("AAPL", from = "2016-01-01", to = "2016-12-31") # Candlestick chart with 50-day SMA overlay aapl %>% ggplot(aes(x = date, y = close)) + geom_candlestick(aes(open = open, high = high, low = low, close = close), colour_up = "darkgreen", colour_down = "red", fill_up = "darkgreen", fill_down = "red") + geom_ma(ma_fun = SMA, n = 50, color = "dodgerblue", linetype = "solid") + coord_x_date(xlim = c("2016-06-01", "2016-12-31"), ylim = c(90, 120)) + labs(title = "AAPL Candlestick Chart (2016 H2)", x = "Date", y = "Price (USD)") + theme_tq() ``` -------------------------------- ### Excel Date Functions Source: https://context7.com/business-science/tidyquant/llms.txt Provides over 50 Excel-style date and time utilities for converting, extracting, performing date math, and creating date sequences. These functions integrate with lubridate and timeDate calendars and accept character strings or date objects. ```APIDOC ## Excel Date Functions Provides 50+ Excel-style date/time utilities (converters, extractors, date math, date sequences, and date collapsers). All accept character strings or date objects and integrate with `lubridate` and `timeDate` calendars. ### Converters - `AS_DATE(string)`: Converts a string to a date. - `YMD(string)`: Parses a string in Year-Month-Day format. - `MDY(string)`: Parses a string in Month-Day-Year format. - `DMY(string)`: Parses a string in Day-Month-Year format. - `YMD_HMS(string)`: Parses a string in Year-Month-Day Hour:Minute:Second format. ### Extractors - `YEAR(date)`: Extracts the year from a date. - `QUARTER(date)`: Extracts the quarter from a date. - `MONTH(date)`: Extracts the month from a date. - `WEEKDAY(date)`: Extracts the weekday from a date. - `DAY(date)`: Extracts the day from a date. ### Current time - `TODAY()`: Returns the current date. - `NOW()`: Returns the current date and time. ### Date math - `EOMONTH(date, months)`: Returns the last day of the month, offset by `months`. - `EDATE(date, months)`: Returns the date offset by `months`. - `NET_WORKDAYS(start_date, end_date, holidays)`: Calculates the number of net workdays between two dates. - `YEARFRAC(start_date, end_date)`: Calculates the fraction of a year between two dates. ### Date sequences - `DATE_SEQUENCE(start_date, end_date)`: Generates a sequence of daily dates. - `WORKDAY_SEQUENCE(start_date, end_date)`: Generates a sequence of business days. - `HOLIDAY_SEQUENCE(start_date, end_date, calendar)`: Generates a sequence of holidays for a specified calendar. ### Date collapsers - `FLOOR_DATE(date, by)`: Rounds a date down to the nearest specified unit (e.g., 'month', 'quarter'). - `CEILING_DATE(date, by)`: Rounds a date up to the nearest specified unit. - `ROUND_DATE(date, by)`: Rounds a date to the nearest specified unit. ### Integration with pivot_table Example usage within a `pivot_table` for data aggregation and transformation. ``` -------------------------------- ### Create Bar Charts with geom_barchart Source: https://github.com/business-science/tidyquant/blob/master/NEWS.md Integrates with ggplot2 to create bar charts for financial data. ```r geom_barchart() ``` -------------------------------- ### Rename Arguments in tq_transform_xy Source: https://github.com/business-science/tidyquant/blob/master/NEWS.md The `.x` and `.y` arguments in `tq_transform_xy` have been renamed to `x` and `y` respectively for consistency. ```r tq_transform_xy(data, x = close, y = open, fun = "delta") ``` -------------------------------- ### Applying tidyquant Dark Theme (theme_tq_dark) Source: https://context7.com/business-science/tidyquant/llms.txt Apply a dark ggplot2 theme from tidyquant, suitable for financial charts. This theme also uses the package's color palette and can be used with candlestick charts. ```R aapl %>$ ggplot(aes(x = date, y = adjusted)) + geom_candlestick(aes(open = open, high = high, low = low, close = close)) + coord_x_date(xlim = c("2023-01-01", "2023-12-31")) + theme_tq_dark() ``` -------------------------------- ### Excel Statistical Summary Functions Source: https://context7.com/business-science/tidyquant/llms.txt Offers 15+ Excel-named statistical summary functions that ignore NA values by default. These are optimized for use within `dplyr::summarise()`, `tq_transmute()`, and `pivot_table()`. ```APIDOC ## Excel Statistical Summary Functions Provides 15+ Excel-named summary functions (SUM, AVERAGE, MEDIAN, etc.) that ignore `NA` values by default. Designed for use inside `dplyr::summarise()`, `tq_transmute()`, and `pivot_table()`. ### Scalar Usage Examples - `SUM(vector)`: Calculates the sum of a vector. - `AVERAGE(vector)`: Calculates the average of a vector. - `MEDIAN(vector)`: Calculates the median of a vector. - `MIN(vector)`: Finds the minimum value in a vector. - `MAX(vector)`: Finds the maximum value in a vector. - `STDEV(vector)`: Calculates the standard deviation of a vector. - `COUNT(vector)`: Counts the number of non-NA values in a vector. - `COUNT_UNIQUE(vector)`: Counts the number of unique non-NA values. - `FIRST(vector)`: Returns the first non-NA value. - `LAST(vector)`: Returns the last non-NA value. - `NTH(vector, n)`: Returns the n-th non-NA value. - `PCT_CHANGE_FIRSTLAST(vector)`: Calculates the percentage change between the first and last non-NA values. - `CHANGE_FIRSTLAST(vector)`: Calculates the absolute change between the first and last non-NA values. ### Usage within dplyr Pipelines Demonstrates how to use these functions within `dplyr::summarise()` for grouped data analysis. ``` -------------------------------- ### Plotting Elastic Volume-Weighted Moving Average (EVWMA) Source: https://context7.com/business-science/tidyquant/llms.txt Visualize the Elastic Volume-Weighted Moving Average (EVWMA) on a stock's adjusted closing price. This requires volume data and uses the EVWMA function. ```R aapl %>$ ggplot(aes(x = date, y = adjusted)) + geom_line(alpha = 0.4) + geom_ma(aes(volume = volume), ma_fun = EVWMA, n = 50, color = "purple") + coord_x_date(xlim = c("2016-01-01", "2016-12-31"), ylim = c(90, 130)) + theme_tq() ```