Home > Enterprise >  Can't save computed values result in DataFrame
Can't save computed values result in DataFrame

Time:07-04

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:

  1. 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)
  1. Computing Return:

for stock in test_stocks:
    trading_df['Return'] = trading_df[trading_df['Symbol'] == stock]['Adj Close'].pct_change(1)
  1. The result:

Rendered data

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)
  • Related