IRR Calculate (finance)
by mesias - Saturday September 23, 2023 at 03:17 AM
#1
I Want to share this PostgreSQL Function Big Grin

-- Function: irr_calculate(double precision[]) -- DROP FUNCTION irr_calculate(double precision[]); -- Just enter cash flow to use this function CREATE OR REPLACE FUNCTION irr_calculate(cashflows double precision[])   RETURNS double precision AS $BODY$ DECLARE     epsilon double precision := 0.00001; -- The desired level of precision     max_iterations integer := 100; -- Maximum number of iterations     guess double precision := 0.1; -- Initial initialization for IRR     irr double precision := 0.0; -- Initialize IRR to 0     npv double precision;     derivative double precision; BEGIN     FOR i IN 1..max_iterations LOOP         npv := 0.0;         derivative := 0.0;                 FOR j IN 1..array_length(cashflows, 1) LOOP             npv := npv + cashflows[j] / power(1.0 + irr, j - 1);             derivative := derivative - j * cashflows[j] / power(1.0 + irr, j);         END LOOP;                 irr := irr - npv / derivative;                 IF abs(npv) < epsilon THEN             RETURN irr * 100.0;         END IF;     END LOOP;         RAISE EXCEPTION 'The IRR calculation did not found'; END; $BODY$   LANGUAGE plpgsql VOLATILE   COST 100; ALTER FUNCTION irr_calculate(double precision[])   OWNER TO postgres;  
Reply




 Users browsing this thread: 1 Guest(s)