Python:Trying to create a loop that scan stock list and return gappers

Viewed 312

I have a allstock .CSV file with list of stocks(only ticker symbol) I want to create another .CSV with ONLY the stocks that gapped more than 20% from previous day+ their daily data . I am trying to create a loop but I’m not even sure where to begin. I know how to return the daily data (high , low, open, close , volume) for each name but can’t do a loop that does that AND create a .CSV of only the gappers+data.

I checked the .loc command and try to integrate it but I am not sure about the right structure.

Any advice that can put me in the right direction is appreciated. If anyone can share a code to do that it’s obviously amazing. Or just bread crumbs. Anything. Really.

Thanks in advance

Edit: I’m adding a simplified version as requested of what I’m trying to do. (Apologize on the mess I’m editing it on my phone)

import pandas as pd 

flag='no gap' 
data=[['Monday',3,3,2,flag],['Tuesday',2,2,1,flag],['Wednsday',2,3,2,flag]] 
df=pd.DataFrame(data,columns=['day','previous close','open','close','gap'])

for df[flag] in df:
   if df['open']>df['previous close']: 
       df[flag]='gap' 
1 Answers

You were pretty close with your attempt and your guess that .loc is the appropriate function:

import pandas as pd 

flag='no gap' 
data=[['Monday',3,3,2,flag],['Tuesday',2,2,1,flag],['Wednsday',2,3,2,flag]] 
df=pd.DataFrame(data,columns=['day','previous close','open','close','gap'])

df.loc[df.open > df["previous close"]]

Output

        day  previous close  open  close     gap
2  Wednsday               2     3      2  no gap

You can then write that to a csv:

df.loc[df.open > df["previous close"]].to_csv(...)`
Related