
import pandas_datareader.data as pdr
import numpy as np
import datetime

ticker = 'AMZN'
ohlcv = pdr.get_data_yahoo(ticker, datetime.date.today() - datetime.timedelta(1825), datetime.date.today())
n = 14

# Plot
# ohlcv['Adj Close'].plot()

DF = ohlcv.copy()

def CAGR(DF):
    df = DF.copy()
    df['daily_ret'] = DF['Adj Close'].pct_change()
    df['cum_return'] = (1 + df['daily_ret']).cumprod() 
    n = len(df) / 252
    CAGR = (df['cum_return'][-1]) ** (1 / n) - 1
    return CAGR

cagr = CAGR(DF)

def volatility(DF):
    df = DF.copy()
    df['daily_ret'] = DF['Adj Close'].pct_change()
    vol = df['daily_ret'].std() * np.sqrt(252)
    return vol

# rf: risk free return
def sharpe(DF, rf):
    df = DF.copy()
    sr = (CAGR(df) - rf) / volatility(df)
    return sr

rf = 0.022

sharpe_res = sharpe(ohlcv, rf)


def sortino(DF, rf):
    df = DF.copy()
    df['daily_ret'] = DF['Adj Close'].pct_change()
    neg_vol = df[df['daily_ret'] < 0]['daily_ret'].std() * np.sqrt(252) 
    sr = (CAGR(df) - rf) / neg_vol
    return sr

sortino_res = sortino(ohlcv, rf)


def max_dd(DF):
    df = DF.copy()
    df['daily_ret'] = DF['Adj Close'].pct_change()
    df['cum_return'] = (1 + df['daily_ret']).cumprod()
    df['cum_roll_max'] = df['cum_return'].cummax()
    # df['cum_return'].iloc[-100:].plot(title='cum_return')
    df['drawdown'] = df['cum_roll_max'] - df['cum_return']
    df['drawdown_pct'] = df['drawdown'] / df['cum_roll_max']
    max_dd = df['drawdown'].max()
    return max_dd
    
max_dd_res = max_dd(ohlcv)

ohlcv['Adj Close'].plot()
    
def calmar(DF):
    '''
    This function calculate the Calmar ratio
    
    * Calmar Ratio is the ratio of CAGR and Max drawdown and it's measure of risk adjusted return.
    '''
    df = DF.copy() 
    clmr = CAGR(df) / max_dd(df)
    return clmr

calmar_res = calmar(ohlcv)