### Quantmod Getting Started Source: https://github.com/joshuaulrich/quantmod/blob/master/README.md Basic usage of the quantmod package, including importing data with `getSymbols()` and visualizing with `chartSeries()`. ```APIDOC ## Getting Started It is possible to import data from a variety of sources with one quantmod function: `getSymbols()`. ### Example 1: Importing data from Yahoo Finance and FRED ```r > getSymbols("AAPL", src = "yahoo") # from yahoo finance [1] "AAPL" > getSymbols("DEXJPUS", src = "FRED") # FX rates from FRED [1] "DEXJPUS" ``` ### Example 2: Visualizing data and adding technical indicators Once you've imported the data, you can use `chartSeries()` to visualize it and even add technical indicators from the [TTR](https://CRAN.R-project.org/package=TTR) package: ```r > getSymbols("AAPL") [1] "AAPL" > chartSeries(AAPL) > addMACD() > addBBands() ``` ``` -------------------------------- ### Install quantmod Package Source: https://github.com/joshuaulrich/quantmod/blob/master/README.md Instructions for installing the quantmod package from CRAN or the development version from GitHub. ```R install.packages("quantmod") remotes::install_github("joshuaulrich/quantmod") devtools::install_github("joshuaulrich/quantmod") ``` -------------------------------- ### Quantmod Installation Source: https://github.com/joshuaulrich/quantmod/blob/master/README.md Instructions for installing the quantmod R package from CRAN or development versions from GitHub. ```APIDOC ## Installation The current release is available on [CRAN](https://CRAN.R-project.org/package=quantmod), which you can install via: ```r install.packages("quantmod") ``` To install the development version, you need to clone the repository and build from source, or run one of: ```r # lightweight remotes::install_github("joshuaulrich/quantmod") # or devtools::install_github("joshuaulrich/quantmod") ``` You may need tools to compile C, C++, or Fortran code. See the relevant appendix in the [R Installation and Administration manual](https://cran.r-project.org/doc/manuals/r-release/R-admin.html) for your operating system. ``` -------------------------------- ### Example of a Well-Structured Git Commit Message Source: https://github.com/joshuaulrich/quantmod/wiki/Contributing-Guide This snippet demonstrates the recommended format for a commit message, including a concise subject line, a detailed body explaining the 'what' and 'why', and a reference to the relevant issue tracker. ```text Correct endpoints when index is before the epoch The endpoints C code casts the double index to long, which truncates it toward zero. This behavior is desired when the index is positive, because it moves the endpoint *back* in time. But when the index is negative, truncating toward zero moves the endpoint *forward* in time. This is also an issue if the index value is stored as integer, since the C99 specification states that integer division truncates toward zero. If the first index value is less than zero, branch into a special case to handle pre-epoch index values. This avoids performance degradation if all index values are after the epoch. If the index value is less than zero, simply add 1 to offset the truncation toward zero. We also need to furthre adjust the potential endpoint value if the index is exactly equal to zero. Fixes #144. ``` -------------------------------- ### Convenience Charting Functions: barChart, candleChart, lineChart Source: https://context7.com/joshuaulrich/quantmod/llms.txt Provides examples of using convenience wrapper functions (barChart, candleChart, lineChart) that simplify the creation of specific financial chart types by calling chartSeries with predefined settings. ```R getSymbols("AAPL") # Bar chart (OHLC bars) barChart(AAPL) barChart(AAPL, subset = "2023") # Candlestick chart candleChart(AAPL) candleChart(AAPL, theme = chartTheme("white")) # Line chart lineChart(AAPL) lineChart(AAPL, subset = "last 6 months") ``` -------------------------------- ### GET /getOptionChain Source: https://context7.com/joshuaulrich/quantmod/llms.txt Retrieves option chain data including calls and puts for a specified underlying symbol. ```APIDOC ## GET /getOptionChain ### Description Retrieves call and put option data for a symbol, supporting specific expiration dates and alternative data sources. ### Method GET ### Endpoint getOptionChain(symbol, Exp, src, api.key) ### Parameters #### Path Parameters - **symbol** (string) - Required - The ticker symbol #### Query Parameters - **Exp** (string) - Optional - Expiration date or range - **src** (string) - Optional - Data source (e.g., "orats") - **api.key** (string) - Optional - API key for external sources ### Request Example getOptionChain("AAPL", Exp = "2024-01/2024-06") ### Response #### Success Response (200) - **calls** (data.frame) - Call options data - **puts** (data.frame) - Put options data ``` -------------------------------- ### GET /tradeModel Source: https://context7.com/joshuaulrich/quantmod/llms.txt Applies a fitted model to generate trading signals based on predictions. ```APIDOC ## GET /tradeModel ### Description Generates trading signals by applying a previously fitted model to the data. ### Method GET ### Endpoint tradeModel(model) ### Parameters #### Query Parameters - **model** (quantmodModel) - Required - The fitted model object. ### Request Example { "model": "q.model" } ### Response #### Success Response (200) - **signals** (xts) - Time series of generated trading signals. #### Response Example { "signals": "[...data...]" } ``` -------------------------------- ### GET /Delt Source: https://context7.com/joshuaulrich/quantmod/llms.txt Calculates k-period percent differences or returns for time series data. ```APIDOC ## GET /Delt ### Description Calculates arithmetic or logarithmic percent changes for a series or between two series. ### Method GET ### Endpoint Delt(x1, x2, k, type) ### Parameters #### Query Parameters - **x1** (numeric) - Required - First series - **x2** (numeric) - Optional - Second series for comparison - **k** (integer) - Optional - Number of periods to lag - **type** (string) - Optional - "arithmetic" or "log" ### Request Example Delt(Cl(AAPL), k = 1, type = "arithmetic") ### Response #### Success Response (200) - **result** (xts) - Time series of calculated percent changes ``` -------------------------------- ### GET /getDividends Source: https://context7.com/joshuaulrich/quantmod/llms.txt Retrieves dividend history for a given symbol with options for date ranges and split adjustment. ```APIDOC ## GET /getDividends ### Description Fetches historical dividend data for a specified stock symbol. ### Method GET ### Endpoint getDividends(symbol, from, to, split.adjust) ### Parameters #### Path Parameters - **symbol** (string) - Required - The ticker symbol (e.g., "AAPL") #### Query Parameters - **from** (string) - Optional - Start date in YYYY-MM-DD format - **to** (string) - Optional - End date in YYYY-MM-DD format - **split.adjust** (boolean) - Optional - Whether to adjust dividends for stock splits ### Request Example getDividends("AAPL", from = "2020-01-01", to = "2023-12-31") ### Response #### Success Response (200) - **data** (xts) - Time series object containing dividend history ``` -------------------------------- ### Quantmod Contributing and Support Source: https://github.com/joshuaulrich/quantmod/blob/master/README.md Information on how to contribute to quantmod development and where to seek support. ```APIDOC ## Contributing Please see the [contributing guide](https://github.com/joshuaulrich/quantmod/wiki/Contributing-Guide). ## Supporting quantmod development If you are interested in supporting the ongoing development and maintenance of quantmod, please consider [becoming a sponsor](https://github.com/sponsors/joshuaulrich). ## Have a question? Ask your question on [Stack Overflow](http://stackoverflow.com/questions/tagged/r) or the [R-SIG-Finance](https://stat.ethz.ch/mailman/listinfo/r-sig-finance) mailing list (you must subscribe to post). ``` -------------------------------- ### Retrieve Financial Data with getSymbols Source: https://github.com/joshuaulrich/quantmod/blob/master/README.md Demonstrates how to import financial data from external sources like Yahoo Finance and FRED using the getSymbols function. ```R getSymbols("AAPL", src = "yahoo") getSymbols("DEXJPUS", src = "FRED") ``` -------------------------------- ### Visualize Financial Data and Indicators Source: https://github.com/joshuaulrich/quantmod/blob/master/README.md Shows how to create a chart series for imported data and overlay technical indicators such as MACD and Bollinger Bands. ```R getSymbols("AAPL") chartSeries(AAPL) addMACD() addBBands() ``` -------------------------------- ### periodReturn: Calculate Various Periodic Returns Source: https://context7.com/joshuaulrich/quantmod/llms.txt Demonstrates the calculation of financial returns at different time frequencies (daily, weekly, monthly, quarterly, yearly) using the periodReturn function and its wrappers. It supports arithmetic and logarithmic return types and allows subsetting by date. ```R getSymbols("QQQ") # Calculate returns at different frequencies dailyReturn(QQQ) # Daily returns weeklyReturn(QQQ) # Weekly returns monthlyReturn(QQQ) # Monthly returns quarterlyReturn(QQQ) # Quarterly returns yearlyReturn(QQQ) # Yearly returns (same as annualReturn) annualReturn(QQQ) # Annual returns # Get all available return periods at once allReturns(QQQ) # Specify period using periodReturn periodReturn(QQQ, period = "monthly") periodReturn(QQQ, period = "quarterly") periodReturn(QQQ, period = "yearly") # Subset by date periodReturn(QQQ, period = "yearly", subset = "2020::") # 2020 onwards periodReturn(QQQ, period = "yearly", subset = "2020") # Only 2020 # Arithmetic vs logarithmic returns dailyReturn(QQQ, type = "arithmetic") # Default dailyReturn(QQQ, type = "log") # Continuous/log returns # Exclude incomplete leading period monthlyReturn(QQQ, leading = FALSE) # Example: Performance analysis monthly_rets <- monthlyReturn(QQQ) annual_rets <- yearlyReturn(QQQ) # Calculate cumulative returns cumprod(1 + dailyReturn(QQQ)) ``` -------------------------------- ### POST /buildModel Source: https://context7.com/joshuaulrich/quantmod/llms.txt Fits a specified trading model using various machine learning and statistical methods. ```APIDOC ## POST /buildModel ### Description Fits a specified model using various machine learning and statistical methods such as lm, randomForest, or svm. ### Method POST ### Endpoint buildModel(model, method, training.per, ...) ### Parameters #### Request Body - **model** (quantmodModel) - Required - The model object created by specifyModel. - **method** (string) - Required - The algorithm to use (e.g., 'lm', 'randomForest', 'svm'). - **training.per** (vector) - Required - Date range for training. ### Request Example { "method": "randomForest", "training.per": ["2020-01-01", "2022-12-31"] } ### Response #### Success Response (200) - **fitted_model** (object) - The trained model object. #### Response Example { "status": "success", "model_type": "randomForest" } ``` -------------------------------- ### chartSeries: Create Financial Charts Source: https://context7.com/joshuaulrich/quantmod/llms.txt Illustrates the creation of professional financial charts using chartSeries, supporting various chart types (candlesticks, bars, lines) and customization options. It includes automatic volume display, technical indicators, date range subsetting, and theming. ```R getSymbols("AAPL") # Basic candlestick chart with volume chartSeries(AAPL) # Different chart types chartSeries(AAPL, type = "candlesticks") # Default chartSeries(AAPL, type = "bars") # OHLC bars chartSeries(AAPL, type = "line") # Line chart chartSeries(AAPL, type = "matchsticks") # 1-pixel candles # Chart specific date range using xts-style subsetting chartSeries(AAPL, subset = "2023") # Year 2023 chartSeries(AAPL, subset = "2023-06::") # June 2023 onwards chartSeries(AAPL, subset = "2023-01::2023-06") # Jan-Jun 2023 chartSeries(AAPL, subset = "last 4 months") # Last 4 months chartSeries(AAPL, subset = "last 52 weeks") # Last year # Customize appearance chartSeries(AAPL, theme = chartTheme("white")) # White background chartSeries(AAPL, theme = chartTheme("black")) # Black background (default) # Remove volume chartSeries(AAPL, TA = NULL) # Add technical indicators during chart creation chartSeries(AAPL, TA = c(addVo(), addBBands(), addMACD())) # Use logarithmic scale chartSeries(AAPL, log.scale = TRUE) # Multi-color candles (4 color coding scheme) chartSeries(AAPL, multi.col = TRUE) # Custom up/down colors chartSeries(AAPL, up.col = "green", dn.col = "red") ``` -------------------------------- ### Fit Trading Models with buildModel Source: https://context7.com/joshuaulrich/quantmod/llms.txt Fits a specified model using various statistical and machine learning methods such as linear regression, random forests, or support vector machines. ```R q.model <- buildModel(q.model, method = "lm", training.per = c("2020-01-01", "2022-12-31")) q.model.rf <- buildModel(q.model, method = "randomForest", training.per = c("2020-01-01", "2022-12-31"), ntree = 500) q.model.svm <- buildModel(q.model, method = "svm", training.per = c("2020-01-01", "2022-12-31")) ``` -------------------------------- ### Data Loading and Management Source: https://context7.com/joshuaulrich/quantmod/llms.txt Functions for loading financial data from various sources, configuring data sources, and downloading real-time quotes and exchange rates. ```APIDOC ## getSymbols - Load Financial Data from Multiple Sources ### Description The `getSymbols` function is the primary data import mechanism in quantmod, supporting multiple data sources including Yahoo Finance, FRED, Alpha Vantage, Tiingo, MySQL databases, and CSV files. By default, it automatically assigns data to the calling environment with the symbol name as the variable name, though this can be disabled for explicit assignment. ### Method `getSymbols(Symbols, src = "yahoo", ...)` ### Endpoint N/A (R function) ### Parameters #### Path Parameters None #### Query Parameters - **Symbols** (character or character vector) - The stock symbol(s) or data identifier(s) to load. - **src** (character) - The data source (e.g., "yahoo", "FRED", "av", "tiingo", "MySQL", "csv"). Defaults to "yahoo". - **from** (character or Date) - The start date for the data. - **to** (character or Date) - The end date for the data. - **auto.assign** (logical) - If TRUE, data is automatically assigned to the environment. Defaults to TRUE. - **env** (environment) - The environment to assign the data to if `auto.assign` is TRUE. - **api.key** (character) - API key for sources like Alpha Vantage or Tiingo. - **dir** (character) - Directory path for loading from CSV files. ### Request Example ```r library(quantmod) # Load stock data from Yahoo Finance (default source) getSymbols("AAPL") # Load multiple symbols at once getSymbols(c("AAPL", "MSFT", "GOOG")) # Load from FRED getSymbols("CPIAUCNS", src = "FRED") # Specify date range getSymbols("AAPL", from = "2020-01-01", to = "2023-12-31") ``` ### Response #### Success Response (200) Data is typically returned as an object of class 'xts' (eXtensible Time Series) and assigned to a variable named after the symbol, or returned directly if `auto.assign = FALSE`. #### Response Example ```r # Example output structure for AAPL # AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted # 2007-01-03 86.29 86.58 81.90 83.80 309579900 11.17 ``` ``` ```APIDOC ## setSymbolLookup - Configure Default Data Sources ### Description The `setSymbolLookup` function allows users to pre-configure default data sources and parameters for specific symbols, making subsequent `getSymbols` calls simpler and more consistent across an analysis session. ### Method `setSymbolLookup(..., auto.assign = TRUE)` ### Endpoint N/A (R function) ### Parameters #### Path Parameters None #### Query Parameters - **Symbol configurations**: A list or named arguments where each name is a symbol and the value specifies the source and parameters (e.g., `AAPL = "yahoo"`, `DJI = list(name = "^DJI", src = "yahoo")`). - **auto.assign** (logical): If TRUE, applies the lookup configuration. Defaults to TRUE. ### Request Example ```r # Set default sources for specific symbols setSymbolLookup(AAPL = "yahoo", DIA = "MySQL", CPIAUCNS = "FRED") # Set with additional parameters setSymbolLookup(DJI = list(name = "^DJI", src = "yahoo")) # Clear a symbol's defaults setSymbolLookup(AAPL = NULL) ``` ### Response #### Success Response (200) Modifies the global symbol lookup table. No direct return value, but subsequent `getSymbols` calls will use the configured defaults. ``` ```APIDOC ## getQuote - Download Real-Time Stock Quotes ### Description The `getQuote` function fetches current stock quotes from Yahoo Finance or Alpha Vantage, providing real-time or near-real-time market data for one or more symbols. ### Method `getQuote(Symbols, src = "yahoo", ...)` ### Endpoint N/A (R function) ### Parameters #### Path Parameters None #### Query Parameters - **Symbols** (character or character vector) - The stock symbol(s) to get quotes for. - **src** (character) - The data source (e.g., "yahoo", "av"). Defaults to "yahoo". - **what** (function or character) - Specifies the fields to retrieve (e.g., `yahooQF()`, `yahooQuote.EOD`). - **api.key** (character) - API key for sources like Alpha Vantage. ### Request Example ```r # Get current quote for a single symbol getQuote("AAPL") # Get quotes for multiple symbols getQuote("AAPL;MSFT;GOOG") # Request specific fields getQuote("AAPL", what = yahooQF(c("Bid", "Ask", "Volume"))) # Get quote from Alpha Vantage getQuote("AAPL", src = "av", api.key = "your_api_key") ``` ### Response #### Success Response (200) A data frame containing the requested quote information for the specified symbols. #### Response Example ```r # Example output structure # Trade Time Last Change % Change Open High Low Volume # AAPL 2024-01-15 185.92 1.23 0.67% 184.50 186.74 184.22 52M ``` ``` ```APIDOC ## getFX - Download Exchange Rates ### Description The `getFX` function is a convenience wrapper for downloading foreign exchange rate data from Oanda. ### Method `getFX(Currencies, from = "1970-01-01", to = Sys.Date(), auto.assign = TRUE, ...)` ### Endpoint N/A (R function) ### Parameters #### Path Parameters None #### Query Parameters - **Currencies** (character or character vector) - The currency pair(s) to download (e.g., "USD/JPY"). - **from** (character or Date) - The start date for the data. - **to** (character or Date) - The end date for the data. - **auto.assign** (logical) - If TRUE, data is automatically assigned to the environment. Defaults to TRUE. ### Request Example ```r # Download USD/JPY exchange rate getFX("USD/JPY") # Download EUR/USD with date range getFX("EUR/USD", from = "2023-01-01") # Download multiple currency pairs getFX(c("USD/JPY", "EUR/USD", "GBP/USD")) # Return data directly without auto-assignment equiv_eur_usd <- getFX("EUR/USD", auto.assign = FALSE) ``` ### Response #### Success Response (200) Exchange rate data, typically returned as an 'xts' object named after the currency pair, or returned directly if `auto.assign = FALSE`. #### Response Example ```r # Example output structure for USDJPY # USD/JPY # 2023-01-01 130.50 # 2023-01-02 131.20 ``` ``` ```APIDOC ## getDividends and getSplits - Corporate Action Data ### Description These functions download dividend and stock split history from Yahoo Finance for a given symbol. ### Method `getDividends(Symbols, ...)` `getSplits(Symbols, ...)` ### Endpoint N/A (R function) ### Parameters #### Path Parameters None #### Query Parameters - **Symbols** (character or character vector) - The stock symbol(s) to get dividend or split history for. ### Request Example ```r # Load stock data first (if not already loaded) getSymbols("MSFT") # Get dividend history msft_div <- getDividends("MSFT") # Get split history msft_splits <- getSplits("MSFT") ``` ### Response #### Success Response (200) A data frame or 'xts' object containing the dividend or split history for the specified symbol(s). #### Response Example ```r # Example output structure for dividends # MSFT.div # 2003-02-19 0.08 # 2003-08-18 0.08 ``` ``` -------------------------------- ### Specify Trading Models with specifyModel Source: https://context7.com/joshuaulrich/quantmod/llms.txt Uses R formula syntax to define predictive trading models. It supports multi-asset inputs and integration with external economic data sources like FRED. ```R q.model <- specifyModel(Next(OpCl(QQQ)) ~ Lag(OpHi(QQQ), 0:3)) setSymbolLookup(CPIAUCNS = "FRED") q.model <- specifyModel(Next(Cl(SPY)) ~ Lag(Cl(SPY), 1:5) + CPIAUCNS) model_data <- modelData(q.model) ``` -------------------------------- ### Retrieve Financial Symbols with getSymbols Source: https://github.com/joshuaulrich/quantmod/blob/master/NEWS.md Demonstrates the usage of the getSymbols function to fetch financial data. Note that symbols with a '^' prefix are handled by removing the prefix from the resulting object name. ```R sym <- getSymbols("^IXIC") ``` -------------------------------- ### Retrieve Dividends and Splits with Quantmod Source: https://context7.com/joshuaulrich/quantmod/llms.txt Functions to fetch dividend history and stock split data for financial symbols, with options for split adjustments and automatic object updates. ```R getDividends("AAPL", from = "2020-01-01", to = "2023-12-31") getDividends("AAPL", split.adjust = TRUE) getDividends("AAPL", split.adjust = FALSE) msft_splits <- getSplits("MSFT") getDividends("MSFT", auto.update = TRUE) getSplits("MSFT", auto.update = TRUE) ``` -------------------------------- ### Manage Technical Indicators on Charts Source: https://context7.com/joshuaulrich/quantmod/llms.txt Demonstrates how to add, list, remove, swap, and move technical indicators on financial charts. It also shows how to set default indicators for all subsequent chartSeries calls. ```R getSymbols("AAPL") chartSeries(AAPL) addMACD() addRSI() addBBands() listTA() dropTA(2) swapTA(1, 2) moveTA(from = 3, to = 1) setTA(addVo(), addMACD(), addRSI()) chartSeries(AAPL) ``` -------------------------------- ### Generate Trading Signals with tradeModel Source: https://context7.com/joshuaulrich/quantmod/llms.txt Applies a previously fitted model to generate actionable trading signals based on model predictions. ```R signals <- tradeModel(q.model) head(signals) ``` -------------------------------- ### POST /specifyModel Source: https://context7.com/joshuaulrich/quantmod/llms.txt Defines a trading model specification using R formula syntax and data from various sources. ```APIDOC ## POST /specifyModel ### Description Creates a reusable model specification using R formula syntax, automatically handling data retrieval from multiple sources. ### Method POST ### Endpoint specifyModel(formula, data, ...) ### Parameters #### Request Body - **formula** (formula) - Required - R formula defining the relationship between target and predictors. - **data** (xts/zoo) - Optional - Data object containing the variables. ### Request Example { "formula": "Next(OpCl(QQQ)) ~ Lag(OpHi(QQQ), 0:3)" } ### Response #### Success Response (200) - **model** (quantmodModel) - A model specification object. #### Response Example { "model": "q.model" } ``` -------------------------------- ### Calculate Price Changes and Returns Source: https://context7.com/joshuaulrich/quantmod/llms.txt Functions to calculate intraday, overnight, and daily price changes between OHLC components, and percentage changes using Delt. ```R OpCl(AAPL) ClCl(AAPL) ClOp(AAPL) HiCl(AAPL) LoCl(AAPL) LoHi(AAPL) OpHi(AAPL) OpLo(AAPL) OpOp(AAPL) Delt(Stock.Open, k = 1:3) Delt(Stock.Open, type = "log") Delt(Cl(AAPL), k = 5) ``` -------------------------------- ### Download Exchange Rates with getFX in R Source: https://context7.com/joshuaulrich/quantmod/llms.txt The getFX function is a utility for downloading foreign exchange rate data, primarily from Oanda. It allows downloading rates for specific currency pairs, over specified date ranges, and supports multiple pairs simultaneously. ```r # Download USD/JPY exchange rate getFX("USD/JPY") head(USDJPY) # Download EUR/USD with date range getFX("EUR/USD", from = "2023-01-01") # Download multiple currency pairs getFX(c("USD/JPY", "EUR/USD", "GBP/USD")) # Return data directly without auto-assignment eur_usd <- getFX("EUR/USD", auto.assign = FALSE) ``` -------------------------------- ### Download Option Chain Data Source: https://context7.com/joshuaulrich/quantmod/llms.txt Retrieves call and put option data for a symbol. Supports filtering by expiration dates and using external backends like ORATS. ```R aapl_opts <- getOptionChain("AAPL") aapl_all_opts <- getOptionChain("AAPL", Exp = NULL) aapl_2024 <- getOptionChain("AAPL", Exp = "2024") aapl_range <- getOptionChain("AAPL", Exp = "2024-01/2024-06") opts <- getOptionChain(c("AAPL", "MSFT"), Exp = "2024", src = "orats", api.key = Sys.getenv("ORATS_API_KEY")) ``` -------------------------------- ### Quantmod Related Packages Source: https://github.com/joshuaulrich/quantmod/blob/master/README.md List of packages related to quantmod, including TTR and xts. ```APIDOC ## See Also - [TTR](https://CRAN.R-project.org/package=TTR): functions for technical trading rules - [xts](https://CRAN.R-project.org/package=xts): eXtensible Time Series based on [zoo](https://CRAN.R-project.org/package=zoo) ``` -------------------------------- ### Utilize Built-in Technical Indicators Source: https://context7.com/joshuaulrich/quantmod/llms.txt Quantmod provides a comprehensive set of functions for adding various pre-built technical indicators, often integrating with the TTR package. These include moving averages, trend indicators, momentum oscillators, volatility measures, and volume-based indicators. ```r getSymbols("AAPL") chartSeries(AAPL, subset = "last 6 months") addSMA(n = 20) addEMA(n = 20) addWMA(n = 20) addDEMA(n = 20) addZLEMA(n = 20) addEVWMA(n = 20) addMACD(fast = 12, slow = 26, signal = 9) addADX(n = 14) addAroon(n = 20) addAroonOsc(n = 20) addSAR() addTRIX(n = 20) addKST() addRSI(n = 14) addCCI(n = 20) addCMO(n = 14) addROC(n = 10) addMomentum(n = 10) addWPR(n = 14) addSMI() addBBands(n = 20, sd = 2) addATR(n = 14) addVolatility(calc = "close") addEnvelope(n = 20, p = 0.025) addVo() addOBV() addMFI(n = 14) addCMF(n = 20) addChAD() addEMV(n = 9) addExpiry() addZigZag() addLines(h = 100) addPoints(x, y) ``` -------------------------------- ### Lag and Next Functions for Time Series Data Source: https://context7.com/joshuaulrich/quantmod/llms.txt Demonstrates the use of Lag and Next functions to create lagged (past) and forward (future) shifted time series data. These are essential for creating features for predictive models. ```R Lag(Stock.Close, k = 1) # Same as default Lag(Stock.Close, k = 2) # 2-period lag Lag(Stock.Close, k = 1:3) # Multiple lags at once Next(Stock.Close) # 1-period forward Next(Stock.Close, k = 2) # 2-period forward getSymbols("AAPL") features <- cbind( Today = Cl(AAPL), Lag1 = Lag(Cl(AAPL), 1), Lag2 = Lag(Cl(AAPL), 2), Tomorrow = Next(Cl(AAPL), 1) ) head(features, 5) ``` -------------------------------- ### Configure Default Data Sources with setSymbolLookup in R Source: https://context7.com/joshuaulrich/quantmod/llms.txt The setSymbolLookup function allows users to define default data sources and parameters for specific financial symbols. This simplifies subsequent calls to getSymbols by pre-configuring source and other options, and the configuration can be viewed, saved, and loaded. ```r # Set default sources for specific symbols setSymbolLookup(AAPL = "yahoo", DIA = "MySQL", CPIAUCNS = "FRED") # Now getSymbols will use the configured sources automatically getSymbols(c("AAPL", "CPIAUCNS")) # Set with additional parameters setSymbolLookup(DJI = list(name = "^DJI", src = "yahoo")) setSymbolLookup(MYSTOCK = list(src = "MySQL", dbname = "stocks", password = "secret")) # View current symbol lookup configuration getSymbolLookup("AAPL") getSymbolLookup(c("AAPL", "DIA", "CPIAUCNS")) # Save and load symbol lookup tables for persistence saveSymbolLookup(file = "my_symbols.rda") loadSymbolLookup(file = "my_symbols.rda") # Clear a symbol's defaults setSymbolLookup(AAPL = NULL) ``` -------------------------------- ### Download Corporate Actions Data with getDividends and getSplits in R Source: https://context7.com/joshuaulrich/quantmod/llms.txt These functions, getDividends and getSplits, are used to retrieve historical dividend payments and stock split information, respectively, for a given stock symbol, typically from Yahoo Finance. ```r # Get dividend history getSymbols("MSFT") msft_div <- getDividends("MSFT") head(msft_div) # MSFT.div # 2003-02-19 0.08 # 2003-08-18 0.08 ``` -------------------------------- ### adjustOHLC: Adjust Stock Prices for Splits and Dividends Source: https://context7.com/joshuaulrich/quantmod/llms.txt Shows how to use the adjustOHLC function to correct historical OHLC (Open, High, Low, Close) stock prices for the effects of stock splits and dividend payouts. It allows adjustments for splits only, dividends only, or both, and can also use Yahoo's pre-adjusted data. ```R getSymbols("AAPL", from = "2014-01-01") # View unadjusted data head(AAPL) # Adjust for both splits and dividends (default) AAPL.adjusted <- adjustOHLC(AAPL) head(AAPL.adjusted) # Adjust for splits only AAPL.split.adj <- adjustOHLC(AAPL, adjust = "split") # Adjust for dividends only AAPL.div.adj <- adjustOHLC(AAPL, adjust = "dividend") # Use Yahoo's pre-adjusted column (less precise but faster) AAPL.yahoo.adj <- adjustOHLC(AAPL, use.Adjusted = TRUE) # Compare intraday returns (should be identical) head(cbind( Original = OpCl(AAPL), Adjusted = OpCl(AAPL.adjusted), YahooAdj = OpCl(AAPL.yahoo.adj) )) # Compare close-to-close returns (may differ slightly) head(cbind( Original = ClCl(AAPL), Adjusted = ClCl(AAPL.adjusted) )) ``` -------------------------------- ### Load Financial Data with getSymbols in R Source: https://context7.com/joshuaulrich/quantmod/llms.txt The getSymbols function is the primary tool for importing financial data into R from multiple sources like Yahoo Finance, FRED, Alpha Vantage, Tiingo, MySQL, and CSV files. It can automatically assign data to variables or return it directly, and supports specifying date ranges and environments. ```r library(quantmod) # Load stock data from Yahoo Finance (default source) getSymbols("AAPL") head(AAPL) # AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted # 2007-01-03 86.29 86.58 81.90 83.80 309579900 11.17 # Load multiple symbols at once getSymbols(c("AAPL", "MSFT", "GOOG")) # Load data and return directly (no auto-assignment) spy_data <- getSymbols("SPY", auto.assign = FALSE) # Load into a specific environment data_env <- new.env() getSymbols("AAPL", env = data_env) ls(data_env) # [1] "AAPL" # Load from FRED (Federal Reserve Economic Data) getSymbols("CPIAUCNS", src = "FRED") # Consumer Price Index # Load from Alpha Vantage (requires API key) getSymbols("AAPL", src = "av", api.key = "your_api_key") # Load from Tiingo (requires API key) getSymbols("AAPL", src = "tiingo", api.key = "your_api_key") # Load from CSV file getSymbols("MYDATA", src = "csv", dir = "/path/to/data/") # Specify date range getSymbols("AAPL", from = "2020-01-01", to = "2023-12-31") ``` -------------------------------- ### Download Real-Time Quotes with getQuote in R Source: https://context7.com/joshuaulrich/quantmod/llms.txt The getQuote function retrieves current stock quotes from sources like Yahoo Finance and Alpha Vantage. It supports fetching quotes for single or multiple symbols, requesting specific data fields, and using different quote formats. ```r # Get current quote for a single symbol getQuote("AAPL") # Trade Time Last Change % Change Open High Low Volume # AAPL 2024-01-15 185.92 1.23 0.67% 184.50 186.74 184.22 52M # Get quotes for multiple symbols (semicolon-separated) getQuote("AAPL;MSFT;GOOG") # Request specific fields getQuote("AAPL", what = yahooQF(c("Bid", "Ask", "Volume"))) # Use end-of-day quote format getQuote("AAPL", what = yahooQuote.EOD) # Get quote from Alpha Vantage getQuote("AAPL", src = "av", api.key = "your_api_key") # Interactive field selection (opens selection menu) yahooQF() # View standard quote fields standardQuote() ``` -------------------------------- ### Customize Chart Appearance with chartTheme Source: https://context7.com/joshuaulrich/quantmod/llms.txt The chartTheme function allows users to create and modify chart theme objects to control the visual styling of financial charts, including colors for price movements, backgrounds, and grid lines. It supports pre-built themes and extensive customization options. ```r str(chartTheme()) chartTheme("black") chartTheme("white") custom_theme <- chartTheme("white", up.col = "darkgreen", dn.col = "darkred", up.border = "darkgreen", dn.border = "darkred" ) chartSeries(AAPL, theme = custom_theme) chartSeries(AAPL, theme = chartTheme("white", up.col = "blue", dn.col = "red")) chartTheme(addRSI.col = "purple") my_theme <- chartTheme("black", fg.col = "white", bg.col = "#1a1a2e", grid.col = "#2d2d44", border = "#4a4a6a", up.col = "#00ff88", dn.col = "#ff4444", up.border = "#00ff88", dn.border = "#ff4444" ) getSymbols("AAPL") chartSeries(AAPL, theme = my_theme, subset = "last 3 months") ``` -------------------------------- ### Create Custom Technical Indicator with newTA Source: https://context7.com/joshuaulrich/quantmod/llms.txt Defines a custom technical indicator using the newTA function. It requires a processing function (FUN) and a pre-processing function (preFUN) to extract specific OHLC data columns. ```R newSpread <- newTA( FUN = function(x) x[, 1] - x[, 2], preFUN = function(x) cbind(Hi(x), Lo(x)), legend.name = "Hi-Lo Spread" ) newSpread() ``` -------------------------------- ### Extract OHLC Data Columns Source: https://context7.com/joshuaulrich/quantmod/llms.txt Helper functions to extract specific price components (Open, High, Low, Close, Volume, Adjusted) from OHLC time series objects. ```R getSymbols("AAPL") Op(AAPL) Hi(AAPL) Lo(AAPL) Cl(AAPL) Vo(AAPL) Ad(AAPL) HL(AAPL) HLC(AAPL) OHLC(AAPL) OHLCV(AAPL) seriesHi(AAPL) seriesLo(AAPL) getPrice(AAPL, prefer = "close") ``` -------------------------------- ### Add Custom Technical Indicators with addTA Source: https://context7.com/joshuaulrich/quantmod/llms.txt The addTA function is used to overlay custom data series or technical indicators onto existing financial charts. Indicators can be plotted on the main price panel or in separate sub-panels, with options for customizing appearance and line styles. ```r getSymbols("SBUX") barChart(SBUX) addTA(EMA(Cl(SBUX), n = 20), on = 1, col = "blue") addTA(EMA(Cl(SBUX), n = 50), on = 1, col = "red") addTA(OpCl(SBUX), col = "purple", type = "h") addTA(EMA(Cl(SBUX), n = 10), on = 1, col = "green", lwd = 2, lty = 2) bullish <- Cl(SBUX) > Op(SBUX) addTA(bullish, on = 1, col = "lightgreen") ``` -------------------------------- ### Create Custom TA Functions with newTA Source: https://context7.com/joshuaulrich/quantmod/llms.txt The newTA function simplifies the creation of reusable custom technical analysis indicator functions that adhere to the addTA convention. It allows users to define custom indicators based on existing functions, specifying how they should be plotted on charts. ```r getSymbols("SBUX") barChart(SBUX) newEMA <- newTA(FUN = EMA, preFUN = Cl, on = 1, col = 7) newEMA() newEMA(n = 10, col = 5) newEMA(on = NA, col = 3) newRSI <- newTA(FUN = RSI, preFUN = Cl, yrange = c(0, 100)) newRSI() ``` -------------------------------- ### Shift Time Series with Lag and Next Source: https://context7.com/joshuaulrich/quantmod/llms.txt Shifts time series data forward or backward by a specified number of periods, essential for creating predictive features. ```R Lag(Stock.Close) Next(Stock.Close) ``` -------------------------------- ### Change Chart Zoom Level with zoomChart Source: https://context7.com/joshuaulrich/quantmod/llms.txt The zoomChart function enables dynamic adjustment of the date range displayed on a financial chart without requiring a full redraw. It supports zooming to specific dates, ranges, or resetting to the full data view. An interactive zooming function, zooom(), is also available. ```r getSymbols("AAPL") chartSeries(AAPL) zoomChart("2023-06::") zoomChart("2023-01::2023-06") zoomChart("2023") zoomChart("::2023-03") zoomChart() zooom() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.