import requests
from bs4 import BeautifulSoup
import pandas as pd
# 1. Get list of S&P 500 tickers
def get_sp500_tickers():
wiki_url = 'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'
response = requests.get(wiki_url)
soup = BeautifulSoup(response.text, 'html.parser')
table = soup.find('table', {'id': 'constituents'})
df = pd.read_html(str(table))[0]
tickers = df['Symbol'].tolist()
# Replace any dots in tickers (e.g., BRK.B to BRK-B)
tickers = [ticker.replace('.', '-') for ticker in tickers]
return tickers
# 2. Iterate over each ticker and check the condition
def find_buy_tickers(tickers):
saved_tickers = []
for ticker in tickers:
url = f'https://stocknear.com/stocks/{ticker}'
response = requests.get(url)
if response.status_code != 200:
continue # Skip if page not found
soup = BeautifulSoup(response.text, 'html.parser')
divs = soup.find_all('div', class_='flex flex-col mt-5 w-full')
for div in divs:
if 'buy' in div.get_text().lower():
saved_tickers.append(ticker)
break # No need to check further divs for this ticker
return saved_tickers
# Main execution
tickers = get_sp500_tickers()
saved_tickers = find_buy_tickers(tickers)
# 4. Output the saved tickers
print(saved_tickers)
Explanation:
-
Get the list of S&P 500 tickers:
- We fetch the list of S&P 500 companies from Wikipedia.
- Parse the HTML table to extract the ticker symbols.
- Replace any dots in tickers (e.g., change
BRK.B to BRK-B) to match the URL format.
-
Iterate over each ticker:
- For each ticker, construct the URL
https://stocknear.com/stocks/<ticker>.
- Fetch the webpage content.
- Check if the response status is 200 (OK). If not, skip to the next ticker.
- Parse the HTML content using BeautifulSoup.
- Find all
<div> elements with the class flex flex-col mt-5 w-full.
- For each such
<div>, check if the text contains the word "buy" (case-insensitive).
- If
"buy" is found, save the ticker and move to the next one.
-
Output the saved tickers:
- After processing all tickers, print the list of saved tickers that met the condition.
Note: Make sure you have the requests, beautifulsoup4, and pandas libraries installed in your Google Colab environment. You can install any missing libraries using the following commands:
!pip install requests
!pip install beautifulsoup4
!pip install pandas