Beispiel #1
0
def research():
    Whattodo = input("Which stock are you interested? ")
    try:
        stock = yf.Ticker(Whattodo)
        information = stock.info
        print('Here is some basic info of the stock {}:'.format(
            information.get('longName')))
        print('Symbol: {}'.format(information.get('symbol')))
        print('industry: {}'.format(information.get('industry')))
        print('country: {}'.format(information.get('country')))
        print('state: {}'.format(information.get('state')))
        print('city: {}'.format(information.get('city')))
        print('phone:{}'.format(information.get('phone')))
        print('website:{}'.format(information.get('website')))
        print('address:{}'.format(information.get('address1')))
        print('market: {}'.format(information.get('market')))
        print("All data are from Yahoo finance\n")
        q1 = 9
        while q1 != 0:
            q1 = gf.getnumber(
                "Press 1 if you want the open and close prices of the company \nPress 2 if you want the long summary of the company \nPress 3 to show everything\nPress 0 to quit \n"
            )
            if q1 == 1:
                print('Open: {}'.format(information.get('open')))
                print('High: {}'.format(
                    information.get('regularMarketDayHigh')))
                print('Low: {}'.format(information.get('regularMarketDayLow')))
                print('Previous Close: {}'.format(
                    information.get('regularMarketPreviousClose')))
                print('50days average: {}'.format(
                    information.get('fiftyDayAverage')))
                print('52wk high: {}'.format(
                    information.get('fiftyTwoWeekHigh')))
                print('52wk low: {}'.format(
                    information.get('fiftyTwoWeekLow')))
                print('52wk change: {}'.format(
                    information.get('52WeekChange')))
                print('forwardPE: {}'.format(information.get('forwardPE')))
                print('Beta: {}'.format(information.get('beta')))
                print("BookValue: {}".format(information.get('bookValue')))
                print('Regular Market Volume: {}'.format(
                    information.get('regularMarketVolume')))
                print('Average Volume:{}\n'.format(
                    information.get('aveageVolume')))
            elif q1 == 2:
                print('Long business summary: {}\n'.format(
                    information.get('longBusinessSummary')))
            elif q1 == 3:
                for k, v in information.items():
                    print('{}: {}'.format(k, v))

    except IndexError:
        print("Sorry, can not access the data of {}".format(Whattodo))
Beispiel #2
0
def cal():
    current = generalfunction.getnumber("What is your current ap? ")
    difference_40 = 40 - float(current)
    difference_80 = 80 - float(current)
    difference_120 = 120 - float(current)
    timeneededminute_40 = difference_40 * 5
    timeneededminute_80 = difference_80 * 5
    timeneededminute_120 = difference_120 * 5
    now = datetime.datetime.now()
    timeofcompletion_40 = now + datetime.timedelta(hours=0, minutes=timeneededminute_40, seconds=0)
    timeofcompletion_80 = now + datetime.timedelta(hours=0, minutes=timeneededminute_80, seconds=0)
    timeofcompletion_120 = now + datetime.timedelta(hours=0, minutes=timeneededminute_120, seconds=0)
    print("Your ap will be replenish to 40 at " + str(timeofcompletion_40))
    print("Your ap will be replenish to 80 at " + str(timeofcompletion_80))
    print("Your ap will be replenish to 120 at " + str(timeofcompletion_120))
    timeofcompletiondat = open("timeofcompletion.dat","wb")
    pickle.dump(str(timeofcompletion_40),timeofcompletiondat)
    pickle.dump(str(timeofcompletion_80), timeofcompletiondat)
    pickle.dump(str(timeofcompletion_120), timeofcompletiondat)
    timeofcompletiondat.close()
Beispiel #3
0
def get_index():
    str = ''
    index = gf.getnumber(
        "Which index do you want to compare?\n1) S&P \n2) NASDAQ \n3) Dows Jones\n4) Hang Seng index\n5) Euronext 100\n6) S&P TSX ")
    if index == 1:
        str = '^GSPC'
    if index == 2:
        str = '^IXIC'
    if index == 3:
        str = '^DJI'
    #if index == 4:
        #str = '^SSEC'
    if index == 4:
        str = '^HSI'
    #if index == 6:
       # str = '^FTSE 100'
    if index == 5:
        str = '^N100'
    if index == 6:
        str = '^GSPTSE'
    return str
Beispiel #4
0
def main():
    yf.pdr_override()
    sp500 = pdr.get_data_yahoo('^GSPC', period=('30d'))
    print(sp500.tail())
    mpf.plot(sp500, type='line', title='S&P 500')
    action = 1
    while action != 0:
        print("What do you want to do today\n")
        action = gf.getnumber(
            "\npress 1 to search current and historic stock price \npress 2 to download data about a stock \npress 3 to view downloaded data \npress 4 to show the index\npress 5 to get tickers from an index \npress 6 to get all s&p 500 or nasdaq price data (WARNING: THIS WILL TAKE A WHILE)\npress 7 to show the correlation heatmap between stock (WARNING: THIS WILL TAKE A WHILE)\npress 8 to use the stock researcher \npress 9 to use the calculator \npress 0 to quit "
        )
        #if action == 1:
        #Whattofind = input("What you want to find? ")
        #specificCellletter = (find_specific_cell(Whattofind))
        #value = get_role_value(specificCellletter)
        #newvalue = input("What the new value? ")
        #currentSheet['C' + str(value)] = float(newvalue)
        #theFile.save('stock portfolio.xlsx')
        #print("The stock " + Whattofind + " value has changed to " +newvalue)
        #elif action == 2:
        #Whattofind = input("What you want to find? ")
        #specificCellletter = (find_specific_cell(Whattofind))
        #value = get_role_value(specificCellletter)
        #price = currentSheet['C' + str(value)].value
        #print("\nThe value of the stock "+ Whattofind +" is "+ str(price) +"\n")

        if action == 1:  #A function to show stock price by asking the user to input the stock symbol, also provide the user the ability to choose the time period
            Whattofind = input("Which stock price are you interested? ")
            whattofindprice = yf.Ticker(Whattofind)
            pricehistory = whattofindprice.history(period="10d")
            print("The price of " + Whattofind + " for the last 10 days is\n" +
                  str(pricehistory))
            try:
                mpf.plot(pricehistory,
                         type='candle',
                         volume=True,
                         title=str(Whattofind),
                         ylabel='OHLC Candles',
                         ylabel_lower='Volume',
                         style='charles')
            except:
                print()
            option = input("Would you want more data? y/n")
            while option == "y":
                period = gf.getnumber("How many days of data do you want? ")
                pricehistory = whattofindprice.history(period=(str(period) +
                                                               "d"))
                print("The price of " + Whattofind + " is\n" +
                      str(pricehistory))
                mpf.plot(pricehistory,
                         type='candle',
                         volume=True,
                         title=str(Whattofind),
                         ylabel='OHLC Candles',
                         ylabel_lower='Volume',
                         style='charles')
                option = input("Would you want more data? y/n")

        elif action == 2:  #A function allows the user to download stock data by asking the user to input the stock symbol and the start and end date then save the data into a csv file
            yes = 0
            if not os.path.exists('history/downloadhistory.dat'):
                Whattofind = input(
                    "Which stock/stocks price are you interested? (You can enter one or more stocks just separate the stock symbol with space)"
                )
                startdate = input("Startdate (format: YYYY/MM/DD): ")
                enddate = input("Enddate (format: YYYY/MM/DD): ")
                lastdownload = open('history/downloadhistory.dat', 'wb')
                pickle.dump(str(Whattofind), lastdownload)
                pickle.dump(startdate, lastdownload)
                pickle.dump(enddate, lastdownload)
                lastdownload.close()
            else:
                lastdownload = open('history/downloadhistory.dat', 'rb')
                history = pickle.load(lastdownload)
                hisstart = pickle.load(lastdownload)
                hisend = pickle.load(lastdownload)
                print(
                    "You have previously download data of '{}', would you like to download it again?"
                    .format(history))
                choice = input("y/n\n")
                if choice == 'y':
                    question = input(
                        "Would you like to download the same period? if yes please press 1, if you would like to update your data to today press 2, if you would like to update your data to 60days press 3, if you would like to download the data of specific time period press enter."
                    )
                    Whattofind = history
                    if question == '1':
                        startdate = hisstart
                        enddate = hisend
                    elif question == "2":
                        startdate = hisstart
                        enddate = dt.date.today()
                        enddate = enddate + dt.timedelta(days=1)
                        lastdownload = open('history/downloadhistory.dat',
                                            'wb')
                        pickle.dump(str(Whattofind), lastdownload)
                        pickle.dump(startdate, lastdownload)
                        pickle.dump(enddate, lastdownload)
                        lastdownload.close()
                    elif question == '3':
                        yes = 1
                        pass
                    else:
                        startdate = input("Startdate (format: YYYY/MM/DD): ")
                        enddate = input("Enddate (format: YYYY/MM/DD): ")
                        lastdownload = open('history/downloadhistory.dat',
                                            'wb')
                        pickle.dump(str(Whattofind), lastdownload)
                        pickle.dump(startdate, lastdownload)
                        pickle.dump(enddate, lastdownload)
                        lastdownload.close()
                else:
                    Whattofind = input(
                        "Which stock/stocks price are you interested? (You can enter one or more stocks just separate the stock symbol with space)"
                    )
                    CHOICE = input(
                        "The default option for this download is 60 day period, do you want to proceed?(y/n)"
                    )
                    if CHOICE.lower() == 'y':
                        startdate = "0000/00/00"
                        enddate = "0000/00/00"
                        lastdownload = open('history/downloadhistory.dat',
                                            'wb')
                        pickle.dump(str(Whattofind), lastdownload)
                        pickle.dump(startdate, lastdownload)
                        pickle.dump(enddate, lastdownload)
                        lastdownload.close()
                        yes = 1
                    if CHOICE.lower() == 'n':
                        startdate = input("Startdate (format: YYYY/MM/DD): ")
                        enddate = input("Enddate (format: YYYY/MM/DD): ")
                        lastdownload = open('history/downloadhistory.dat',
                                            'wb')
                        pickle.dump(str(Whattofind), lastdownload)
                        pickle.dump(startdate, lastdownload)
                        pickle.dump(enddate, lastdownload)
                        lastdownload.close()
                # the following three try functions are use to change the date from string to dt type and also choosing which mode to download, the 60 days or the custom date
            try:
                startdate = gf.changestringtodate(startdate)
            except:
                pass
            try:
                enddate = gf.changestringtodate(enddate)
                enddate = enddate + dt.timedelta(days=1)
            except:
                pass
            if yes == 0:
                data = yf.download(
                    str(Whattofind), start=startdate,
                    end=enddate).to_csv(str(Whattofind) + ".csv")
            elif yes == 1:
                data = yf.download(
                    str(Whattofind),
                    period="60d").to_csv(str(Whattofind) + ".csv")
            print("The data have been saved in the directory " +
                  str(os.getcwd()))

        elif action == 3:  #A function to allow user to open csv files
            print(
                "Which csv do you want to open? (Please type the full name): ")
            currentpathnote = os.getcwd()
            os.chdir(str(currentpathnote))
            for file in glob.glob("*.csv"):
                print(file)
            filename = input("")
            try:
                df = pd.read_csv(filename,
                                 header=0,
                                 index_col='Date',
                                 parse_dates=True)
                print(df)
            except ValueError:
                df = pd.read_csv(filename, skiprows=1)
                print(df)

        elif action == 4:  #A function allows the user to search up s&p 500 index history
            choice = 0
            stockidx = financeplayground.get_index()
            sp500 = pdr.get_data_yahoo(stockidx, period=('60d'))
            print(sp500.tail())
            mpf.plot(sp500, type='line', title=stockidx)
            choice = gf.getnumber(
                "What would you like to do?\nPress 1 to show the candle plot\nPress 2 to download data\n"
            )
            if choice == 1:
                mpf.plot(sp500, type='candle', title=stockidx, style='charles')
            if choice == 2:
                lastdownload = open('history/downloadhistory.dat', 'rb')
                history = pickle.load(lastdownload)
                hisstart = pickle.load(lastdownload)
                hisend = pickle.load(lastdownload)
                startdate = gf.changestringtodate(hisstart)
                enddate = gf.changestringtodate(hisend)
                enddate = enddate + dt.timedelta(days=1)
                data = yf.download(str(stockidx), start=startdate,
                                   end=enddate).to_csv(str(stockidx) + ".csv")

        elif action == 5:  #get tickers
            action = gf.getnumber(
                "Which ticket do you want to get?\ns&p press 1\nnasdaq press 2"
            )
            if action == 1:
                financeplayground.save_tickers(
                    'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies',
                    'sp500tickers.pickle', 0)
                with open("ticker/sp500tickers.pickle", "rb") as f:
                    tickers = pickle.load(f)
                    print(tickers)
            if action == 2:
                financeplayground.save_tickers(
                    'https://en.wikipedia.org/wiki/NASDAQ-100',
                    'nasdaqtickers.pickle', 1)
                with open("ticker/nasdaqtickers.pickle", "rb") as f:
                    tickers = pickle.load(f)
                    print(tickers)

        elif action == 6:  #download s&p 500 data and automatically compile them into a separate file contain all the adjusted close
            action = gf.getnumber(
                "Which data do you wanna get?\ns&p press 1\nnasdaq press 2\nget all press 3 "
            )
            if action == 1:
                update.updatesp()
            if action == 2:
                update.updatenasdaq()
            if action == 3:
                update.updateall()

        elif action == 7:
            action = gf.getnumber('s&p 500 press 1\nnasdaq press 2 ')
            if action == 1:
                if not os.path.exists(
                        'joined_closed/sp500tickers.pickle_joined_closed.csv'):
                    financeplayground.compile_data('sp500tickers.pickle',
                                                   'stocks_dfs')
                financeplayground.visualize_data(
                    'sp500tickers.pickle_joined_closed.csv')
            if action == 2:
                if not os.path.exists(
                        'joined_closed/nasdaqtickers.pickle_joined_closed.csv'
                ):
                    financeplayground.compile_data('nasdaqtickers.pickle',
                                                   'stocks_nasdaq')
                financeplayground.visualize_data(
                    'nasdaqtickers.pickle_joined_closed.csv')

        elif action == 8:  ## Research stocks
            researcher.research()

        elif action == 9:  #A function that allow the user to use the calculator
            calc = ""
            while calc != 'exit':
                calc = input("Type Calculation (type exit to exit): \n")
                print("Answer: " + str(eval(calc)))
while chkpromot(promot) != 999:
    print(promot)
    if chkpromot(promot) == 2:
        DT = dt.datetime.now()
        currenttime = "It is " + DT.strftime("%H:%M:%S") + " now"
        print(currenttime)

    elif chkpromot(promot) == 1:
        stocks.main()

    elif chkpromot(promot) == 3:
        print(
            "If you like to calculate ap press 1\nIf you like to view your history press 2\n"
        )
        choice = generalfunction.getnumber("")
        while choice != 1 and choice != 2:
            print("Please input a valid option!")
            choice = generalfunction.getnumber("")
        if choice == 1:
            apcalculator.cal()
        elif choice == 2:
            apcalculator.showhistory()

    elif chkpromot(promot) == 4:
        print("Which notebook do you want to open?")
        originalpathnote = os.getcwd()
        currentpathnote = os.getcwd() + "/note"
        os.chdir(str(currentpathnote))
        for file in glob.glob("*.txt"):
            print(file)