*! fracirf 1.0.1  C F Baum 0A11
* mod 0A11 to add cumulative function
* calculate an approximation to the impulse response function (infinite
* MA representation) of an ARFIMA(p,d,q) model
* from its estimated AR, MA, and d coefficients
* Following Gourieroux and Monfort, Time series and dynamic models,
* theorem 11.10 (1997, p.438)

program define fracirf,rclass
version 6.0
syntax newvarname, D(real) [ AR(numlist) MA(numlist) CUM(string)]

     if "`cum'" != "" {
        	capture confirm new variable `cum'
        	if _rc {
                	di in r "`cum' already exists: " _c
                	di in r "specify new variable with cum( ) option"
                	exit 110
        	}
        }
local sumar 1.0
local summa 1.0

if "`ar'" !="" {
	local n_ar : word count `ar'
	tokenize `ar'
	local i 1
	while "``i''" != "" {
		local sumar = `sumar'-``i''
		local i = `i'+1
		}
	di " "
	di "AR(`n_ar'): phi(1) = `sumar'"
	if `sumar'<=0 {
		di in r "Error: phi must be stationary => phi(1) > 0"
		drop `varlist'
		exit
		}
	}
if "`ma'" !="" {
	local n_ma : word count `ma'
	tokenize `ma'
	local i 1
	while "``i''" != "" {
		local summa = `summa'+``i''
		local i = `i'+1
		}
	di " "
	di "MA(`n_ma'): theta(1) = `summa'"
	if `summa'==0 {
		di in r "Error: theta must be invertible => theta(1) != 0"
		drop `varlist'
		exit
		}
	}
local mult = `summa'/(`sumar'*exp(lngamma(`d')))
qui gen double `varlist' = _n^(`d'-1)*`mult'
if "`cum'" !="" {
	qui gen double `cum' = sum(`varlist')
	}
end