import math


def compute_sharpe_ratio(daily_rets, rf=0, freq='daily'):
    """
         mean(Rp - Rf)
    SR = -------------
            std(Rp)

    sharpe ratio is an annual measure, so:
    SR_annualized = K * SR

    K = square root of #samples of year

    daily K = square root of 252
    weekly K = square root of 52
    monthly K = square root of 12

    risk free rate:
    1. LIBOR: London Interbank Offer Rate 伦敦银行同业拆放利率
    2. 3mo T-bill: 3 month Treasury bill 3月期国债利率
    3. 0%

    FOR EXAMPLE, cacluate SR using daily data:

                   mean ( daily_rets - daily_risk_free_rate )
    sharpe_ratio = ------------------------------------------
                    std ( daily_rets - daily_risk_free_rate )

    SR = sqrt(252) * (daily_rets - daily_rf).mean() / daily_rets.std()

    daily risk free rate traditional shortcut:
    daily_rf = 252nd root of (1 + Rf)

    :return:
    """
    freqs = {'daily': 252, 'weekly': 52, 'monthly': 12, 'yearly': 1}
    f = freqs[freq]
    k = math.sqrt(f)

    daily_rf = math.pow(1+rf, 1/f) - 1

    sr = k * (daily_rets - daily_rf).mean() / daily_rets.std()

    return sr