czzz0414
czzz0414

Reputation: 67

having trouble calculating daily return per ticker using dataframe in notebook

Below is the code for getting all the data from finance

# now get the first column(tickers) from the above data
# convert it into a list
ticker_list = df['Symbol'].values.tolist()
# convert the list into a string, separated by space, and replace . with -
all_tickers = " ".join(ticker_list).replace('.', '-')

# get all the tickers from yfinance
tickers = yf.Tickers(all_tickers)
# set a start and end date to get two-years info
# group by the ticker
hist = tickers.history(start='2020-05-01', end='2022-05-01', group_by='ticker')
Data_stack = hist.stack(level=0).reset_index().rename(columns = {'level_1':'Ticker'})

Now, I would like to add a new column that calculates the daily return per ticker daily returned is calculated as: (previous close price - current close price) / previous close price Below is my code (several ways but none of them work)

Data_stack['Daily Return %'] = Data_stack.groupby(['Ticker', 'Date'])['Close'].apply(lambda x: (x - x.shift())/x.shift())['Close'].rename(columns = {'Close': 'Daily Return %'})
Data_stack['Daily Return %'] = Data_stack.groupby(['Ticker', 'Date'])['Close']/Data_stack.groupby(['Ticker', 'Date'])['Close'].shift() -1
Data_stack['Daily Return %'] = Data_stack.groupby(['Ticker', 'Date']).transform(lambda x: (x - x.shift())/x.shift())[['Close']].rename(columns = {'Close': 'Daily Return %'})

Here is what I expected to obtain: enter image description here

Upvotes: 1

Views: 140

Answers (1)

Code Different
Code Different

Reputation: 93151

Your dataframe needs to be sorted first:

Data_stack['Daily Return %'] = Data_stack.sort_values(['Ticker', 'Date']).groupby('Ticker')['Close'].pct_change() * 100

Upvotes: 1

Related Questions