How to calculate a condition for all stocks in a list

Hello.

I’m trying to develop my Python script but I’m really a rookie and I cannot find the solution.

I have a list of stocks (listatitoli), I create the csv files, I calculate if the max of today is higher than the previous 11 days (thank for your help), and now I need to establish for which stock of the list (listatitoli) this condition is valid and Python must write the code of every stock that satisfy the condition in a csv file named overmax12gg.csv

Following my script:

``````listatitoli = ["A2A.MI", "ABT.MI", "ACE.MI", "AC5.MI", "AEF.MI", "ADB.MI", "ARN.MI", "ALW.MI", "ALK.MI", "AMP.MI", "ANIM.MI", "AV.MI"]

#Elimino tutti i file presenti nella cartella upovermax10gg
files = glob.glob('/Users/fabry/upovermax12gg/*')
for f in files:
os.remove(f)

#Per ogni titolo della lista titoli scarico i dati di ieri e creo un file .csv per ogni titolo
for stock in listatitoli:
df = pd.DataFrame(stock_data)
df.to_csv(stock + ".csv", index=False)

#Sposto i file .csv nella cartella CSV titoli
src = r"/Users/fabry/"
dest = r"/Users/fabry/upovermax12gg"
os.chdir(src)
for files in glob.glob("*.csv"):
shutil.move(files, dest)

#Inizio analisi titoli

max_values_11_days = []

# Faccio l'append dei primi 11 max dalla colonna High
for row in range(len(df) - 1):

max_values_11_days.append(df.iat[row, 1])

maxdi11gg = max(max_values_11_days)
maxdodicesimogg = df.iat[11, 1]

for stock in listatitoli:
if maxdodicesimogg>maxdi11gg:
OM = open('/Users/fabry/upovermax12gg/overmax12gg.csv', "w")
OM.write("here must be written the stock code \n")
OM.close()
``````

I’m studying very hard but I cannot understand how to solve the problem.
Thank you in advance for any suggestion,
Fabrizio

Hi,

you can try something like this:

``````from pathlib import Path
overmax12gg_path = Path('/Users/fabry/upovermax12gg/overmax12gg.csv')

for stock in listatitoli:

df = pd.DataFrame(stock_data)
df.to_csv(stock + ".csv", index=False)

max_values_11_days = []

# Faccio l'append dei primi 11 max dalla colonna High
for row in range(len(df) - 1):
max_values_11_days.append(df.iat[row, 1])

maxdi11gg = max(max_values_11_days)
maxdodicesimogg = df.iat[11, 1]

if maxdodicesimogg > maxdi11gg:
# Use the 'a' for append.  Using 'w' will overwrite the current contents
with open(overmax12gg_path, 'a', encoding='UTF-8') as OM:
OM.write("here must be written the stock code \n")
``````

Note that using the `with open` form for opening files is preferred since the file is automatically closed regardless if there is an error during processing. You don’t need to tell it to close explicitly.

Since you’re processing every stock via the `for stock in listatitoli` conditional statement, it makes sense to do the comparison as well as the writing to the file after every comparison here. Note that we make use of the ‘prefix’ `a` instead of the `w` because using the `w` will overwrite the existing content. Using the `a` prefix appends the data.

Note that we have also predefined the file path at the beginning using the package module `pathlib` and importing its `Path` class for storing the file path .

Hi. Thank you very much for your suggestions. I wrote the path:

``````with open(overmax12gg_"/Users/fabry/upovermax12gg/overmax12gg.csv", 'a', encoding='UTF-8') as OM:
``````

but I don’t understand what I must write here:

``````OM.write("here must be written the stock code \n")
``````

instead of “here must be written…”

I need that in the csv file must be present all the stocks’ codes that satisfy the condition.

Thank you!

This is your original file name and location.

The following two lines take care of that.

``````overmax12gg_path = Path('/Users/fabry/upovermax12gg/overmax12gg.csv')

with open(overmax12gg_path, 'a', encoding='UTF-8') as OM:
``````

Don’t modify it. If you wish to change the file name and / or path, make the edits to the first line only.

Its your script, what do you want written there? Here are your options (not all inclusive):

1. maxdodicesimogg
2. maxdi11gg
3. df
4. A combination of these

Don’t be afraid to experiment. Test what you want written. Before writing the values to the file, print out the variable(s). Determine if the value that is printed is what you want written to your .csv file.

Hi.
No, I’m not able… I really don’t understand how to print/copy all the name of the stocks that satisfy the condition 12th max is max than the 11 previous.

``````

listatitoli = ["A2A.MI", "ABT.MI", "ACE.MI", "AC5.MI", "AEF.MI", "ADB.MI", "ARN.MI", "ALW.MI", "ALK.MI", "AMP.MI", "ANIM.MI", "AV.MI", "ECNL.MI", "ARIS.MI", "ASC.MI", "AVIO.MI", "AZM.MI", "BEC.MI", "BFG.MI", "BGN.MI", "IF.MI", "BMED.MI", "BMPS.MI", "PRO.MI", "BST.MI", "BAMI.MI", "BAN.MI", "B.MI", "BDB.MI", "BWZ.MI", "BE.MI", "BES.MI", "BFF.MI", "BIA.MI", "BSS.MI", "BIE.MI", "BO.MI", "BPSO.MI", "BPE.MI", "BRE.MI", "BRI.MI", "BC.MI", "BZU.MI", "CAI.MI", "CLF.MI", "CALT.MI", "CPR.MI", "CRL.MI", "CELL.MI", "CMB.MI", "CEM.MI", "CLI.MI", "CIR.MI", "CLE.MI", "COM.MI", "CNF.MI", "CE.MI", "CSP.MI", "CY4.MI", "DIS.MI", "DAN.MI", "DAL.MI", "DLG.MI", "DIA.MI", "DGV.MI", "DIB.MI", "DOV.MI", "EDNR.MI", "ELN.MI", "ELC.MI", "EM.MI", "ENAV.MI", "ENEL.MI", "ENV.MI", "ENI.MI", "EQUI.MI", "ERG.MI", "PRT.MI", "EUK.MI", "ECMPM.MI", "EGLA.MI", "ETH.MI", "XPR.MI", "RACE.MI", "YACHT.MI", "FDA.MI", "FM.MI", "FILA.MI", "FCT.MI", "FF.MI", "FBK.MI", "FNM.MI", "GAB.MI", "GHC.MI", "GSP.MI", "GE.MI", "GF.MI", "G.MI", "GEO.MI", "GG.MI", "GPI.MI", "GVS.MI", "HER.MI", "IGV.MI", "IGD.MI", "ILTY.MI", "IMS.MI", "DNR.MI", "INDB.MI", "ICOS.MI", "IP.MI", "ISP.MI", "INW.MI", "IRC.MI", "IRE.MI", "IEG.MI", "ITW.MI", "IG.MI", "IDB.MI", "ITM.MI", "IVG.MI", "KME.MI", "LNDR.MI", "LDO.MI", "LTMC.MI", "LUVE.MI", "LVEN.MI", "MAIRE.MI", "MAPS.MI", "MARR.MI", "MB.MI", "MFEA.MI", "MIT.MI", "MONC.MI", "MN.MI", "MTV.MI", "MOL.MI", "NDT.MI", "NWL.MI", "NEXI.MI", "NR.MI", "OLI.MI", "OJM.MI", "ORS.MI", "OVS.MI", "PHN.MI", "PHIL.MI", "PIA.MI", "PINF.MI", "PVN.MI", "PQ.MI", "PIRC.MI", "PLC.MI", "PST.MI", "PRY.MI", "RWAY.MI", "RAT.MI", "RCS.MI", "REC.MI", "REY.MI", "REVO.MI", "SAB.MI", "SG.MI", "SFL.MI", "SPM.MI", "SFER.MI", "SL.MI", "IOT.MI", "SERI.MI", "SRI.MI", "SES.MI", "SIT.MI", "SRG.MI", "SFT.MI", "SGF.MI", "SOL.MI", "SOM.MI", "STLAM.MI", "STMMI.MI", "TIP.MI", "TGYM.MI", "TPRO.MI", "TIT.MI", "TEN.MI", "TRN.MI", "TES.MI", "TSL.MI", "TISG.MI", "TNXT.MI", "TYA.MI", "TB.MI", "TXT.MI", "UCG.MI", "UD.MI", "UNIR.MI", "UNI.MI", "VLS.MI", "VIA.MI", "ZUC.MI", "WBD.MI", "WIIT.MI", "ZV.MI"]

#Elimino tutti i file presenti nella cartella upovermax10gg
files = glob.glob('/Users/fabry/upovermax12gg/*')
for f in files:
os.remove(f)

#Per ogni titolo della lista titoli scarico i dati di ieri e creo un file .csv per ogni titolo
for stock in listatitoli:
df = pd.DataFrame(stock_data)
df.to_csv(stock + ".csv", index=False)

#Sposto i file .csv nella cartella CSV titoli
src = r"/Users/fabry/"
dest = r"/Users/fabry/upovermax12gg"
os.chdir(src)
for files in glob.glob("*.csv"):
shutil.move(files, dest)

#Inizio analisi titoli

max_values_11_days = []

# Faccio l'append dei primi 11 max dalla colonna High
for row in range(len(df) - 1):

max_values_11_days.append(df.iat[row, 1])

maxdi11gg = max(max_values_11_days)
maxdodicesimogg = df.iat[11, 1]

#Stabilisco per ogni titolo se il max di oggi supera quello degli ultimi 11gg
if maxdodicesimogg > maxdi11gg:

``````

if if if…how can I say “if the max of the 12th day is higher that the previous 11, write in the csv file?” And this condition for every stock.

I’m not able to say “do it for all the stocks”.

Do I have to use df?

Thank you

I’ve tried again and I have this error:

`````` File "<ipython-input-104-cdbe1fdeeb6a>", line 57
with open(overmax12gg_"/Users/fabry/upovermax12gg/overmax12gg.csv", 'a', encoding='UTF-8') as OM:
^
SyntaxError: invalid syntax
``````

From previous reply, this is the correct way (also had stated not to change … review previous post)

``````overmax12gg_path = Path('/Users/fabry/upovermax12gg/overmax12gg.csv')

with open(overmax12gg_path, 'a', encoding='UTF-8') as OM:
``````

Why are you changing the filename inside the `with open` statement with this: ?

This is why you are getting your error.

Ok, sorry for the mistake, I understood and now I have:

``````overmax12gg_path = Path('/Users/fabry/upovermax12gg/overmax12gg.csv')

#Stabilisco per ogni titolo se il max di oggi supera quello degli ultimi 11gg
if maxdodicesimogg > maxdi11gg:
with open(overmax12gg_path, 'a', encoding='UTF-8') as OM:
``````

But now I really don’t know how to continue? How can I say: “ok, write in the csv file the stocks that satisfy the condition (today High price is higher than the last 11)”?

Thank you!

I already told you in a previous post - from this one. Read it carefully.

Share Post #2 Jul 10, 11:26 AM

Right under this line of code, you can add/append the results for every stock:

``````if maxdodicesimogg > maxdi11gg:
``````

This should work because you should already be iterating through every stock via the top
`for` conditional statement:

``````for stock in listatitoli:
``````

Could you supply the complete source code that you are running? I’m not sure what the `yf` module is since there’s no import statement for it. The cause of the problem could be in some code that you aren’t sharing. Also, is there an error message that you are getting? Or does the csv file not seem to have the output you expect? (And if not, what output is there instead?)

(post deleted by author)

Hi. Following the source code:

``````#importo tutte le librerie di cui necessito
import csv
from datetime import datetime, timedelta
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import shutil
import yfinance as yf
import os
import os.path
import glob
import smtplib, ssl
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from pandas_datareader import data as web

listatitoli = ["A2A.MI", "ABT.MI", "ACE.MI", "AC5.MI", "AEF.MI", "ADB.MI", "ARN.MI", "ALW.MI", "ALK.MI", "AMP.MI", "ANIM.MI", "AV.MI", "ECNL.MI", "ARIS.MI", "ASC.MI", "AVIO.MI", "AZM.MI", "BEC.MI", "BFG.MI", "BGN.MI", "IF.MI", "BMED.MI", "BMPS.MI", "PRO.MI", "BST.MI", "BAMI.MI", "BAN.MI", "B.MI", "BDB.MI", "BWZ.MI", "BE.MI", "BES.MI", "BFF.MI", "BIA.MI", "BSS.MI", "BIE.MI", "BO.MI", "BPSO.MI", "BPE.MI", "BRE.MI", "BRI.MI", "BC.MI", "BZU.MI", "CAI.MI", "CLF.MI", "CALT.MI", "CPR.MI", "CRL.MI", "CELL.MI", "CMB.MI", "CEM.MI", "CLI.MI", "CIR.MI", "CLE.MI", "COM.MI", "CNF.MI", "CE.MI", "CSP.MI", "CY4.MI", "DIS.MI", "DAN.MI", "DAL.MI", "DLG.MI", "DIA.MI", "DGV.MI", "DIB.MI", "DOV.MI", "EDNR.MI", "ELN.MI", "ELC.MI", "EM.MI", "ENAV.MI", "ENEL.MI", "ENV.MI", "ENI.MI", "EQUI.MI", "ERG.MI", "PRT.MI", "EUK.MI", "ECMPM.MI", "EGLA.MI", "ETH.MI", "XPR.MI", "RACE.MI", "YACHT.MI", "FDA.MI", "FM.MI", "FILA.MI", "FCT.MI", "FF.MI", "FBK.MI", "FNM.MI", "GAB.MI", "GHC.MI", "GSP.MI", "GE.MI", "GF.MI", "G.MI", "GEO.MI", "GG.MI", "GPI.MI", "GVS.MI", "HER.MI", "IGV.MI", "IGD.MI", "ILTY.MI", "IMS.MI", "DNR.MI", "INDB.MI", "ICOS.MI", "IP.MI", "ISP.MI", "INW.MI", "IRC.MI", "IRE.MI", "IEG.MI", "ITW.MI", "IG.MI", "IDB.MI", "ITM.MI", "IVG.MI", "KME.MI", "LNDR.MI", "LDO.MI", "LTMC.MI", "LUVE.MI", "LVEN.MI", "MAIRE.MI", "MAPS.MI", "MARR.MI", "MB.MI", "MFEA.MI", "MIT.MI", "MONC.MI", "MN.MI", "MTV.MI", "MOL.MI", "NDT.MI", "NWL.MI", "NEXI.MI", "NR.MI", "OLI.MI", "OJM.MI", "ORS.MI", "OVS.MI", "PHN.MI", "PHIL.MI", "PIA.MI", "PINF.MI", "PVN.MI", "PQ.MI", "PIRC.MI", "PLC.MI", "PST.MI", "PRY.MI", "RWAY.MI", "RAT.MI", "RCS.MI", "REC.MI", "REY.MI", "REVO.MI", "SAB.MI", "SG.MI", "SFL.MI", "SPM.MI", "SFER.MI", "SL.MI", "IOT.MI", "SERI.MI", "SRI.MI", "SES.MI", "SIT.MI", "SRG.MI", "SFT.MI", "SGF.MI", "SOL.MI", "SOM.MI", "STLAM.MI", "STMMI.MI", "TIP.MI", "TGYM.MI", "TPRO.MI", "TIT.MI", "TEN.MI", "TRN.MI", "TES.MI", "TSL.MI", "TISG.MI", "TNXT.MI", "TYA.MI", "TB.MI", "TXT.MI", "UCG.MI", "UD.MI", "UNIR.MI", "UNI.MI", "VLS.MI", "VIA.MI", "ZUC.MI", "WBD.MI", "WIIT.MI", "ZV.MI"]

#Elimino tutti i file presenti nella cartella upovermax10gg
files = glob.glob('/Users/fabry/upovermax12gg/*')
for f in files:
os.remove(f)

#Per ogni titolo della lista titoli scarico i dati di ieri e creo un file .csv per ogni titolo
for stock in listatitoli:
df = pd.DataFrame(stock_data)
df.to_csv(stock + ".csv", index=False)

#Sposto i file .csv nella cartella CSV titoli
src = r"/Users/fabry/"
dest = r"/Users/fabry/upovermax12gg"
os.chdir(src)
for files in glob.glob("*.csv"):
shutil.move(files, dest)

#Inizio analisi titoli

max_values_11_days = []

# Faccio l'append dei primi 11 max dalla colonna High
for row in range(len(df) - 1):

max_values_11_days.append(df.iat[row, 1])

maxdi11gg = max(max_values_11_days)
maxdodicesimogg = df.iat[11, 1]

#overmax12gg_path = Path('/Users/fabry/upovermax12gg/overmax12gg.csv')

#Stabilisco per ogni titolo se il max di oggi supera quello degli ultimi 11gg
if maxdodicesimogg > maxdi11gg:
# Use the 'a' for append.  Using 'w' will overwrite the current contents
with open('/Users/fabry/upovermax12gg/overmax12gg.csv', 'a', encoding='UTF-8') as OM:
OM.close()
``````

No error messages but Python doesn’t create the csv file overmax12gg.csv.

If I use the code lines suggested by Paul:

``````overmax12gg_path = Path('/Users/fabry/upovermax12gg/overmax12gg.csv')
if maxdodicesimogg > maxdi11gg:
with open(overmax12gg_path, 'a', encoding='UTF-8') as OM:
``````

``````---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
52 maxdodicesimogg = df.iat[11, 1]
53
---> 54 overmax12gg_path = Path('/Users/fabry/upovermax12gg/overmax12gg.csv')
55
56 #Stabilisco per ogni titolo se il max di oggi supera quello degli ultimi 11gg

NameError: name 'Path' is not defined
``````

I think that I must write something like this:

``````if maxdodicesimogg > maxdi11gg:
OM = open('/Users/fabry/upovermax12gg/overmax12gg.csv', "a")
OM.write("stock codes (e.g. ENI.MI, A2A.MI.... \n") #HERE'S THE PROBLEM!!
OM.close()
``````

I don’t know how to say to Python to write in the csv all the stock codes that satisfy the condition.

Thank you!