### Log Returns Calculation (makeReturns) Source: https://context7.com/cran/highfrequency/llms.txt Computes log returns from price data. ```APIDOC ## makeReturns ### Description Computes log returns from price data. ### Method `makeReturns` ### Parameters #### Function Arguments - `price` (numeric or xts) - A numeric vector or xts object of prices. - `alignBy` (character, optional) - The time unit for alignment (e.g., "minutes", "hours"). Used when input is xts. - `alignPeriod` (numeric, optional) - The period for alignment (e.g., 1 for 1-minute intervals). Used when input is xts. ### Request Example ```R library(highfrequency) # Calculate returns from price series prices <- sampleTData[as.Date(DT) == "2018-01-02", PRICE] returns <- makeReturns(prices) head(returns) # Works with xts objects library(xts) priceXts <- as.xts(sampleTData[, list(DT, PRICE)]) returnXts <- makeReturns(priceXts) head(returnXts) ``` ### Response Returns a numeric vector or xts object of log returns. ``` -------------------------------- ### Spot Volatility Estimation (spotVol) Source: https://context7.com/cran/highfrequency/llms.txt Estimates intraday spot volatility using various methods. ```APIDOC ## spotVol ### Description Estimates intraday spot volatility using various methods including deterministic periodicity, stochastic periodicity, kernel smoothing, and piecewise constant approaches. ### Method `spotVol` ### Parameters #### Function Arguments - `data` (xts or data.frame) - High-frequency price data, typically with columns for timestamp and price. - `method` (character, optional) - The method for spot volatility estimation. Options include "detPer" (deterministic periodicity, default), "RM" (realized measures), "kernel", "piecewise". - `alignBy` (character, optional) - Time unit for alignment (e.g., "minutes"). - `alignPeriod` (numeric, optional) - Period for alignment (e.g., 5 for 5-minute intervals). - `marketOpen` (character, optional) - The market opening time (e.g., "09:30:00"). - `marketClose` (character, optional) - The market closing time (e.g., "16:00:00"). - `tz` (character, optional) - Timezone for the data. - `RM` (character, optional) - Realized measure to use when `method = "RM"`. Options include "rBPCov", "rCov". - `lookBackPeriod` (numeric, optional) - The look-back period for rolling window calculations when `method = "RM"`. - `type` (character, optional) - Kernel type for "kernel" method (e.g., "gaussian", "epanechnikov"). - `est` (character, optional) - Estimation method for bandwidth when `method = "kernel"` (e.g., "cv" for cross-validation). ### Request Example ```R library(highfrequency) # Method 1: Deterministic Periodicity (default) spotVolDetPer <- spotVol( data = sampleOneMinuteData[, list(DT, PRICE = MARKET)], method = "detPer", alignBy = "minutes", alignPeriod = 5, marketOpen = "09:30:00", marketClose = "16:00:00" ) # Method 2: Realized Measures based spot volatility spotVolRM <- spotVol( data = sampleTDataEurope[, list(DT, PRICE)], method = "RM", RM = "rBPCov", lookBackPeriod = 10, alignBy = "minutes", alignPeriod = 1, marketOpen = "09:00:00", marketClose = "17:30:00", tz = "UTC" ) # Method 3: Kernel-based nonparametric estimation spotVolKernel <- spotVol( data = sampleOneMinuteData[, list(DT, PRICE = MARKET)], method = "kernel", type = "gaussian", est = "cv" ) ``` ### Response Returns a list containing spot volatility estimates and potentially daily and periodic components, depending on the method used. ``` -------------------------------- ### Calculate Log Returns Source: https://context7.com/cran/highfrequency/llms.txt Computes log returns from price data, supporting both raw vectors and xts objects. ```r library(highfrequency) # Calculate returns from price series prices <- sampleTData[as.Date(DT) == "2018-01-02", PRICE] returns <- makeReturns(prices) head(returns) # [1] 0.000000000 0.000096339 -0.000048168 0.000144502 ... # Works with xts objects library(xts) priceXts <- as.xts(sampleTData[, list(DT, PRICE)]) returnXts <- makeReturns(priceXts) head(returnXts) ``` -------------------------------- ### Compute Liquidity Measures Source: https://context7.com/cran/highfrequency/llms.txt Calculates various liquidity metrics from matched trade and quote data. Requires pre-matching data using matchTradesQuotes. ```r library(highfrequency) # First match trades and quotes tqData <- matchTradesQuotes( sampleTData[as.Date(DT) == "2018-01-02"], sampleQData[as.Date(DT) == "2018-01-02"] ) # Calculate liquidity measures liqMeasures <- getLiquidityMeasures( tqData = tqData, win = 300 # 5-minute window for realized spread ) # View available measures names(liqMeasures) # [1] "DT" "SYMBOL" "PRICE" "SIZE" "BID" "OFR" "BIDSIZ" "OFRSIZ" # [9] "effectiveSpread" "realizedSpread" "valueTrade" "signedValueTrade" # [13] "depthImbalanceDifference" "depthImbalanceRatio" "proportionalEffectiveSpread" # [17] "proportionalRealizedSpread" "priceImpact" "proportionalPriceImpact" # [21] "halfTradedSpread" "proportionalHalfTradedSpread" "squaredLogReturn" # [25] "absLogReturn" "quotedSpread" "proportionalQuotedSpread" "logQuotedSpread" # [29] "logQuotedSize" "quotedSlope" "logQSlope" "midQuoteSquaredReturn" # [33] "midQuoteAbsReturn" "signedTradeSize" # Summary statistics for effective spread summary(liqMeasures$effectiveSpread) # Min. 1st Qu. Median Mean 3rd Qu. Max. # -0.0200 0.0050 0.0100 0.0123 0.0150 0.0800 # Calculate daily averages dailyLiq <- liqMeasures[, .( avgEffSpread = mean(effectiveSpread, na.rm = TRUE), avgQuotedSpread = mean(quotedSpread, na.rm = TRUE), avgPriceImpact = mean(priceImpact, na.rm = TRUE), totalVolume = sum(valueTrade, na.rm = TRUE) )] dailyLiq ``` -------------------------------- ### Estimate Piecewise Constant Volatility Source: https://context7.com/cran/highfrequency/llms.txt Estimates piecewise constant volatility using a reference and test window. Set online to TRUE for online estimation. ```r spotVolPiecewise <- spotVol( data = sampleOneMinuteData[, list(DT, PRICE = MARKET)], method = "piecewise", m = 200, # Reference window n = 100, # Test window alpha = 0.005, # Significance level online = FALSE ) # View detected change points spotVolPiecewise$cp ``` -------------------------------- ### Perform Intraday Jump Detection (Lee-Mykland) Source: https://context7.com/cran/highfrequency/llms.txt Conducts intraday jump detection using Lee-Mykland style tests. Specify volatility and drift estimators, alignment parameters, and market open/close times. The 'RM' argument specifies the jump-robust volatility estimator. ```r library(highfrequency) # Lee-Mykland style jump test LMtest <- intradayJumpTest( pData = sampleTData[, list(DT, PRICE)], volEstimator = "RM", # Realized measures for volatility driftEstimator = "none", # No drift estimation alpha = 0.95, alignBy = "minutes", alignPeriod = 5, marketOpen = "09:30:00", marketClose = "16:00:00", RM = "rBPCov", # Jump-robust volatility estimator lookBackPeriod = 20 ) # Plot detected jumps plot(LMtest) ``` ```r # Pre-averaged version (robust to microstructure noise) FoFtest <- intradayJumpTest( pData = sampleTData[, list(DT, PRICE)], volEstimator = "PARM", # Pre-Averaged Realized Measures driftEstimator = "none", RM = "rBPCov", lookBackPeriod = 20, theta = 1.2, # Pre-averaging parameter marketOpen = "09:30:00", marketClose = "16:00:00" ) plot(FoFtest) ``` -------------------------------- ### Analyze Lead-Lag Relationships Source: https://context7.com/cran/highfrequency/llms.txt Identifies price discovery leadership between two assets. Supports different time resolutions such as seconds or milliseconds. ```r library(highfrequency) # Spread prices for multiple assets spread <- spreadPrices(sampleMultiTradeData[SYMBOL %in% c("ETF", "AAA")]) # Estimate lead-lag relationship llResult <- leadLag( price1 = spread[!is.na(AAA), list(DT, PRICE = AAA)], price2 = spread[!is.na(ETF), list(DT, PRICE = ETF)], lags = seq(-15, 15), # Test lags from -15 to +15 seconds resolution = "seconds", normalize = TRUE ) # View results llResult$`lead-lag-ratio` # [1] 0.85 # LLR < 1 suggests price1 (AAA) may lead price2 (ETF) # Plot contrast function plot(llResult) # The contrast values at each lag head(llResult$contrasts) # lag contrast # 1 -15 0.000234 # 2 -14 0.000256 # ... # With millisecond resolution llResultMs <- leadLag( price1 = spread[!is.na(AAA), list(DT, PRICE = AAA)], price2 = spread[!is.na(ETF), list(DT, PRICE = ETF)], lags = seq(-100, 100), resolution = "milliseconds" ) ``` -------------------------------- ### Estimate Microstructure Noise with ReMeDI Source: https://context7.com/cran/highfrequency/llms.txt Estimates the autocovariance of market microstructure noise. Includes automatic tuning parameter selection via knChooseReMeDI. ```r library(highfrequency) # Estimate microstructure noise autocovariance dat <- sampleTData[as.Date(DT) == "2018-01-02"] remed <- ReMeDI( pData = dat, kn = 2, # Tuning parameter lags = 1:8 # Estimate covariance at lags 1-8 ) remed # lag covariance # 1 1 2.345e-08 # 2 2 1.234e-08 # 3 3 5.678e-09 # ... # Find optimal kn using automatic selection optimalKn <- knChooseReMeDI( pData = dat, knMax = 10, tol = 0.05, size = 3, lower = 2, upper = 5, plot = TRUE ) optimalKn # [1] 4 # Re-estimate with optimal kn remedOptimal <- ReMeDI(dat, kn = optimalKn, lags = 1:8) ``` -------------------------------- ### Match Trades and Quotes Source: https://context7.com/cran/highfrequency/llms.txt Matches trade and quote data, aligning each trade with the prevailing bid-ask quote. Supports Backwards-Forwards Matching (BFM) algorithm for handling late-reported trades. Use this to link trade execution data with the corresponding quote information. ```r library(highfrequency) # Match trades with quotes for a single day tqData <- matchTradesQuotes( tData = sampleTData[as.Date(DT) == "2018-01-02"], qData = sampleQData[as.Date(DT) == "2018-01-02"], lagQuotes = 0, # Quote lag in seconds BFM = FALSE # Backwards-Forwards Matching ) # View matched data head(tqData) # DT SYMBOL PRICE SIZE BID OFR BIDSIZ OFRSIZ # 1: 2018-01-02 09:30:01.382 XXX 103.75 200 103.74 103.76 1500 2200 # 2: 2018-01-02 09:30:02.156 XXX 103.76 100 103.75 103.77 1200 1800 # Multi-day matching is also supported tqDataMulti <- matchTradesQuotes(sampleTData, sampleQData) ``` -------------------------------- ### Test for Drift Bursts Source: https://context7.com/cran/highfrequency/llms.txt Tests for drift bursts, which are gradual price movements that can precede extreme events. Requires specifying test times, pre-averaging window, and bandwidths for mean and variance. ```r library(highfrequency) # Select single day of data dat <- sampleTData[as.Date(DT) == "2018-01-02"] # Run drift burst test # Testing every 60 seconds from 09:45:00 (35100 sec) to 16:00:00 (57600 sec) DBH <- driftBursts( pData = dat, testTimes = seq(35100, 57600, 60), preAverage = 2, # Pre-averaging window ACLag = -1L, # Automatic lag selection meanBandwidth = 300L, # 5-minute bandwidth for mean varianceBandwidth = 900L # 15-minute bandwidth for variance ) # Print test results print(DBH) ``` ```r # Print with custom significance level print(DBH, alpha = 0.99) ``` ```r # Plot test statistics with price data plot(DBH, pData = dat) ``` ```r # Get critical values for different confidence levels critVals <- getCriticalValues(DBH, alpha = 0.95) critVals$quantile ``` -------------------------------- ### Estimate HEAVY Volatility Model Source: https://context7.com/cran/highfrequency/llms.txt Models returns and realized measures jointly to estimate conditional volatility. Requires data formatted as an xts object containing returns and realized measures. ```r library(highfrequency) library(xts) # Prepare data: returns (in %) and realized measures logReturns <- 100 * makeReturns(SPYRM$CLOSE)[-1] dataSPY <- xts( cbind(logReturns, SPYRM$BPV5[-1] * 10000), order.by = SPYRM$DT[-1] ) colnames(dataSPY) <- c("returns", "RM") # Fit HEAVY model heavyFit <- HEAVYmodel(dataSPY) # View estimated coefficients and standard errors heavyFit # HEAVY Model Estimation # # Variance Equation (returns): # omega alpha beta # 0.00234 0.15234 0.82345 # # Realized Measure Equation: # omega_R alpha_R beta_R # 0.00123 0.12456 0.85234 # Summary with robust standard errors summary(heavyFit) # Multi-step ahead forecasts forecasts <- predict(heavyFit, stepsAhead = 12) forecasts # Step varForecast RMForecast # 1 1 0.0001234 0.0001456 # 2 2 0.0001198 0.0001423 # ... # Plot conditional variances plot(heavyFit) ``` -------------------------------- ### Estimate Spot Volatility Source: https://context7.com/cran/highfrequency/llms.txt Estimates intraday spot volatility using methods like deterministic periodicity, realized measures, or kernel smoothing. ```r library(highfrequency) # Method 1: Deterministic Periodicity (default) # Decomposes volatility into daily and periodic intraday components spotVolDetPer <- spotVol( data = sampleOneMinuteData[, list(DT, PRICE = MARKET)], method = "detPer", alignBy = "minutes", alignPeriod = 5, marketOpen = "09:30:00", marketClose = "16:00:00" ) # View spot volatility estimates head(spotVolDetPer$spot) # Access daily and periodic components spotVolDetPer$daily # Daily volatility levels spotVolDetPer$periodic # Intraday periodicity pattern # Method 2: Realized Measures based spot volatility spotVolRM <- spotVol( data = sampleTDataEurope[, list(DT, PRICE)], method = "RM", RM = "rBPCov", # Use bipower variation (jump-robust) lookBackPeriod = 10, # Rolling window of 10 observations alignBy = "minutes", alignPeriod = 1, marketOpen = "09:00:00", marketClose = "17:30:00", tz = "UTC" ) # Plot spot volatility plot(spotVolRM) # Method 3: Kernel-based nonparametric estimation spotVolKernel <- spotVol( data = sampleOneMinuteData[, list(DT, PRICE = MARKET)], method = "kernel", type = "gaussian", # Gaussian kernel est = "cv" # Cross-validation for bandwidth ) ``` -------------------------------- ### Estimate HAR Model for Volatility Forecasting Source: https://context7.com/cran/highfrequency/llms.txt Estimates Heterogeneous Autoregressive (HAR) models for realized volatility forecasting. Supports HAR, HARJ, HARQ, and CHARQ variants. Specify aggregation periods and RV estimators. Use 'inputType = "RM"' if input is realized measures. ```r library(highfrequency) library(xts) # Prepare realized volatility series RVSPY <- as.xts(SPYRM$RV5, order.by = SPYRM$DT) # Basic HAR model harFit <- HARmodel( data = RVSPY, periods = c(1, 5, 22), # Daily, weekly, monthly aggregation RVest = c("rCov"), type = "HAR", h = 1, # 1-day ahead forecast inputType = "RM" # Input is realized measures ) # Model summary with Newey-West standard errors summary(harFit) ``` ```r # Forecast predict(harFit) ``` ```r # Plot fitted values vs actual plot(harFit) ``` ```r # HARQ model (includes realized quarticity) dat <- SPYRM[, list(DT, RV5, BPV5, RQ5)] harqFit <- HARmodel( data = as.xts(dat), periods = c(1, 5, 22), periodsQ = c(1), type = "HARQ" ) ``` ```r # HARCJ model (continuous and jump components) harcjFit <- HARmodel( data = as.xts(SPYRM[, list(DT, RV5, BPV5)]), periods = c(1, 5, 22), periodsJ = c(1, 5, 22), type = "HARCJ", alpha = 0.05 # Jump significance level ) predict(harcjFit) ``` -------------------------------- ### Calculate Realized Bipower Covariance Source: https://context7.com/cran/highfrequency/llms.txt Computes jump-robust realized bipower variance or covariance. Can return correlation matrices by setting cor = TRUE. ```r library(highfrequency) # Univariate: Realized Bipower Variance rbpv <- rBPCov( rData = sampleTData[, list(DT, PRICE)], alignBy = "minutes", alignPeriod = 5, makeReturns = TRUE ) rbpv # [1] 0.0001234 # Multivariate: Realized Bipower Covariance matrix rbpc <- rBPCov( rData = sampleOneMinuteData, makeReturns = TRUE, makePsd = TRUE # Ensure positive semi-definiteness ) # View covariance matrix for first day rbpc[[1]] # MARKET STOCK # MARKET 0.00008421 0.00006234 # STOCK 0.00006234 0.00015234 # Get correlation instead of covariance rbpCorr <- rBPCov(sampleOneMinuteData, makeReturns = TRUE, cor = TRUE) ``` -------------------------------- ### Realized Variance Estimators Source: https://context7.com/cran/highfrequency/llms.txt Functions to calculate realized variance and covariance from high-frequency data. ```APIDOC ## Realized Variance Estimators ### rRVar #### Description Calculates realized variance, the sum of squared intraday returns. #### Method `rRVar` #### Parameters - `rData` (xts or data.frame) - High-frequency return data. If it's price data, `makeReturns` will be applied internally. - `makeReturns` (logical, optional) - If TRUE, `rData` is treated as prices and converted to returns using `makeReturns`. - `alignBy` (character, optional) - Time unit for alignment (e.g., "minutes"). - `alignPeriod` (numeric, optional) - Period for alignment (e.g., 5 for 5-minute intervals). #### Request Example ```R library(highfrequency) # Realized variance from 1-minute price data rv <- rRVar( rData = sampleOneMinuteData, makeReturns = TRUE ) # With custom sampling frequency (5-minute returns) rv5min <- rRVar(sampleTData[, list(DT, PRICE)], alignBy = "minutes", alignPeriod = 5, makeReturns = TRUE) ``` #### Response Returns an xts object containing daily realized variance values. ### rBPCov #### Description Calculates realized bipower covariance, a jump-robust estimator of integrated variance/covariance. #### Method `rBPCov` #### Parameters - `rData` (xts or data.frame) - High-frequency return data. If it's price data, `makeReturns` will be applied internally. - `alignBy` (character, optional) - Time unit for alignment (e.g., "minutes"). - `alignPeriod` (numeric, optional) - Period for alignment (e.g., 5 for 5-minute intervals). - `makeReturns` (logical, optional) - If TRUE, `rData` is treated as prices and converted to returns using `makeReturns`. - `makePsd` (logical, optional) - If TRUE, ensures the resulting covariance matrix is positive semi-definite. - `cor` (logical, optional) - If TRUE, returns a correlation matrix instead of a covariance matrix. #### Request Example ```R library(highfrequency) # Univariate: Realized Bipower Variance rbpv <- rBPCov( rData = sampleTData[, list(DT, PRICE)], alignBy = "minutes", alignPeriod = 5, makeReturns = TRUE ) # Multivariate: Realized Bipower Covariance matrix rbpc <- rBPCov( rData = sampleOneMinuteData, makeReturns = TRUE, makePsd = TRUE ) # Get correlation instead of covariance rbpCorr <- rBPCov(sampleOneMinuteData, makeReturns = TRUE, cor = TRUE) ``` #### Response Returns a numeric value (for univariate) or a list of matrices (for multivariate) representing realized bipower variance/covariance. ### rCov #### Description Calculates realized covariance matrix from high-frequency returns. #### Method `rCov` #### Parameters - `rData` (xts or data.frame) - High-frequency return data. If it's price data, `makeReturns` will be applied internally. - `alignBy` (character, optional) - Time unit for alignment (e.g., "minutes"). - `alignPeriod` (numeric, optional) - Period for alignment (e.g., 5 for 5-minute intervals). - `makeReturns` (logical, optional) - If TRUE, `rData` is treated as prices and converted to returns using `makeReturns`. - `cor` (logical, optional) - If TRUE, returns a correlation matrix instead of a covariance matrix. #### Request Example ```R library(highfrequency) # Univariate realized variance rv <- rCov( rData = sampleTData[, list(DT, PRICE)], alignBy = "minutes", alignPeriod = 5, makeReturns = TRUE ) # Multivariate realized covariance rc <- rCov( rData = sampleOneMinuteData, makeReturns = TRUE ) # Get correlation matrix rcCorr <- rCov(sampleOneMinuteData, makeReturns = TRUE, cor = TRUE) ``` #### Response Returns a numeric value (for univariate) or a list of matrices (for multivariate) representing realized variance/covariance. ``` -------------------------------- ### Clean Raw Quote Data Source: https://context7.com/cran/highfrequency/llms.txt Cleans raw quote data by removing zero quotes, filtering to exchange hours, removing negative and large spreads, merging same-timestamp quotes, and removing outliers. Essential for preparing quote data for liquidity analysis. Supports median-based merging for same-timestamp quotes and outlier detection using a specified window. ```r library(highfrequency) # Load raw quote data head(sampleQDataRaw) dim(sampleQDataRaw) # Clean quote data with NYSE exchange qDataCleaned <- quotesCleanup( qDataRaw = sampleQDataRaw, exchanges = "N", # NYSE report = TRUE, selection = "median", maxi = 50, # Max spread = 50x median spread window = 50, # Window for outlier detection marketOpen = "09:30:00", marketClose = "16:00:00" ) # View cleaning report qDataCleaned$report # nObs # initial 52876 # noZeroQuotes 52876 # exchangeHoursOnly 48234 # selectExchange 38456 # rmNegativeSpread 38432 # rmLargeSpread 38012 # mergeTimestamp 25634 # rmOutliersQuotes 25589 # Access cleaned quotes head(qDataCleaned$qData) ``` -------------------------------- ### Clean Raw Trade Data Source: https://context7.com/cran/highfrequency/llms.txt Cleans raw trade data by removing zero prices, selecting exchanges, filtering invalid conditions, and merging trades with identical timestamps. Use this as the first step in a high-frequency data analysis pipeline. Automatic exchange selection and median-based merging for same-timestamp trades are supported. ```r library(highfrequency) # Load raw trade data head(sampleTDataRaw) dim(sampleTDataRaw) # Clean the trade data with automatic exchange selection tDataCleaned <- tradesCleanup( tDataRaw = sampleTDataRaw, exchanges = "auto", # Automatic exchange selection report = TRUE, # Return cleaning report selection = "median", # Merge same-timestamp trades using median marketOpen = "09:30:00", marketClose = "16:00:00" ) # View the cleaning report showing trades removed at each step tDataCleaned$report # nObs # initial 15324 # noZeroPrices 15324 # selectExchange 12543 # tradesCondition 11897 # mergeTimestamp 8562 # Access cleaned data dim(tDataCleaned$tData) head(tDataCleaned$tData) ``` -------------------------------- ### Aggregate Trade Data Source: https://context7.com/cran/highfrequency/llms.txt Aggregates tick-by-tick trade data to regular time intervals using previous tick aggregation for prices and sum aggregation for volume. Useful for creating time-series data at fixed frequencies like minutes or seconds. ```r library(highfrequency) # Aggregate trades to 5-minute frequency tDataAgg5min <- aggregateTrades( tData = sampleTData, alignBy = "minutes", alignPeriod = 5, marketOpen = "09:30:00", marketClose = "16:00:00" ) head(tDataAgg5min) # DT SYMBOL PRICE SIZE VWPRICE # 1: 2018-01-02 09:35:00 XXX 103.82 45200 103.79 # 2: 2018-01-02 09:40:00 XXX 103.95 32100 103.88 # Aggregate to 1-minute frequency tDataAgg1min <- aggregateTrades(sampleTData, alignBy = "minutes", alignPeriod = 1) # Aggregate to 30-second frequency tDataAgg30sec <- aggregateTrades(sampleTData, alignBy = "seconds", alignPeriod = 30) ``` -------------------------------- ### Time Series Aggregation (aggregateTS) Source: https://context7.com/cran/highfrequency/llms.txt General-purpose time series aggregation function supporting various aggregation methods including previous tick, mean, and weighted average. ```APIDOC ## aggregateTS ### Description General-purpose time series aggregation function supporting various aggregation methods including previous tick, mean, and weighted average. ### Method `aggregateTS` ### Parameters #### Function Arguments - `ts` (xts) - The time series object to aggregate. - `FUN` (character, optional) - The aggregation function to use. Options include "previoustick", "mean", "weighted.mean", etc. Defaults to "mean" if not specified. - `alignBy` (character, optional) - The time unit for alignment (e.g., "minutes", "hours", "days"). - `alignPeriod` (numeric, optional) - The period for alignment (e.g., 5 for 5-minute intervals). - `weights` (xts, optional) - A time series of weights to be used with "weighted.mean" aggregation. ### Request Example ```R library(highfrequency) library(xts) # Convert to xts for aggregation ts <- as.xts(sampleTData[, list(DT, PRICE, SIZE)]) # Previous tick aggregation to 5-minute frequency tsAgg5min <- aggregateTS(ts, FUN = "previoustick", alignBy = "minutes", alignPeriod = 5) head(tsAgg5min) # Mean aggregation to 1-minute frequency tsAggMean <- aggregateTS(ts, FUN = "mean", alignBy = "minutes", alignPeriod = 1) # Tick-based aggregation (every 100 ticks) tsAggTicks <- aggregateTS(ts, alignBy = "ticks", alignPeriod = 100) # Weighted average aggregation using volume weights weights <- xts(sampleTData$SIZE, order.by = sampleTData$DT) tsAggWeighted <- aggregateTS(ts[, "PRICE"], weights = weights, alignBy = "minutes", alignPeriod = 5) ``` ### Response Returns an xts object with aggregated time series data. ``` -------------------------------- ### Perform BNS Jump Test Source: https://context7.com/cran/highfrequency/llms.txt Applies the Barndorff-Nielsen and Shephard test for jumps in asset prices. Requires specifying jump-robust variance and quarticity estimators. The 'type' argument can be 'linear' or 'quadratic'. ```r library(highfrequency) # Basic BNS jump test bnsTest <- BNSjumpTest( rData = sampleTData[, list(DT, PRICE)], IVestimator = "rMinRVar", # Jump-robust variance estimator IQestimator = "rMedRQuar", # Jump-robust quarticity estimator type = "linear", makeReturns = TRUE, alpha = 0.975 ) bnsTest ``` ```r # Test with 5-minute sampling bnsTest5min <- BNSjumpTest( rData = sampleTData[, list(DT, PRICE)], alignBy = "minutes", alignPeriod = 5, IVestimator = "rBPCov", IQestimator = "rTPQuar", makeReturns = TRUE ) ``` ```r # Multi-day testing returns xts object bnsMulti <- BNSjumpTest(sampleOneMinuteData[, list(DT, MARKET)], makeReturns = TRUE) ``` -------------------------------- ### Calculate Realized Covariance Source: https://context7.com/cran/highfrequency/llms.txt Computes realized covariance matrices from high-frequency returns, supporting both univariate and multivariate data. ```r library(highfrequency) # Univariate realized variance rv <- rCov( rData = sampleTData[, list(DT, PRICE)], alignBy = "minutes", alignPeriod = 5, makeReturns = TRUE ) rv # Multivariate realized covariance rc <- rCov( rData = sampleOneMinuteData, makeReturns = TRUE ) # First day's covariance matrix rc[[1]] # MARKET STOCK # MARKET 0.00008956 0.00006789 # STOCK 0.00006789 0.00016234 # Get correlation matrix rcCorr <- rCov(sampleOneMinuteData, makeReturns = TRUE, cor = TRUE) ``` -------------------------------- ### Aggregate Time Series Data Source: https://context7.com/cran/highfrequency/llms.txt Aggregates high-frequency data using various methods like previous tick, mean, or weighted averages. Requires input as an xts object. ```r library(highfrequency) library(xts) # Convert to xts for aggregation ts <- as.xts(sampleTData[, list(DT, PRICE, SIZE)]) # Previous tick aggregation to 5-minute frequency tsAgg5min <- aggregateTS(ts, FUN = "previoustick", alignBy = "minutes", alignPeriod = 5) head(tsAgg5min) # Mean aggregation to 1-minute frequency tsAggMean <- aggregateTS(ts, FUN = "mean", alignBy = "minutes", alignPeriod = 1) # Tick-based aggregation (every 100 ticks) tsAggTicks <- aggregateTS(ts, alignBy = "ticks", alignPeriod = 100) # Weighted average aggregation using volume weights weights <- xts(sampleTData$SIZE, order.by = sampleTData$DT) tsAggWeighted <- aggregateTS(ts[, "PRICE"], weights = weights, alignBy = "minutes", alignPeriod = 5) ``` -------------------------------- ### Estimate Realized Variance Source: https://context7.com/cran/highfrequency/llms.txt Calculates realized variance as the sum of squared intraday returns. Supports custom sampling frequencies. ```r library(highfrequency) # Realized variance from 1-minute price data rv <- rRVar( rData = sampleOneMinuteData, makeReturns = TRUE ) # View results (one value per day) head(rv) # DT MARKET STOCK # 1: 2019-01-02 0.0000842 0.0001523 # 2: 2019-01-03 0.0001256 0.0002134 # Plot realized variance time series plot(rv[, DT], rv[, MARKET], type = "l", xlab = "Date", ylab = "Realized Variance", main = "Daily Realized Variance") # With custom sampling frequency (5-minute returns) rv5min <- rRVar(sampleTData[, list(DT, PRICE)], alignBy = "minutes", alignPeriod = 5, makeReturns = TRUE) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.