## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

## ----setup--------------------------------------------------------------------
library(grangersearch)

## ----basic-usage--------------------------------------------------------------
# Generate example time series
set.seed(123)
n <- 100

# X is a random walk
x <- cumsum(rnorm(n))

# Y depends on lagged X (so X should Granger-cause Y)
y <- c(0, x[1:(n-1)]) + rnorm(n, sd = 0.5)

# Perform the test
result <- granger_causality_test(x = x, y = y)
print(result)

## ----summary------------------------------------------------------------------
summary(result)

## ----tidyverse-df-------------------------------------------------------------
library(tibble)

# Create a tibble with time series
df <- tibble(
  price = cumsum(rnorm(100)),
  volume = c(0, cumsum(rnorm(99)))
)

# Use column names directly
result <- granger_causality_test(df, price, volume)
print(result)

## ----pipes--------------------------------------------------------------------
# With base R pipe
df |>
  granger_causality_test(price, volume)

## ----tidy---------------------------------------------------------------------
result <- granger_causality_test(x = x, y = y)
tidy(result)

## ----glance-------------------------------------------------------------------
glance(result)

## ----lag----------------------------------------------------------------------
# Using lag = 2
result_lag2 <- granger_causality_test(x = x, y = y, lag = 2)
print(result_lag2)

## ----alpha--------------------------------------------------------------------
# More conservative test with alpha = 0.01
result_strict <- granger_causality_test(x = x, y = y, alpha = 0.01)
print(result_strict)

## ----components---------------------------------------------------------------
result <- granger_causality_test(x = x, y = y)

# Logical indicators
result$x_causes_y
result$y_causes_x

# P-values
result$p_value_xy
result$p_value_yx

# Test statistics
result$test_statistic_xy

## ----finance-example----------------------------------------------------------
set.seed(42)
n <- 250  # About one year of trading days

# Simulate stock returns
stock_returns <- rnorm(n, mean = 0.0005, sd = 0.02)

# Trading volume often leads price movements
# Volume is partially predictive of next-day returns
volume <- abs(rnorm(n, mean = 1000, sd = 200))
volume_effect <- c(0, 0.001 * scale(volume[1:(n-1)]))
price_with_volume <- stock_returns + volume_effect

df <- tibble(
  returns = price_with_volume,
  volume = volume
)

# Test if volume Granger-causes returns
result <- df |> granger_causality_test(volume, returns)
print(result)

