Search code examples
python-3.xexport-to-csvyahoo-finance

How to save multiple stocks data frame into different separate csv files?


Sample code:

tickers = ["FB", "AMZN", "AAPL", "NFLX", "GOOG", "^GSPC",...]
multpl_stocks = web.get_data_yahoo(tickers,
start = "2013-01-01",
end = "2014-03-01"())

I would like to save all tickers at the same time into different csv files.

Of course, I know the following code which just save one of the data frames.

apple = web.get_data_yahoo("AAPL",
                        
                            start = "2009-01-01",
                            end = datetime.now())

But, I want to save them at the same time each one into a csv file .

I do not want to do that one by one as it takes a lot time

I tried the following code ,but did not work

 apple, goog, fb  = web.get_data_yahoo("AAPL","GOOG", "FB"
                        
                            start = "2009-01-01",
                            end =  "2013-01-01))

apple, goog, fb.to_csv(r("c:\desktop\users\fb.csv, goog.csv, apple.csv"))

I want the result to be like this and be stored in my pc:

fb.csv

goog.csv

apple.csv


Solution

  • You could do something like this:

    import pandas as pd
    from pandas_datareader import data as web #I assume this is what you have
    from datetime import datetime
    
    tickers = ["FB", "AMZN", "AAPL", "NFLX", "GOOG"] #and everything else
    
    for stock in tickers:
     stock_data = web.get_data_yahoo(stock, start = "2009-01-01", end = datetime.now())
     df = pd.DataFrame(stock_data)
     df.to_csv(stock + ".csv", index=False)