Code Monkey home page Code Monkey logo

Comments (11)

onlypencil avatar onlypencil commented on July 28, 2024 1

@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.

onlypencil avatar onlypencil commented on July 28, 2024

Im having the same issue with the same error

from yahoo_fin.

adadoucette avatar adadoucette commented on July 28, 2024

Also having the same issue. Returning ['\n']. Also, the "get_options_chain()" command doesn't work either.

from yahoo_fin.

benoitdr avatar benoitdr commented on July 28, 2024

Same here, also get_stats() doesn't work anymore.
Probably due to the new yahoo!finance web interface

from yahoo_fin.

benoitdr avatar benoitdr commented on July 28, 2024

Switching to yfinance ...

from yahoo_fin.

onlypencil avatar onlypencil commented on July 28, 2024

I got it working but had to make my own functions based on their code

from yahoo_fin.

Rahul-Holla avatar Rahul-Holla commented on July 28, 2024

@onlypencil can you please share it here so I can have a look as well. Much appreciated!

from yahoo_fin.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.