# from pandas_datareader import data
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
import datetime as dt
import urllib.request, json
import os
import alpha_advantage_api_key as aa_api_key
import polygon_api_key as poly_api_key
# import numpy as np
import mplfinance as mpf
from mplfinance.original_flavor import candlestick_ohlc

#  import tensorflow as tf # This code has been tested with TensorFlow 1.6
# from sklearn.preprocessing import MinMaxScaler

ROOTDIR = os.path.abspath(os.curdir)
POLYGON_API_KEY = poly_api_key.POLYGON_API_KEY
ALPHA_ADVANTAGE_API_KEY = aa_api_key.ALPHA_ADVANTAGE_API_KEY

# Stock ticker
ticker = 'SPY'

# API Urls
polygon_url_string = 'https://api.polygon.io/v2/aggs/ticker/%s/range/1/day/2023-01-09/2023-01-09?apiKey=%s'%(ticker, POLYGON_API_KEY)
alpha_advantage_url_string = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=%s&outputsize=full&apikey=%s"%(ticker, ALPHA_ADVANTAGE_API_KEY)

# Save data to this file
file_to_save = os.path.join(ROOTDIR, 'StockPrediction-Gitlab', 'market_data', ticker + '.csv')
#file_to_save = '%s/StockPrediction-Gitlab/market_data/%s.csv'%(ROOTDIR, ticker)

if not os.path.exists(file_to_save):
    with urllib.request.urlopen(alpha_advantage_url_string) as url:
        data = json.loads(url.read().decode())
        # print(data)
        # with open("sample.json", "w") as outfile:
        #     json.dump(data, outfile)
        # extract stock market data
        data = data['Time Series (Daily)']
        df = pd.DataFrame(columns=['Date','Low','High','Close','Open', 'Volume'])
        for k,v in data.items():
            date = dt.datetime.strptime(k, '%Y-%m-%d')
            data_row = [date.date(),float(v['3. low']),float(v['2. high']),
                        float(v['4. close']),float(v['1. open']),float(v['6. volume'])]
            df.loc[-1,:] = data_row
            df.index = df.index + 1
    # print('Data saved to : %s'%file_to_save)        
    df.to_csv(file_to_save)
    # df.to_json(file_to_save + '.json')

    # If the data is already there, just load it from the CSV
else:
    print('File already exists. Loading data from CSV')
    

if not os.path.exists(file_to_save):
    quit("File not found")

df = pd.read_csv(file_to_save, index_col=0, parse_dates=True, skipinitialspace=False)

# Sort DataFrame by date
df = df.sort_values('Date')
df_reverse = df.sort_values('Date', ascending=False)

# Display 5 most recent days
print(df_reverse.head().to_string(index=False))

# Plot
plt.figure(figsize = (12,6))
plt.plot(range(df.shape[0]),(df['Low']+df['High'])/2.0)
plt.xticks(range(0,df.shape[0],500),df['Date'].loc[::500],rotation=45)
plt.xlabel('Date',fontsize=18)
plt.ylabel('Mid Price',fontsize=18)
plt.title(ticker, fontsize=26)
plt.show()

# One Month Candlestick Chart
current_date = dt.datetime.now()
formatted_current_date = current_date.strftime('%Y-%m-%d')
formatted_one_month_ago = (current_date - dt.timedelta(days=30)).strftime('%Y-%m-%d')

# Candlestick using mplfinance NEW API
df.index = pd.DatetimeIndex(df['Date'])
tdf = df.loc[formatted_one_month_ago:formatted_current_date,:]
mpf.plot(tdf, type='candlestick', style='charles', volume=True, title=ticker, figsize=(12,6))

# Three Month Candlestick Chart
formatted_three_month_ago = (current_date - dt.timedelta(days=90)).strftime('%Y-%m-%d')
tdf = df.loc[formatted_three_month_ago:formatted_current_date,:]
mpf.plot(tdf, type='candlestick', style='charles', volume=True, title=ticker, figsize=(12,6))

# One Year Candlestick Chart
formatted_one_year_ago = (current_date - dt.timedelta(days=365)).strftime('%Y-%m-%d')
tdf = df.loc[formatted_one_year_ago:formatted_current_date,:]
mpf.plot(tdf, type='candlestick', style='charles', volume=True, title=ticker, figsize=(12,6))