Search code examples
pythonfor-loopgoogle-sheetsyahoo-finance

How to increment a variable within a for loop in python


Im building a google sheet to keep track of stock prices for the stocks i own. I have an API running thats connected to Google Sheets and my own python application.

My google sheet looks like this

Stock | Previous close

AAPL  | 316.73

NVDA  | 348.71

SPOT  | 191.00

i currently have the code running as follows.

import requests 
import gspread
from oauth2client.service_account import ServiceAccountCredentials 

sheet = client.open("Stock").sheet1
AAPL = sheet.cell(2,1).value
url = ('https://ca.finance.yahoo.com/quote/'+AAPL+'?p='+AAPL+'&.tsrc=fin-srch')
response = requests.get(url) 
htmltext = response.text
splitlist = htmltext.split("Previous Close")
afterfirstsplit =splitlist[1].split("\">")[2]
aftersecondsplit = afterfirstsplit.split("</span>")
datavalue = aftersecondsplit[0] 
sheet.update_cell(2,2,datavalue) 

# this would update the value within my google sheet to the previous close price

For each individual stock, i would copy and paste, change the stock symbol, to find the value of the next quote. I know theres a way to use FOR statements to automate this process. I tried that with the following but it wouldnt update as needed. I reached a wall at this point and would appreciate any help or insight on how i could automate this function.

tickers = {sheet.cell(2,1).value : [],
           sheet.cell(3,1).value : [],
           sheet.cell(4,1).value : [], 
           sheet.cell(5,1).value :[]}

for symbols in tickers: 

    url = ('https://ca.finance.yahoo.com/quote/'+symbols+'?p='+symbols+'&.tsrc=fin-srch')
    response = requests.get(url) 
    htmltext = response.text
    splitlist = htmltext.split("Previous Close")
    afterfirstsplit =splitlist[1].split("\">")[2]
    aftersecondsplit = afterfirstsplit.split("</span>")
    datavalue = aftersecondsplit[0]
    sheet.update.cell(2,1,datavalue)
    print (datavalue)

Doing this gathers all the values of the current stock prices and it does import it into the excel file but only to one coordinate. I dont know how to increase the '1' within sheet.update.cell(2,1,datavalue), each time within the FOR statement. I believe that is the way to solve this, but if anyone has any other suggestions, im all ears.


Solution

  • In regards to answering this part of your question:

    "I don't know how to increase the '1' within sheet.update.cell(2,1,datavalue), each time within the FOR statement."

    This is how you increment a counter inside a for loop typically speaking:

    counter = 1
    
    for symbol in tickers:
        #Your code
        sheet.update.cell(2,counter,datavalue)
        counter = counter+1