I'm building a dataframe which contains trading data from Yahoo Finance.
When I'm trying to compute Return using for loop for each stock, only the last result is saved in dataframe, while rest of the stocks are Nan.
I assume that computed returns are overwrite for every stock except the last one, but have no idea what is the reason for that occurrence.
Here's my code:
- Load data from Yahoo Finance:
trading_df = pd.DataFrame()
for stock in test_stocks:
st = web.DataReader(stock, 'yahoo', start, end)
st['Symbol'] = stock
trading_df = trading_df.append(st)
- Computing Return:
for stock in test_stocks:
trading_df['Return'] = trading_df[trading_df['Symbol'] == stock]['Adj Close'].pct_change(1)
- The result:
Thanks in advance.
CodePudding user response:
You need to slice the dataframe when assigning values
trading_df.loc[trading_df['Symbol'] == stock, 'Return'] = trading_df[trading_df['Symbol'] == stock]['Adj Close'].pct_change(1)