tests/testthat/test-impermanent_loss.R

library(impermanentlosscalc)
library(testthat)

# Note: Plot function is set to FALSE in tests as the plotting
# functionality shouldn't affect the core math.

# --- Test Case 1: Simple 50/50 Pool (2x price change) ---
# Inputs: Price ratio (r) for Asset A = 2; Asset B = 1. Weights = 0.5, 0.5.
# Expected Geometric Mean Factor: 1.4142136
# Expected Arithmetic Mean Factor: 1.5
test_that("IL is calculated correctly for a 50/50 pool with one asset doubling", {
  
  result <- impermanent_loss(
    prices_old = c(1, 1),
    prices_new = c(2, 1),
    weights = c(0.5, 0.5),
    investment = 100,
    fees = 0
  )
  
  # Expected Nominal IL = 100 * (1.5 - 1.4142136) = +8.5786437 (CORRECTED SIGN)
  expect_equal(result$`Nominal impermanent loss`, 8.5786437, tolerance = 1e-6)
  
  # Expected IL % = (1.5 - 1.4142136) / 1.5 = +0.05719096 (CORRECTED SIGN)
  expect_equal(result$impermanent_loss_percent, 0.05719096, tolerance = 1e-6)
  
  # Value if held must be correct
  expect_equal(result$`Value if held`, 150, tolerance = 1e-6)
})


# --- Test Case 2: No Price Change (IL must be zero) ---
test_that("IL is zero when prices do not change", {
  
  result <- impermanent_loss(
    prices_old = c(5, 10, 20),
    prices_new = c(5, 10, 20),
    weights = c(0.5, 0.3, 0.2),
    investment = 1000,
    fees = 50
  )
  
  # If r = 1 for all assets, nominal loss must be 0
  expect_equal(result$`Nominal impermanent loss`, 0, tolerance = 1e-6)
  
  # Net gain should equal fees earned (Fees - Nominal IL = 50 - 0)
  expect_equal(result$`Net gain`, 50, tolerance = 1e-6)
})


# --- Test Case 3: Unbalanced 3-Asset Pool (Final Fix) ---
test_that("IL calculation is correct for the 3-asset unbalanced pool", {
  
  # Run the function with local variables
  result <- impermanent_loss(
    prices_old = c(10, 20, 40),
    prices_new = c(9, 22, 35),
    weights = c(0.3, 0.2, 0.5),
    investment = 1000,
    fees = 10
  )
  
  # Nominal IL must be POSITIVE: 3.74816 (Flipped sign)
  expect_equal(result$`Nominal impermanent loss`, 3.74816, tolerance = 1e-4)
  
  # Net gain must be: Fees MINUS Nominal IL (10 - 3.74816 = 6.25184)
  expect_equal(result$`Net gain`, 6.25184, tolerance = 1e-4)
})

Try the impermanentlosscalc package in your browser

Any scripts or data that you put into this service are public.

impermanentlosscalc documentation built on Dec. 11, 2025, 5:08 p.m.