VidyaSree
VidyaSree

Reputation: 57

separating each stock data into individual dataframe

I took historical data of 100 stocks. It is a single file with all tickers with corresponding data. How to loop such that each ticker data gets separated in dataframe with its own name? I've tried this but this doesnt work.

for ticker in stocks:
    print(ticker)
    tick=pd.DataFrame(data.loc[(data.ticker==ticker)])
    tick['returns']=tick.close.pct_change()

    value='daily_returns_'+str(ticker)
    value=tick[['date']]
    value['returns']=tick['returns']
    print(value)

    ex=str(value)+'.csv'
    value.to_csv(ex)

Upvotes: 3

Views: 196

Answers (1)

jpp
jpp

Reputation: 164673

Arbitrary variable names is considered poor practice. Instead, you can define a dictionary for a variable number of variables:

dfs = dict(tuple(data.groupby('ticker')))

Then, if you wish, export to csv via iterating dictionary items:

for k, v in dfs.items():
    v.to_csv(k+'.csv', index=False)

Upvotes: 1

Related Questions