更新於 2020/05/11閱讀時間約 3 分鐘

Branching Ratio in R (Hawkes Model)

    TW.Data=fread('test.txt',data.table=F)
    colnames(TW.Data)=c("Name","Code","Date","Price","Vol")
    TW.Codelist=unique(TW.Data$Code)
    TW.Data=TW.Data %% group_by(Name) %% mutate(logRet=log(Price/lag(Price)))
    TW.Data$Date=ymd(TW.Data$Date)
    output=foreach(i = 1:length(TW.Codelist),.combine = 'rbind')%do%{
    data=TW.Data %% filter(Code==TW.Codelist[i]) %% na.omit()
    Strt.Date = data$Date[1]
    Time= data %% filter(data$logRet!=0) %%
    mutate(Time=Date - Strt.Date) %%
    as.data.frame() %%
    select(Time)
    Time=as.numeric(Time$Time)
    if(length(Time)=2){
    temp = data.frame(Code=TW.Codelist[i],Br=NA)
    }else{
    pstart = c(mu = 1, C = 1, a = 1)
    ppm = ptproc(pts = Time, cond.int = hawkes.cond.int, params = pstart)
    condition(ppm) = penalty(code = NULL, condition = quote(any(params 0)))
    model = ptproc.fit(ppm, optim.control = list(trace = 2), alpha = 1e+5, hessian = TRUE)
    model.sum=summary(model)
    fitted.value=model.sum$ppobj
    Branch=fitted.value$params[3]/fitted.value$params[2]
    temp = data.frame(Code=TW.Codelist[i],Br=Branch)
    }
    return(temp)
    }
    write.csv(output,"output.csv")
    分享至
    成為作者繼續創作的動力吧!
    © 2024 vocus All rights reserved.