TransWikia.com

How to keep a separate count for each item in a list, inside a loop which satisfies an if statement

Stack Overflow Asked by Enthusiast on January 21, 2021

I want to be able to run the following program in a while loop and keep a separate count for each stock ticker that matches the if statement.

However, when I run the following program, it prints the count but not a separate count, it just adds all of them together.

stocklist=["COUP","DOCU", "AAPL", "FB", "NVDA", "TTD", "CVNA", "W", "TDOC", "AMZN"]

qqqpc=1
count = 0
for i in stocklist:
    
    iex_price = pdr.get_data_yahoo(i, period="2d")

    currentclose=round(iex_price['Adj Close'][-1],2)
    previousclose=round(iex_price['Adj Close'][-2],2)
    pc=round((currentclose-previousclose)/(previousclose)*100,2)

    if(pc>qqqpc):
        count+=1
        print(str(count)+" For "+str(i))
        print(str(i)+" Percent Change is greater than QQQ at "+ str(pc))

2 Answers

Instead of a single count variable, you need one for each stock.

The easiest way to achieve this in Python is to use a Counter. It will automatically initialize each entry with 0 as soon as it is accessed for the first time.

Then you can simply replace all occurrences of the count variable by count[i]:

from collections import Counter

stocklist = ["COUP", "DOCU", "AAPL", "FB", "NVDA", "TTD", "CVNA", "W", "TDOC", "AMZN"]

qqqpc = 1
count = Counter()

for i in stocklist:
    iex_price = pdr.get_data_yahoo(i, period="2d")

    currentclose = round(iex_price['Adj Close'][-1], 2)
    previousclose = round(iex_price['Adj Close'][-2], 2)
    pc = round((currentclose - previousclose) / previousclose * 100, 2)

    if(pc > qqqpc):
        count[i] += 1
        print(str(count[i]) + " For " + str(i))
        print(str(i) + " Percent Change is greater than QQQ at " + str(pc))

Correct answer by mkrieger1 on January 21, 2021

You can use a dictionary to store the count for each stock:

import time
stocklist=["COUP","DOCU", "AAPL", "FB", "NVDA", "TTD", "CVNA", "W", "TDOC", "AMZN"]

stockcnts = {}
for s in stocklist: stockcnts[s]=0

qqqpc=1

While True:
    for i in stocklist:
        
        iex_price = pdr.get_data_yahoo(i, period="2d")

        currentclose=round(iex_price['Adj Close'][-1],2)
        previousclose=round(iex_price['Adj Close'][-2],2)
        pc=round((currentclose-previousclose)/(previousclose)*100,2)

        if(pc>qqqpc):
            stockcnts[i]+=1
            print(str(stockcnts[i])+" For "+str(i))
            print(str(i)+" Percent Change is greater than QQQ at "+ str(pc))
    time.sleep(2)  # 2 seconds

Answered by Mike67 on January 21, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP