Home > Net >  Getting strange yfinance ValueError and not receiving the correct outputs
Getting strange yfinance ValueError and not receiving the correct outputs

Time:02-18

I'm trying to display a list of put options for a specific expiry date. For some reason, it's returning a strange error as below.

raise ValueError(
ValueError: Expiration `2022-03-18` cannot be found. Available expiration are: [2022-02-18, 2022-02-25, 2022-03-04, 2022-03-11, 2022-03-18, 2022-03-25, 2022-04-01, 2022-04-14, 2022-05-20, 2022-06-17, 2022-07-15, 2022-08-19, 2022-09-16, 2023-01-20, 2023-03-17, 2023-06-16, 2024-01-19]

Process finished with exit code 1

As you can see, I'm confused because the date mentioned as not being found is clearly in the list of available expirations provided.

This is my code:

import yfinance as yf
import pandas as pd
import datetime
import calendar

pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)

msft = yf.Ticker("MSFT")


# Get the expiry date of closes Friday 30 days from today
today = datetime.date.today()
_30_days_after_today = today   datetime.timedelta(days=30)
next_friday = _30_days_after_today   datetime.timedelta(days=(calendar.FRIDAY - _30_days_after_today.weekday()))
print(type(next_friday))

# get option chain for specific expiration
opt = msft.option_chain(next_friday)
# data available via: opt.calls, opt.puts
print(opt.puts)

Does anyone know what causes this?

CodePudding user response:

Seems like the error is resolved when I convert input into a string.

import pandas as pd
import datetime
import calendar

pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)

msft = yf.Ticker("MSFT")


# Get the expiry date of closes Friday 30 days from today
today = datetime.date.today()
_30_days_after_today = today   datetime.timedelta(days=30)
next_friday = str(_30_days_after_today   datetime.timedelta(days=(calendar.FRIDAY - _30_days_after_today.weekday())))
print(next_friday)

# get option chain for specific expiration
opt = msft.option_chain(date=next_friday)
# data available via: opt.calls, opt.puts
print(opt.puts)
  • Related