Search code examples
pythonfinanceyahoo-finance

Ive only started coding in python for about a month. Can I overwrite previously parsed data? Question continued in the body


I wrote a function that would gather information on a particular stock after parsing it from yahoo finance. Now at the end of the function, I would leave the user the option to search another quote or go back to the homepage. When the user clicks this option, the program crashes, saying the arrays must all be the same length. I assume since the data that was gathered from the previous quote was already registered within the function, and wont allow the user to overwrite and parse. How would i fix this problem? Please advise.

import random
import requests
import numpy as np
import pandas as pd 

def tickersymbol():
    tickersymbol = input("What company would you like information on?") 
    url = ('https://ca.finance.yahoo.com/quote/'+tickersymbol+'?p='+tickersymbol+'&.tsrc=fin-srch')
    response = requests.get(url) 
    htmltext = response.text

    for indicator in Indicators :

        splitlist = htmltext.split(indicator)
        afterfirstsplit =splitlist[1].split("\">")[2]
        aftersecondsplit = afterfirstsplit.split("</span>")
        datavalue = aftersecondsplit[0]
        Indicators[indicator].append(datavalue)

    for values in Misc:
        splitlist = htmltext.split(values)
        afterfirstsplit =splitlist[1].split("\">")[1]
        aftersecondsplit = afterfirstsplit.split("</td>")
        netset = aftersecondsplit[0]
        Misc[values].append(netset)

    Indicators.update(Misc)
    df = pd.DataFrame(Indicators)
    array = np.transpose(df)
    print(array)

    task = input('''
                 Would you like to continue? 

                 [1] : Yes, Look at another Symbol     ##Here is where the problem starts. 
                 [2] : No, Go back to main 

                   ''')

    if task == "1":
        return tickersymbol()
    elif task == "2":
        return main()
    else:
        print("Try to answer that one again")

Indicators =

{"Previous Close" : [], "Open" : [], "Bid" : [] , "Ask": [], 'Volume': [], 'Avg. Volume': [], 'Market Cap': [], 'Beta': [], 'PE Ratio (TTM)': [], 'EPS (TTM)': [], 'Earnings Date': [], 'Ex-Dividend Date': [], '1y Target Est' : []}

Misc =

{'52 Week Range' :[], "Day's Range": [], 'Dividend & Yield' : []}


Solution

  • Issue found with software was line:

    tickersymbol = input("What company would you like information on?") 
    

    Since this is the same as the function name, this causes an error when you try to call the function again i.e.

    return tickersymbol()
    

    Remedy, change line to:

    tickersymbol_ = input("What company would you like information on?") 
    url = ('https://ca.finance.yahoo.com/quote/'+tickersymbol_+'?p='+tickersymbol_+'&.tsrc=fin-srch')
    

    Other Revisions

    1. error checking -- use try/except block

    2. control flow--use while loop rather than function calling itself

    3. indicator and misc--inside function so they are reset for each stock processed

    4. main calls tickersymbol, which returns to it upon completion

    Revised Code

    import random
    import requests
    import numpy as np
    import pandas as pd 
    
    def main():
      tickersymbol()
    
    def tickersymbol():
        while True:
          skip = False
    
          tickersymbol_ = input("What company would you like information on?") 
          url = ('https://ca.finance.yahoo.com/quote/'+tickersymbol_+'?p='+tickersymbol_+'&.tsrc=fin-srch')
          response = requests.get(url) 
          htmltext = response.text
    
          # Reset Indicator and Misc
          Indicators = {"Previous Close" : [], "Open" : [], "Bid" : [] , "Ask": [], 'Volume': [], 'Avg. Volume': [], 'Market Cap': [], 'Beta': [], 'PE Ratio (TTM)': [], 'EPS (TTM)': [], 'Earnings Date': [], 'Ex-Dividend Date': [], '1y Target Est' : []} 
    
          Misc = {'52 Week Range' :[], "Day&#x27;s Range": [], 'Dividend &amp; Yield' : []} 
    
          for indicator in Indicators :
              try:
                splitlist = htmltext.split(indicator)
                afterfirstsplit =splitlist[1].split("\">")[2]
                aftersecondsplit = afterfirstsplit.split("</span>")
                datavalue = aftersecondsplit[0]
                Indicators[indicator].append(datavalue)
              except:
                print('Error with stock')
                skip = True
                break
    
          if skip:
            continue     # continues with the outer while loop
    
          for values in Misc:
              try:
                splitlist = htmltext.split(values)
                afterfirstsplit =splitlist[1].split("\">")[1]
                aftersecondsplit = afterfirstsplit.split("</td>")
                netset = aftersecondsplit[0]
                Misc[values].append(netset)
              except:
                print('Error with stock')
                skip = True
                break
    
          if skip:
            continue    # continues with outer while loop
    
          Indicators.update(Misc)
          df = pd.DataFrame(Indicators)
          array = np.transpose(df)
          print(array)
    
          task = input('''
                      Would you like to continue? 
    
                      [1] : Yes, Look at another Symbol     ##Here is where the problem starts. 
                      [2] : No, Go back to main 
    
                        ''')
    
          if task == "1":
              continue    # continues with outer while loop
          elif task == "2":
              return      # done with tickersymbol function
          else:
              print("Try to answer that one again")
    
    if __name__ == "__main__":
        main()