3

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)
sacuL
  • 49,704
  • 8
  • 81
  • 106
VidyaSree
  • 57
  • 2
  • I've tried creating a dictionary, but the value of the dictionary is a dataframe. How can I make it a series by chosing only one column(daily_returns column)? I want like this dfs= { 'ABBV' : 0.0042, 0.0067 ..., 'JCI': ....} – VidyaSree Jul 03 '18 at 04:57
  • Or how to I convert this dfs dictionary to a dataframe?? – VidyaSree Jul 03 '18 at 04:58

1 Answers1

1

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)
jpp
  • 159,742
  • 34
  • 281
  • 339