Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
tyler-austin opened this issue Sep 7, 2024 · 1 comment

Comments

@tyler-austin
Copy link

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:

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

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
Copy link

Did you end up getting this fixed?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants