import matplotlib.pyplot as plt
import json
import os
from datetime import datetime, date, timedelta
from matplotlib.dates import date2num
import yfinance as yf
import sys
import glob
import numpy as np
# path='../Febrian/Bang Nino/Samples/NEE/2020-05-08/'

my_args = sys.argv[1:]
tick = my_args[0]
filter=int(my_args[1])
visual=100
print(tick)
# path='./Samples/'+tick+'/2020-12-07/'
path='./TempData/'+tick+'/'
all_dirs   = glob.glob(path+"*")
print(path)
print(all_dirs)
latest_dir = max(all_dirs, key=os.path.getctime)
print("Latest Data = ", latest_dir)
latest_dir = latest_dir + "/"
listsymbol = os.listdir(latest_dir+'/')
print(listsymbol)

with open(latest_dir+listsymbol[0],'r') as f:
    print(latest_dir+listsymbol[0])
    hasil=json.load(f)
    # print(hasil)
    print(len(hasil[0]))
    print(len(hasil[1]))
    print(len(hasil[2]))
    akhir=datetime.strptime(str(hasil[2][-1]),'%Y-%m-%d').date()
    print("Current Log : ",akhir)
    extend1=[akhir+timedelta(days=x) for x in range(1,50,1)]
    extend=[]

    for x in extend1:
       if x.weekday() not in [5,6]:
           extend.append(x)

    extend=extend[:14]
    extend=[str(x) for x in extend]
    print("ASasdasdsa",extend)
    # date=date2num(date)
    date=hasil[2]
    plt.plot(hasil[1],color='grey',linewidth=3, linestyle='--', marker='x', alpha=0.8, label="Confirmation")
    plt.plot(hasil[2],hasil[1][0:-5],color='b',linewidth=2)
    # plt.show()

symbol=yf.Ticker(tick)
symbol=symbol.history(start=akhir,end=akhir+timedelta(days=30),interval='1d')
# print(symbol)
symbol=symbol.drop(symbol.index[0])
symbol=symbol.drop(symbol.index[0])
symbol=symbol['Close'][0:14].tolist()
# plt.plot(extend,symbol,color='g',linewidth=10)
avg=[]
for ex,x in enumerate(listsymbol):
    with open(latest_dir+x) as f:
        print(x)
        hasil=json.load(f)
        a=hasil[0][-10:][:14]
        # a = hasil[0][-14:]
        b=hasil[1][-14:]
        print("A & B Temp :")
        print(a)
        print(b)
        count=0
        for x in range(7):
            if (b[x]-(filter/10) <= a[x] <= b[x]+(filter/10)):
                count=count+1
        if count>5:
            print("HORE")
            avg.append(hasil[0][-14:])
            # plt.plot(date+extend,hasil[0], label='Sample %s'%ex, alpha=0.3)
# print(avg)
print("#################################################")
print(avg)
print(" ")
print("#################################################")
avg_total=[]
for x in range(14):
    temp=[]
    for a in range(len(avg)):
        temp.append(avg[a][x])
    # avg_total.append(sum(temp)/len(temp))
    avg_total.append(np.mean(temp))

#   print(avg_total)

atas=[x+(1/visual*x) for x in avg_total]
bawah=[x-(1/visual*x) for x in avg_total]
print([hasil[1][0:-5][-1]]+bawah)
print([hasil[1][0:-5][-1]]+atas)
print([date[-1]]+extend)
plt.fill_between([date[-1]]+extend,[hasil[1][0:-5][-1]]+bawah,[hasil[1][0:-5][-1]]+atas,alpha=0.2,label='Prediction Band')
plt.plot([date[-1]]+extend,[hasil[1][-5]]+avg_total,color='y',linewidth=1,label='Prediction', marker='x')
plt.grid()
#   plt.show()

# print("Date Extended ",(date+extend))
symbol  =   yf.Ticker(tick)
symbol  =   symbol.history(start=akhir,end=akhir+timedelta(days=20),interval='1d')
print(symbol)
symbol  =   symbol.drop(symbol.index[0])
symbol  =   symbol.drop(symbol.index[0])
symbol  =   symbol['Close'][0:14].tolist()
# symbol  =   symbol['Close'].tolist()
#   print(symbol)
# plt.plot(extend[0:len(symbol)],symbol,color='g',label='Actual',linewidth=1)
# plt.plot(hasil[1],color='r', linestyle='--', label='Confirmation',linewidth=2)
plt.plot(hasil[2]+extend[0:14],hasil[0],color='b',label='Train',linewidth=2, alpha=0.4)
# plt.plot(symbol, label="Symbol Real")
# plt.plot(hasil[0], label="Real Predictioh")
#   print(symbol)
#   print(symbol)
# detail = str(akhir)+"\n"+"Prediction :"+str(avg_total[-1:])+"\n"+"Real : " 
# plt.text(0.05, 120, detail, color='black', bbox=dict(facecolor='none', edgecolor='black', boxstyle='round,pad=1'))
plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.01),
          fancybox=True, shadow=True, ncol=7)
plt.title(tick+" Date: "+str(hasil[2][-1])+" to "+str(extend[-1]))
#   plt.get_xaxis().set_ticks([])
plt.xticks([])
plt.show()
