Comments (11)
@onlypencil can you please share it here so I can have a look as well. Much appreciated!
this worked for me and its still working for what i need it.
from bs4 import BeautifulSoup
try:
from requests_html import HTMLSession
except Exception:
pass
def force_float(elt):
try:
return float(elt)
except:
return elt
def get_calls(ticker, date = None):
"""Extracts call option table for input ticker and expiration date
@param: ticker
@param: date"""
options_chain = get_options_chain(ticker, date)
return options_chain["calls"]
def get_puts(ticker, date = None):
"""Extracts put option table for input ticker and expiration date
@param: ticker
@param: date"""
options_chain = get_options_chain(ticker, date)
return options_chain["puts"]
def get_expiration_dates(ticker):
"""Scrapes the expiration dates from each option chain for input ticker.
@param ticker: str - Ticker symbol of the stock/options
@return: list of expiration dates as strings
"""
try:
# Assuming build_options_url is a function that constructs the URL for the options page
site = build_options_url(ticker)
# Create a session and fetch the page
session = HTMLSession()
response = session.get(site)
response.raise_for_status() # Raises an HTTPError for bad responses
# Parse the HTML
soup = BeautifulSoup(response.content, 'html.parser')
options = soup.select('div.itm') # Adjust selector based on actual HTML structure
# Extract dates from each option element
dates = [option.text.strip() for option in options if option.text.strip() != '']
return dates
except Exception as e:
print(f"An error occurred: {e}")
return []
finally:
session.close()
def build_options_url(ticker, date = None):
"""Constructs the URL pointing to options chain"""
url = "https://finance.yahoo.com/quote/" + ticker + "/options?p=" + ticker
if date is not None:
url = url + "&date=" + str(int(pd.Timestamp(date).timestamp()))
return url
def get_options_chain(ticker, date=None, raw=True, headers=None):
"""
Fetch options data for the given ticker and expiration date.
@param ticker: str - Stock ticker symbol
@param date: str - Optional, the expiration date to retrieve options for
@param raw: bool - If False, format certain columns of data
@param headers: dict - HTTP headers to use for the request
@return: dict - Dictionary containing DataFrame for calls and puts
"""
if headers is None:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
# Building URL for options data
site = build_options_url(ticker, date)
# Fetch the HTML and parse it using BeautifulSoup
response = requests.get(site, headers=headers)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
# Locate tables by class name
tables = soup.find_all('table')
# Convert found tables to DataFrames
dataframes = [pd.read_html(str(table)) for table in tables]
# Handling the presence of either one or two tables
if len(dataframes) == 1:
calls = dataframes[0][0].copy()
puts = pd.DataFrame(columns=calls.columns)
elif len(dataframes) > 1:
calls, puts = dataframes[0][0].copy(), dataframes[1][0].copy()
# Optionally clean and format the data
if not raw:
for df in (calls, puts):
# Clean and convert data as necessary
df['% Change'] = df['% Change'].str.replace('%', '').str.replace('-', '0').astype(float) / 100
df['Volume'] = df['Volume'].str.replace('-', '0').replace(',', '', regex=True).astype(int)
df['Open Interest'] = df['Open Interest'].str.replace('-', '0').replace(',', '', regex=True).astype(int)
return {"calls": calls, "puts": puts}
except Exception as e:
print(f"An error occurred: {e}") # Debug: Print any error that occurs
return {"calls": pd.DataFrame(), "puts": pd.DataFrame()}
from yahoo_fin.
Im having the same issue with the same error
from yahoo_fin.
Also having the same issue. Returning ['\n']. Also, the "get_options_chain()" command doesn't work either.
from yahoo_fin.
Same here, also get_stats() doesn't work anymore.
Probably due to the new yahoo!finance web interface
from yahoo_fin.
Switching to yfinance ...
from yahoo_fin.
I got it working but had to make my own functions based on their code
from yahoo_fin.
@onlypencil can you please share it here so I can have a look as well. Much appreciated!
from yahoo_fin.
Related Issues (20)
- Problem in get_earnings_history HOT 2
- How to export data into csv file ? HOT 1
- problem with get_income_data HOT 2
- How to add yahoo_fin to a project in pycharm
- Exceptions since last Yahoo updates HOT 4
- stock_info.tickers_sp500() returning strings of underscores HOT 4
- tickers_sp500() ERROR: ssl.SSLCertVerificationError HOT 1
- get_quote_data() - Invalid response from server HOT 1
- Issue with get_day_gainers() HOT 1
- get_quote_table -> error 'DataFrame' object has no attribute 'append' HOT 2
- OperationalError: unable to open database file
- requests_html error (not installed) HOT 1
- get_quote_table not working HOT 2
- get_stats_valuation not working | yahoo finance error?! HOT 1
- Include multi-year data in Income Statement method
- get_balance_sheet() return empty dataframe
- get_income_statement: string indices must be integers HOT 9
- get_earnings_for_date() Always Fails Now HOT 6
- get_balance_sheet doesn't return any data HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from yahoo_fin.