Search code examples
python-3.xpandasexport-to-csv

Export multiple csv file using different filename in python


I am new to python. After researching some code based on my idea which is extracting historical stock data, I have now working code(see below) when extracting individual name and exporting it to a csv file

import investpy
import sys
sys.stdout = open("extracted.csv", "w")
df = investpy.get_stock_historical_data(stock='JFC',
                                        country='philippines',
                                        from_date='25/11/2020',
                                        to_date='18/12/2020')
print(df)
sys.stdout.close()

Now, I'm trying to make it more advance. I want to run this code multiple times automatically with different stock name(about 300 plus name) and export it respectively.

I know it is possible but I cannot search the exact terminology to this problem. Hoping for your help.

Regards,


Solution

  • you can store the stock's name as a list and then iterate through the list and save all the dataframes into separate files.

    import investpy
    import sys
    stocks_list = ['JFC','AAPL',....] # your stock lists
    for stock in stocks_list:
       df = investpy.get_stock_historical_data(stock=stock,
                                            country='philippines',
                                            from_date='25/11/2020',
                                            to_date='18/12/2020')
      print(df)
      file_name = 'extracted_'+stock+'.csv'
      df.to_csv(file_name,index=False)