# IMPORTING PACKAGES
import pandas as pd
import requests
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from math import floor
from termcolor import colored as cl
import pandas as pd
import finnhub
from sklearn.cluster import KMeans
import mplfinance as mpf
from mplfinance.original_flavor import candlestick_ohlc
import matplotlib.dates as mpl_dates
from datetime import * 
import seaborn as sns
from datetime import datetime

df= pd.read_excel(r'C:\Users\jizha\Desktop\09_21_2022_pasttrade.xlsx')
df.columns
df = df.set_index('symbol')
c = df.copy()

c = c[['Exit_Date','p_gain_loss%']]
c['Exit_Date1'] =pd.to_datetime(c['Exit_Date']).dt.date

k = c.groupby('Exit_Date').sum()
k = k.sort_index()

    
def CAGR(DF):
    "function to calculate the Cumulative Annual Growth Rate of a trading  strategy"
    df = DF.copy()
    df["cum_return"] = (1 + df["mon_ret"]).cumprod()
    n = len(df)/225
    CAGR = (df["cum_return"].tolist()[-1])**(1/n) - 1
    return CAGR

def volatility(DF):
    "function to calculate annualized volatility of a trading strategy"
    df = DF.copy()
    vol = df["mon_ret"].std() * np.sqrt(225)
    return vol

def sharpe(DF,rf):
    "function to calculate sharpe ratio ; rf is the risk free rate"
    df = DF.copy()
    sr = (CAGR(df) - rf)/volatility(df)
    return sr
    

def max_dd(DF):
    "function to calculate max drawdown"
    df = DF.copy()
    df["cum_return"] = (1 + df["mon_ret"]).cumprod()
    df["cum_roll_max"] = df["cum_return"].cummax()
    df["drawdown"] = df["cum_roll_max"] - df["cum_return"]
    df["drawdown_pct"] = df["drawdown"]/df["cum_roll_max"]
    max_dd = df["drawdown_pct"].max()
    return max_dd    





import yfinance as yf
start1 = '2021-08-06'
end1 = '2022-09-15'

#DJI= yf.download("^DJI",start1,end1,interval='1mo')
#DJI["mon_ret"] = DJI["Adj Close"].pct_change()
spy= yf.download("^GSPC",start1,end1,interval='1d')

spy["mon_ret"] = spy["Adj Close"].pct_change()
spy = spy.dropna()
spy1 =pd.DataFrame(spy.loc[:,'mon_ret'])
all_mon_ret =spy1.copy()

CAGR(all_mon_ret)
sharpe(all_mon_ret,0.025)
max_dd(all_mon_ret)
volatility(all_mon_ret)

g =k.copy()
g['mon_ret'] = g['p_gain_loss%']
CAGR(g)
sharpe(g,0.025)
max_dd(g)
volatility(g)

# st = pd.merge(spy1, g, how = 'left')
# spy = spy.dropna()
# ef = ef.iloc[1:,:]

st= spy1.merge(g, how='outer', left_index=True, right_index=True)
st['p_gain_loss%'] = st['p_gain_loss%'].replace(np.nan, 0)
st.columns

st['mon_ret'] =  st['mon_ret'].replace(np.nan, 0)
st1 = st[['p_gain_loss%','mon_ret_x']]
st =st1.copy()
st2 = st[['mon_ret_x','date']]
st3 = st[['p_gain_loss%','date']]
#f['DataFrame Column'] = df['DataFrame Column'].replace(np.nan, 0)
#visualization
st1['date'] =st1.index
st1['date'] =pd.to_datetime(st1['date']).dt.date
st1['date'] =pd.to_datetime(st1['date'])-pd.to_timedelta(7, unit='d')
st12= st2.groupby([pd.Grouper(key='date', freq='W')])['mon_ret_x'].sum()
st13= st3.groupby([pd.Grouper(key='date', freq='W')])['p_gain_loss%'].sum()
st12 =pd.DataFrame(st12)
st13 =pd.DataFrame(st13)
st= st12.merge(st13, left_index=True, right_index=True)
import pandas as pd

#create DataFrame
df = pd.DataFrame({'date': pd.date_range(start='1/5/2022', freq='D', periods=15),
                   'sales': [6, 8, 9, 5, 4, 8, 8, 3, 5, 9, 8, 3, 4, 7, 7]})

#view DataFrame
print(df)
df['date'] = pd.to_datetime(df['date']) - pd.to_timedelta(7, unit='d')

#calculate sum of values, grouped by week
df.groupby([pd.Grouper(key='date', freq='W')])['sales'].sum()
st.to_excel(r'C:\Users\jizha\Desktop\test_data.xlsx')
r'C:\Users\jizha\Desktop\09_21_2022_pasttrade.xlsx'
fig, ax = plt.subplots()
#t = st.reset_index()
st['date'] = st.index
st['date'] = st['date'].dt.date
st['Portfolio_return%'] = st['p_gain_loss%']
st['SPY_return%'] = st['mon_ret_x']


st.plot(x ='date', y ='SPY_return%', kind = 'bar' )
st.plot(x ='date', y ='Portfolio_return%', kind = 'bar' )
st.plot(x ='date', y = ['SPY_return%','Portfolio_return%'], kind = 'bar', color=['red','blue'] )
plt.xticks(rotation = 90)




fig, ax = plt.subplots(dpi = 300 )
ax.set_facecolor('white') 
fig.patch.set_facecolor('white')
ax.ticklabel_format(style='plain')
plt.plot(((1+st['SPY_return%'] ).cumprod()*10000), color = 'red', linewidth = 0.9, label = 'SPY')
plt.plot(((1+st['Portfolio_return%'] ).cumprod()), color = 'purple', linewidth = 0.9, label= 'Portfolio')
plt.legend(loc='upper left')
#plt.title(ticker+ '   Supports and Resistances')
plt.title("Portfolio VS SPY Culumative Return", size = 14, y =0.95)
plt.xticks(rotation=30)
plt.show()


#################################test#########################
from datetime import datetime as dt
import datetime
today = dt.today()
yesterday = today-datetime.timedelta(1)
end = (yesterday.year, yesterday.month, yesterday.day)

for ticker in group1:
    ticker = 'MSFT'
    data1 =  strategy_performance( ticker ,  start = (2011,2,21),  end = end)
   

