import scipy
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# rs = real sortino

def sortino_c(rets, target=0):
    """ PMPT continuous Sortino, returns and target are in annualized percent """
    
    # annualized target in percent to daily
    target = target / 252.0
    # print "daily target", target

    # get params of shape of distribution
    params = scipy.stats.johnsonsu.fit(rets.dropna())
    
    # downside risk from PMPT
    f = lambda x: (target - x)**2 * scipy.stats.johnsonsu.pdf(x,*params)    
    
    # integrate over function
    i, abs_error = scipy.integrate.quad(f, -0.5, target)
    # print "abs_error", abs_error
    result = np.sqrt(252) * (rets.mean() - (target)) / np.sqrt(i)
    # print result

    # x = np.linspace(-np.inf, target, 1000)        
    # print pd.Series(x).apply(f)
    # plt.plot(x, f(x))
    # plt.show()

    return result
    
def var(returns, alpha=0.05):
    """ Computes daily VaR (Value at risk) for specified alpha assuming johnsonsu distribution """
    params = scipy.stats.johnsonsu.fit(returns.dropna())
    return scipy.stats.johnsonsu.ppf(alpha, *params)

def sortino_d(rets, target=0):
    """ discrete sortino """    
    f_mean = rets.mean()
    days = 252 #rets.count() # - annualized sortino
    negative_rets = rets[rets < target]          
    downside_risk = np.sqrt((negative_rets**2).mean())
    f_sortino = f_mean * np.sqrt(days) / downside_risk
    return f_sortino  

# def expected_shortfall(returns, alpha=0.05):
#     params = scipy.stats.johnsonsu.fit(returns.dropna())
#     rv = scipy.stats.johnsonsu(*params)
#     # f = lambda x : scipy.stats.johnsonsu.pdf(x,*params)
#     # i, abs_error = scipy.integrate.quad(f, -0.5, target)
#     return expect(rv,None, -0.5, var(returns,alpha))

# def expect(X, f, lb, ub):
#     if hasattr(X, 'dist'):
#         return X.dist.expect(func=f, lb = lb, ub = ub)
#     else:
#         return X.expect(func=f, lb = lb, ub = ub)