ranaroussi / yfinance

Download market data from Yahoo! Finance's API
https://aroussi.com/post/python-yahoo-finance
Apache License 2.0
14.89k stars 2.44k forks source link

auto_adjust failed with unsupported operand type(s) for /: 'str' and 'float' #2050

Open tyler-austin opened 2 months ago

tyler-austin commented 2 months ago

First off, awesome library! I am getting a lot of use out of it.

I got the following error when using this library:

Error: auto_adjust failed with unsupported operand type(s) for /: 'str' and 'float'

Call to reproduce:

import yfinance as yf
from dateutil.relativedelta import relativedelta
from datetime import datetime

def calculate_period_return(stock, hist, start_date):
    """Helper function to calculate return for a given period."""
    try:
        period_hist = hist.loc[start_date:]
        if len(period_hist) > 0:
            period_return = ((hist['Close'].iloc[-1] / period_hist['Close'].iloc[0]) - 1) * 100
        else:
            period_return = np.nan
        return period_return
    except Exception as e:
        return np.nan

stock = yf.Ticker(ticker, session=session)
hist = stock.history(period="max")

end_date = datetime.now(pytz.UTC)
start_date = end_date - relativedelta(years=1)

calculate_period_return(stock, hist, start_date)

I believe the error is coming from here: https://github.com/ranaroussi/yfinance/blob/3fe87cb1326249cb6a2ce33e9e23c5fd564cf54b/yfinance/utils.py#L453

ratio = (df["Adj Close"] / df["Close"]).to_numpy()

Possible Fix:

# Convert columns to numeric, coercing errors to NaN if there are non-numeric values
df["Adj Close"] = pd.to_numeric(df["Adj Close"], errors='coerce')
df["Close"] = pd.to_numeric(df["Close"], errors='coerce')

# Perform the division and convert the result to a NumPy array
ratio = (df["Adj Close"] / df["Close"]).to_numpy()

# Optionally, you could also drop any rows where the conversion resulted in NaN values:
# df.dropna(subset=["Adj Close", "Close"], inplace=True)
friesentyler commented 4 weeks ago

Did you end up getting this fixed?