Skip to main content

rate_of_change

Schema: lib_math

Description

These functions calculate the percent change from the original value. Two variants of the function exist:

  • rate_of_change: Calculate the rate of change using a 1-based scale to represent the change. E.g. 0.50 represents 50%
  • rate_of_change_percentage: Calculate the rate of change using a 100-based scale to represent the change as a percentage. E.g. 50 represents 50%

All variants use this general formula to determine rate of change: (new_val - original_val) / abs(original_val)

Note that when the original_val is zero, the rate of change returned will be zero.

Usage

Signature

1-based scale (e.g. 0.50 represents 50%):

lib_math.rate_of_change(original_val numeric, new_val numeric)

100-based scale (e.g. 50.0 represents 50%):

lib_math.rate_of_change_percentage(original_val numeric, new_val numeric)

Parameters

NameTypeDescription
original_valnumericThe original value to calculate the percent change from.
new_valnumericThe new value to calculate the percent change to.

Results

The function returns a numeric value representing the percent change from the original value to the new value.

Examples

Calculating the rate of change for from 100 to 175 using a 1-based scale
select lib_math.rate_of_change(100, 175);

That statement will return 0.75.

Calculating the rate of change for from 100 to 175 using a 100-based scale
select lib_math.rate_of_change_percentage(100, 175);

That statement will return 75.

Calculate the total supply change each hour over 24 hours for a contract
with total_supplies as (
select
ts.bucket_time,
ts.total_supply_in_underlying,
lag(ts.total_supply_in_underlying, 1) over (order by ts.bucket_time) as previous_total_supply_in_underlying
from lib_lending.lending_pool_total_supply(
'0xce86ebc669bbf07a64a0a55bb105cc2b5b5d1961',
now() - '1 day'::interval,
now(),
'1 hour'::interval
) ts
order by ts.bucket_time
)
select
ts.bucket_time as time,
lib_math.rate_of_change_percentage(
ts.previous_total_supply_in_underlying,
ts.total_supply_in_underlying
) as val,
ts.total_supply_in_underlying,
ts.previous_total_supply_in_underlying
from total_supplies ts;