Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Loop Through Tickers

I have a program that opens a stock’s data file, feeds it to a function which turns the date into a datetime index, and then returns the file and outputs it as a csv. It works fine, here is the code:

import pandas as pd

def clean_func(f1):
    f1['Date'] = pd.to_datetime(f1['Date']) 
    f1.index = f1['Date']
    return f1
    
df = pd.read_csv(r'C:\\path\\tkr.csv')
df1 = clean_func(df)
df1.to_csv('C:\\path\\tkr.csv')

Rather than have redundant lines of code for each ticker ("tkr" above), I’d like to create a list of ticker symbols and loop through them. I’m not sure how embed everything correctly to loop through a list hence this post. Please advise.

Thank you

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can put them in a for loop with format strings (f-strings) like this:

import pandas as pd

def clean_func(f1):
    f1['Date'] = pd.to_datetime(f1['Date']) 
    f1.index = f1['Date']
    return f1
    
tkrs = ['tkr1', 'tkr2', 'tkr3']
for tkr in tkrs:
    df = pd.read_csv(f'C:\\path\\{tkr}.csv')
    df1 = clean_func(df)
    df1.to_csv(f'C:\\path\\{tkr}.csv')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading