<reponame>jhssilva/Smartie
''' 
                Libraries 
'''
# External libraries
import yfinance as yf #Librarie to connect to Yahoo Finance
#Edited : Add to line 286-292 in base.py of yfinance (https://github.com/ranaroussi/yfinance/issues/208)
#Edited: Comment line 319 in base.py of yfinance because of the error     self._info['regularMarketPrice'] = self._info['regularMarketOpen'] KeyError: 'regularMarketOpen'

# General Libraries
import json 
import sys
import threading #Librarie for threads
import time #Librarie for time purposes

# Libraries from the project
import stock as stk

''' 
                Functions
'''

# Read file with all stock symbols in the market (The file should be updated, but unfortunately just have one request to the api for month )
def fileReadSymbolStocks():
    f = open("Files/StockList.txt", "r")
    p = json.loads(f.read())
    f.close()
    return p

# Creating objects of a stock, with Symbol that identifies the stock and the ticker for doing the request.
def creatingStocks(symbol):
    for x in symbolStock:
        stocks.append(stk.stock(x, yf.Ticker(x)))


''' 
                Get Functions
'''
# General info of a stock
def getStockInfo(stock):
    return stock.getTicker().info

# Historical Market Data of a Stock
def getStockHistoricalMarketData(stock):
    return stock.getTicker().history(period = "max", threads = False)

# Actions (Dividends, splits) of a stock
def getStockActions(stock):
    return (stock.getTicker().actions)

# Dividends of a stock
def getStockDividends(stock):
    return (stock.getTicker().dividends)

# Splits of a stock
def getStockSplits(stock):
    return (stock.getTicker().splits)

# Financials of a stock
def getStockFinancials(stock):
    return (stock.getTicker().financials)

# Quarterly financials of a stock
def getStockQuarterlyFinancials(stock):
    return (stock.getTicker().quarterly_financials)

# Major holders of a stock
def getStockMajorHolders(stock):
    return (stock.getTicker().major_holders)

# Institutional holders of a stock
def getStockInstitutionalHolders(stock):
    return (stock.getTicker().institutional_holders)

# Balance sheet of a stock
def getStockBalanceSheet(stock):
    return (stock.getTicker().balance_sheet)

# Quartely Balance sheet of a stock
def getStockQuarterlyBalanceSheet(stock):
    return (stock.getTicker().quarterly_balance_sheet)

# Cashflow of a stock
def getStockCashFlow(stock):
    return (stock.getTicker().cashflow)

# Quarterly Cashflow of a stock
def getStockQuarterlyCashFlow(stock):
    return (stock.getTicker().quarterly_cashflow)

# Earnings of a stock
def getStockEarnings(stock):
    return (stock.getTicker().earnings)

# Quarterly Earnings of a stock
def getStockQuarterlyEarnings(stock):
    return (stock.getTicker().quarterly_earnings)

# Sustainability of a stock
def getStockSustainability(stock):
    return (stock.getTicker().sustainability)

# Analysts recommendations of a stock
def getStockAnalystsRecommendations(stock):
    return (stock.getTicker().recommendations)

# Next event (earnings, etc) of a stock
def getStockCalendar(stock):
    return (stock.getTicker().calendar)

# get ISIN code - *experimental* of a stock
# ISIN = International Securities Identification Number
def getStock_ISIN_code(stock):
    return (stock.getTicker().isin)

# get options expirations of a stock
def getStockOptions(stock):
    return (stock.getTicker().options)

''' 
                Print to the screen Functions
'''

# Version of the Yfinance
def versionYfinance():
    print('Yfinance = version = ' + yf.__version__)


''' Missing this one chapter '''
# get option chain for specific expiration
#opt = msft.option_chain('YYYY-MM-DD')
# data available via: opt.calls, opt.puts

# Menu options
def  showMenu():
    print("Menu")
    print("1 - Show stock info")
    print("2 - Show historical Market Data")
    print("3 - Show Actions (dividends, splits)")
    print("4 - Show dividends")
    print("5 - Show splits")
    print("6 - Show financials")
    print("7 - Show major holders")
    print("8 - Show Institutional holders")
    print("9 - Show balance sheet")
    print("10 - Show Cashflow")
    print("11 - Show earnings")
    print("12 - Show sustainability")
    print("13 - Show analysys recommendations")
    print("14 - Show next event (earnings, etc)")
    print("15 - Show ISIN code") 
    print("Option: ")

'''
                Handlers
'''

# Menu Handler
def menu():
    run = True
    while (run):
        showMenu()
        option = int(sys.stdin.readline())
        if (option == 0):
            run = False
            exit(0)
        elif (option == 1):
            print("Stock Info")
            print(getStockInfo(stocks[0]))
        elif (option == 2):
            print("Historical market data")
            print(getStockHistoricalMarketData(stocks[0]))
        elif (option == 3):
            print("Actions (Dividends, splits)")
            print(getStockActions(stocks[0]))
        elif (option == 4):
            print("Dividends")
            print(getStockDividends(stocks[0]))
        elif (option == 5):
            print("Splits")
            print(getStockSplits(stocks[0]))
        elif (option == 6):
            print("Financials")
            print(getStockFinancials(stocks[1]))
            print(getStockQuarterlyFinancials(stocks[2]))
        elif (option == 7):
            print("Major holders")
            print(getStockMajorHolders(stocks[0]))
        elif (option == 8):
            print("Institutional holders")
            print(getStockInstitutionalHolders(stocks[0]))
        elif (option == 9):
            print("Balance Sheet")
            print(getStockBalanceSheet(stocks[0]))
            print(getStockQuarterlyBalanceSheet(stocks[0]))
        elif (option == 10):
            print("Cashflow")
            print(getStockCashFlow(stocks[0]))
            print(getStockQuarterlyCashFlow(stocks[0]))
        elif (option == 11): 
            print("Earnings")
            print(getStockEarnings(stocks[0]))
            print(getStockQuarterlyEarnings(stocks[0]))
        elif (option == 12):
            print("Sustainability")
            print(getStockSustainability(stocks[0]))
        elif (option == 13):
            print("Analysys recommendations")    
            print(getStockAnalystsRecommendations(stocks[0]))
        elif (option == 14):
            print("Next event (earnings, etc)")
            print(getStockCalendar(stocks[0]))
        elif(option == 15):
            print("ISIS code")  
            print(getStock_ISIN_code(stocks[0]))
        else:
            print("Not a valid option!")
        time.sleep(5)

'''
                Variables
'''

# Global Variables
stocks = [] # Array of Object's Stock
symbolStock = fileReadSymbolStocks() # All Symbol Stocks read from the file
versionYfinance() # Function that prints the version that it's  operating

''' 
                MAIN LOGIC

'''

t = threading.Thread(target = creatingStocks, args = (symbolStock,)) #Thread for creating objects
t.daemon = True # Needed for when the program shut's down, the thread stops
t.start() #initializes the thread

menu() # initializes the menu