'How to divide a groupby Object by pandas Series efficiently? Or how to convert yfinance multiple ticker data to another currency?

I am pulling historical price data for the S&P500 index components with yfinance and would now like to convert the Close & Volume from USD into EUR.

This is what I tried:

data = yf.download(set(components), group_by="Ticker", start=get_data.start_date)

where start="2020-11-04" and components is a list of yfinance tickers of S&P500 members and the "EURUSD=X" -> the symbol for the conversion rate

#Group by Ticker and Date
df = data.stack(level=0).rename_axis(['Date', 'Ticker']).reset_index(level=1)
df = df.sort_values(by='Ticker',axis='index',kind='stable')

After adding columns for the name, sector & name of the currency (I need this as in my application I am appending several dataframes with tickers of different currency) and dropping columns I dont need, I have a dataframe that looks like this: Link to Dataframe

I now what to convert the Close & the Volume Column into EUR. I have found a way that works on most of the data except the S&P500 and other US stocks, which is why I am posting the question here.

# Check again if Currency is not EUR
if currency != "EUR":
    df['Close in EUR'] = df.groupby('Ticker')['Close'].apply(lambda group: group.iloc[::]/df[df['Ticker']==currency]['Close'])
    df['Volume in Mio. EUR'] = df['Volume']*df['Close in EUR']/1000000
else:
    df['Volume in Mio. EUR'] = df['Volume']*df['Close']/1000000

This does not only take a lot of time (~46 seconds), but it also shows NaN values for "Close in EUR" and "Volume in Mio. EUR" columns. Do you have any idea?

I have found that df[df['Ticker']==currency] has more rows than the stock tickers have due to public holidays of the stock exchanges and even after deleting the unmatched rows, I am left with NaN values. Doing the whole process for other index members, e.g. ^JKLQ45 (Indonesia Stock Exchange index) works, which is surprising.

Please any help or even an idea how to do this more efficiently is highly appreciated!!!

If you want to get a sense of my final project - check out: https://equityanalysis.herokuapp.com/



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source