Search code examples
pythonpython-3.xpandaspandas-datareader

Python Pandas_DataReader to create a DF for each ticker and save .to_csv with tickers name


On a previous question of mine here in StackOverflow, a guy named Ash gave me a code and i edited for my needs, but, i an having a great trouble to figure out how to get 'open','high','low','close','volume' for each Ticker, and save each one of them as CSV.

The code bellow is bringing me just the 'Adj Close' which i dont need. I would like to get a DF for each ticker with open, high, low, close, volume as columns and then save .to_csv each DF with the Ticker name.

Is it possible to do so, without breaking the 'Ticker' list a part?

from datetime import date
import pandas as pd
import datetime
from pandas_datareader import data as wb

start = date.today()-datetime.timedelta(days=2*365)
end = date.today()

tickers = ['MGFF11.SA',
'XPML11.SA',
'VISC11.SA',
'HGCR11.SA',
'XPLG11.SA',]

price_data = []
for ticker in tickers:
    prices = wb.DataReader(ticker, start = start, end = end, data_source='yahoo')
    price_data.append(prices.assign(ticker=ticker)[['ticker', 'Adj Close']])

df = pd.concat(price_data)

pd.set_option('display.max_columns', 500)

df = df.reset_index()
df = df.set_index('Date')
table = df.pivot(columns='ticker')
table.columns = [col[1] for col in table.columns]
print(table)


Solution

  • IIUC:

    for ticker in tickers:
        prices = wb.DataReader(ticker, start = start, end = end, data_source='yahoo')
        ticker_csv = "{}.csv".format(ticker)
        prices.to_csv(ticker_csv)
    

    Separate csv file for every ticker