def calc_ftca(returns, threshold=0.5):
    """
    Implementation of David Varadi's Fast Threshold Clustering Algorithm (FTCA).

    http://cssanalytics.wordpress.com/2013/11/26/fast-threshold-clustering-algorithm-ftca/

    比使用k-means聚类更稳定，如果需要得到更多类，threshold设置大些

    参数:
    returns (DataFrame)：每列对应一种资产
    threshold (float): 用于控制序列相关程度的阈值，从而获得不同数量的聚类

    返回:
    dict: {cluster No.: [col names]}

    """
    i = 0
    corr = returns.corr()
    remain = list(corr.index.copy())
    n = len(remain)
    res = {}
    while n > 0:
        if n == 1:
            i += 1
            res[i] = remain
            n = 0
        else:
            cur_corr = corr[remain].ix[remain]
            mc = cur_corr.mean().order()
            low = mc.index[0]
            high = mc.index[-1]
            if corr[high][low] > threshold:
                i += 1
                res[i] = [low, high]
                remain.remove(low)
                remain.remove(high)
                rmv = []
                for x in remain:
                    avg_corr = (corr[x][high] + corr[x][low]) / 2.0
                    if avg_corr > threshold:
                        res[i].append(x)
                        rmv.append(x)
                [remain.remove(x) for x in rmv]
                n = len(remain)
            else:
                i += 1
                res[i] = [high]
                remain.remove(high)
                remain.remove(low)
                rmv = []
                for x in remain:
                    if corr[x][high] > threshold:
                        res[i].append(x)
                        rmv.append(x)
                [remain.remove(x) for x in rmv]
                i += 1
                res[i] = [low]
                rmv = []
                for x in remain:
                    if corr[x][low] > threshold:
                        res[i].append(x)
                        rmv.append(x)
                [remain.remove(x) for x in rmv]
                n = len(remain)
    return res
