Home > Blockchain >  Loop Through Tickers
Loop Through Tickers

Time:07-01

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

CodePudding user response:

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')
  • Related