from pandas_datareader import data as pdr
import json
from yahoo_fin import stock_info as si
from pandas import ExcelWriter
import numpy as np
import matplotlib.pyplot as plt 
import yfinance as yf
import pandas as pd
import requests
import datetime
import time
import sys
import glob
import os


def roc11(closes):
    print(len(closes))
    roc11_val   = []
    roc14_val   = []
    roc_sum     = []
    x = len(closes)
    for i in range(x):
        if i+11 == x: # Fixed
            break
        # cur_indx = x - i
        # temp_11 = (closes[cur_indx] - closes[cur_indx-11])/closes[cur_indx-11]*100
        temp_11 = (closes[i+11] - closes[i])/closes[i]*100
        roc11_val.append(temp_11)

    for i in range(x):
        if i+14 == x: # Fixed
            break
        temp_14 = (closes[i+14] - closes[i])/closes[i]*100
        roc14_val.append(temp_14)

    for i in range(len(roc14_val)):
        roc_sum.append(roc11_val[i+3]+roc14_val[i])
    print("Finished ")
    return roc_sum

def wma10(roc_sum, n=10):
    roc_sum = pd.DataFrame(roc_sum, columns=['COPPOCK'])
    weights = np.arange(1, n+1)
    wmas = roc_sum.rolling(n).apply(lambda x:np.dot(x, weights)/weights.sum(), raw=True)
    
    print(wmas)
    return wmas


yf.pdr_override()

# stocklist = si.tickers_sp500()
# stock_file = open("./symbols_backup.txt", "r")
# stocklist = stock_file.readlines()
# stock_file.close()
# index_name = '^GSPC' # S&P 500

final = []
index = []
n = -1

def screener(ticker):
    # ticker = sys.argv[1]
    path='./Samples/'+ticker+'/'
    all_dirs   = glob.glob(path+"*")
    print(path)
    print(all_dirs)
    latest_dir = max(all_dirs, key=os.path.getmtime)
    print("Latest Data = ", latest_dir)
    latest_dir = latest_dir + "/"
    listsymbol = os.listdir(latest_dir+'/')
    path = open(latest_dir+listsymbol[0])
    a = json.load(path)
    
    pred_stock = a[0]
    real_pred = a[1]
    
    # RS_Rating 
    start_date = datetime.datetime.now() - datetime.timedelta(days=(365*3)+13)
    end_date = datetime.date.today()
    # 
    df = pdr.get_data_yahoo(ticker, start=start_date, end=end_date)
    real_stock = df["Close"].values
    # real_stock = real_stock.reset_index(drop=True, inplace=True)
    # real_stock = df["Close"].drop("Date")
    print(real_stock)
    print("************")
    closePrice = pred_stock
    # print(closePrice.head())
    
    roc_res = roc11(closePrice)
    wma_res = wma10(roc_res)
    print("==========")
    print(len(wma_res));
    print(len(closePrice));
    print(closePrice.index)
    entry_buy = []
    entry_sell= []
    entry_date = []
    
    
    # i = 0
    entry_buy = []
    
    val = wma_res["COPPOCK"]
    y = 0
    while (y<len(val)-4):
        x = val[y]
        z = val[y+1]
    
        if x < z:
            x = z
    
        if x > z and x < val[y+4]:
            entry_buy.append(y+1)
    
        y = y+1
    
    y = 0
    while (y<len(val)-1):
        x = val[y]
        z = val[y+1]
        if x > z:
            x = z
        if x < z and x > val[y+1]:
            entry_sell.append(y)
        y = y+1
    
    mark_zero = []
    for i in range(len(wma_res)-1):
        mark_1 = wma_res["COPPOCK"][i]
        mark_2 = wma_res["COPPOCK"][i+1]
        if mark_1 > 0 and mark_2 < 0:
            mark_zero.append(i+1)
    
    mark_zero_sell = []
    for i in range(len(wma_res)-20):
        mark_1 = wma_res["COPPOCK"][i]
        mark_2 = wma_res["COPPOCK"][i+1]
        if mark_1 < 0 and mark_2 > 0:
            mark_zero_sell.append(i+1)
    
    print(entry_buy[-10:])
    for i in  range(len(entry_buy)):
        entry_buy[i] = entry_buy[i]+21
    
    for i in  range(len(mark_zero)):
        mark_zero[i] = mark_zero[i]+21
    
    for i in  range(len(mark_zero_sell)):
        mark_zero_sell[i] = mark_zero_sell[i]+21
    
    for i in  entry_sell:
        i = i+14
    
    print(entry_buy[-10:])
    
    # ax1 = plt.subplot(211)
    # plt.title("COPPOCK Indicator "+str(ticker))
    # plt.plot(real_stock[2:], linewidth=2, label="real", linestyle="--")
    # plt.plot(real_pred, linewidth=2, label="real", linestyle="--")
    # plt.plot(closePrice, linewidth=0.2, label="Prediction")
    # plt.legend()
    # 
    # ax2 = plt.subplot(212, sharex=ax1)
    
    fill_front = []
    for i in range(21):
        fill_front.append(np.nan)
    fill_front.extend(wma_res["COPPOCK"])
    
    wma_res = fill_front
    
    # plt.plot(range(len(wma_res)), wma_res, markevery=mark_zero_sell, marker="x", mfc='c', linewidth=0.8)
    # plt.plot(range(len(wma_res)), wma_res, markevery=mark_zero, marker="x", mfc='c', linewidth=0.8)
    # plt.plot(range(len(wma_res)), np.zeros(len(wma_res)), linewidth=0.8)
    # 
    # plt.show()
    # plt.savefig("./screening_result/pred.png")
    # plt.close()
    indictaor = []
    indictaor.append(wma_res)
    indictaor.append(np.zeros(len(wma_res)))
    markers = []
    markers.append(mark_zero)
    markers.append(mark_zero_sell)
    stocks = []
    stocks.append(real_pred)
    stocks.append(closePrice)
    return indictaor, markers, stocks

#  screener("MA")


# writer = ExcelWriter("ScreenOutput.xlsx")
# exportList.to_excel(writer, "Sheet1")
# writer.save()
