'fit Pareto with nested optimization
originally published on stackoverflow'

def fit_ks1_trim(self):

    self.nobs = self.endog.shape[0]
    rvs = np.sort(self.endog)
    rvsmin = rvs.min()
    def pareto_ks(loc, rvs):
        est = stats.pareto.fit_fr(rvs, frozen=[np.nan, loc, np.nan])
        args = (est[0], loc, est[1])
        return stats.kstest(rvs, 'pareto', args)[0]
    maxind = min(np.floor((self.nobs * 0.95)).astype(int), (self.nobs - 10))
    res = []
    for trimidx in range((self.nobs // 2), maxind):
        xmin = loc = rvs[trimidx]
        res.append([trimidx, pareto_ks((loc - 1e-10), rvs[trimidx:])])
    res = np.array(res)
    bestidx = res[(np.argmin(res[:, 1]), 0)].astype(int)
    print(bestidx)
    locest = rvs[bestidx]
    est = stats.pareto.fit_fr(rvs[bestidx:], 1.0, frozen=[np.nan, locest, np.nan])
    args = (est[0], locest, est[1])
    return args
