import matplotlib.pyplot as plt
import json
from pylab import *

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/'
def return_plot(plotax,ticks,filters):
    #my_args = sys.argv[1:]
    #tick = my_args[0]
    #filter=int(my_args[1])
    tick=ticks
    filter=filters
    visual=100
    print(tick)
    # path='./Samples/'+tick+'/2020-12-07/'
    path='./Samples/'+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]
        plotax.plot(hasil[1],color='grey',linewidth=3, linestyle='--', marker='x', alpha=0.8, label="Confirmation")
        plotax.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("#################################################")
            print(x)
            hasil=json.load(f)
            # a=hasil[0][-14:][:14]
            a = hasil[0][-14:][:7]
            b=hasil[1][-7:]
            print("A & B Temp :")
            print(a)
            print(b)
            count=0
            print("Predict - Real ")
            for x in range(7):
                print("%.2f" % (a[x]-b[x]))
                if (b[x]-(filter/10) <= a[x] <= b[x]+(filter/10)):
                    count=count+1
            if count>5:
                print("ACCEPTED . . .")
                predict_val = hasil[0][-14:]
                avg.append(predict_val)
                # avg.append(hasil[0][-10][:14])
                # plt.plot(date+extend,hasil[0], label='Sample %s'%ex, alpha=0.3)
                print()
            else:
                print("NOT ACCEPTED . . .")
                print()
    # print(avg)
    print("#################################################")
    print(avg)
    print(len(avg))
    print("#################################################")
    avg_total=[]
    for x in range(len(extend)):
        temp=[]
        for a in range(len(avg)):
            temp.append(avg[a][x])
        # avg_total.append(sum(temp)/len(temp))
        mean_pred = np.mean(temp)
        print(mean_pred)
        avg_total.append(mean_pred)

    #   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)
    plotax.fill_between([date[-1]]+extend,[hasil[1][0:-5][-1]]+bawah,[hasil[1][0:-5][-1]]+atas,alpha=0.2,label='Prediction Band')
    plotax.plot([date[-1]]+extend,[hasil[1][-5]]+avg_total,color='y',linewidth=1,label='Prediction', marker='x')
    plotax.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'))
    plotax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.01),
              fancybox=True, shadow=True, ncol=7)
    plotax.title.set_text(ticks)
    #plotax.title(tick+" Date: "+str(hasil[2][-1])+" to "+str(extend[-1]))
    #   plt.get_xaxis().set_ticks([])
    #plotax.xticks([])
    return plotax


#subplots_adjust(hspace=0.000)
#symbolss=os.listdir("Samples")
symbolss=["GOOGL","FB","MA","SHOP","NEE"]
#number_of_subplots=len(os.listdir("Samples"))
number_of_subplots=5
for i,v in enumerate(range(number_of_subplots)):
    v = v+1
    ax1 = subplot(number_of_subplots,1,v)
    ax1 = return_plot(ax1,symbolss.pop(0),900)
plt.tight_layout()
plt.show()
