# -*- coding: utf-8 -*-
"""wakanda

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1cXTtvVZdqIXAR506mUQLwzbCwDeHfJO_
"""

import pandas as pd
import numpy as np
from datetime import datetime
from fake_useragent import UserAgent
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
import re
import urllib.parse
from urllib.error import HTTPError
import math
import ssl

def normalize_num(num):
    non_decimal = re.compile(r'[^\d.-]+')
    nom_decimal = non_decimal.sub('', num.replace(",",".")).replace(" ","")
    return float(nom_decimal)

class stock:
    def __init__(self,market='brvm'):
        if market.lower() not in ['brvm','gse','ngse','lse','zse','bse','luse','mse']:
            print('Please pass a correct parameter for market.')
            self.market = None
        else:
            self.market=market

    def DataReader(self,symbol='',start='',end='',adj=False):
        if self.market == None:
            print('Please pass a correct parameter for market.')
            return
        if symbol in ['brvm','gse','ngse','lse','zse','bse','luse','mse']:
            symbol=''

        if start:
            try:
                start = datetime.strptime(start, '%m-%d-%Y')
            except:
                print('Please pass a correct parameter for start date! Format should be m-d-y')
                return None
        if end:
            try:
                end = datetime.strptime(end, '%m-%d-%Y')
            except:
                print('Please pass a correct parameter for end date! Format should be m-d-y')
                return None
        df,htmlfile='',''
        url = "https://afx.kwayisi.org/chart/"+self.market+'/'+symbol
        try:
            htmlfile = urlopen(url).read().decode()
        except:
            print('Something went wrong!')
        else:
            beg = htmlfile.find("[[")
            stop = htmlfile.rfind("],]")
            histData_text = htmlfile[beg+2:stop].replace('d("','').replace('")','').split("],[")
            chartData = []
            for elem in histData_text:
              chartData.append(elem.split(","))

            #get close price
            df = pd.DataFrame(np.array(chartData),columns=['date','close price'])
            df['close price'] = pd.to_numeric(df['close price'])
            df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')

            # collect imformation about stock split
            if adj is True:
                df['ratio'] = round(1/(df['close price'].pct_change()+1),0)
                myresult = df[df['ratio'] >= 2 ]
                if len(myresult) >=1 :
                    for i in list(myresult.index):
                        date = df.loc[i,'date']
                        split = df.loc[i,'ratio']
                        for j in list(df.index):
                            d=1
                            if df.loc[j,'date'] < date:
                                d=split
                            df.loc[j,'adj. price'] = round(int(df.loc[j,'close price'])/d,1)
                df = df.drop('ratio',axis=1)
            #filter base on start and end date
            if start:
                df = df[df['date'] >= np.datetime64(start,'D')]
            if end:
                df = df[df['date'] <= np.datetime64(end,'D')]

            #change date format
            df['date'] = df['date'].dt.strftime('%m-%d-%Y')
            #reset index
            df.reset_index(drop=True, inplace=True)

        return df

    def get_quote(self,symbol):
        if isinstance(symbol, str):
            symbol = [symbol]
        url = 'https://www.brvm.org/fr/cours-actions/0'
        ssl._create_default_https_context = ssl._create_unverified_context
        header = {'User-Agent':str(UserAgent().chrome)}
        req = Request(url, headers=header)
        try:
            html = urlopen(req).read()
        except:
            print('Something went wrong!')
        else:
            try:
               soup = BeautifulSoup(html, "html.parser")
            except AttributeError as e:
                print(e)
            else:
                market_status = ''
                status = soup.find("div",{"class":"block-seance"}).div.text
                status = status.strip()
                if status.find("Ouverte") is not -1:
                    market_status = 'open'
                elif status.find("fermée") is not -1:
                    market_status = 'closed'
                current_price,price_change = {},{}
                if market_status == 'open':
                    for stock in soup.find("section",{"id":"slide-seance"}).findAll("div"):
                        item = stock.findAll("span")
                        if len(item)>0:
                            ticker = item[0].text.strip()
                            if ticker in symbol:
                                current_price[ticker]=(normalize_num(item[1].text.strip()))
                                price_change[ticker]=(normalize_num(item[2].text.strip()))

                volume,open_price,close_price,valid={},{},{},[]
                for stock in soup.find("section",{"id":"block-system-main"}).findAll("tr"):
                    item = stock.findAll("td")
                    if len(item)>0:
                        ticker = item[0].text.strip()
                        if ticker in symbol:
                            valid.append(ticker)
                            volume[ticker]=(normalize_num(item[2].text.strip()))
                            open_price[ticker]=(normalize_num(item[4].text.strip()))
                            close_price[ticker]=(normalize_num(item[5].text.strip()))

                if market_status:
                    print('Market status: '+market_status)
                print('\n')
                if market_status == 'open':
                    print('            Current price          Volume      Open price')
                    print('Symbol')
                    for i in symbol:
                        if i in valid:
                            print(i ,'        ',current_price[i],'          ',volume[i],'        ',open_price[i])
                        else:
                            print(i ,'        cannot find                                         ')
                elif market_status == 'closed':
                    print('            Close price           Volume        Open price')
                    print('Symbol')
                    for i in symbol:
                      if i in valid:
                        print(i ,'        ',close_price[i],'          ',volume[i],'        ',open_price[i])
                      else:
                        print(i ,'        cannot find                                        ')
