Advertisement
UF6

Stock Scraping Tool

UF6
Jan 16th, 2024
701
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.48 KB | Source Code | 0 0
  1. import requests
  2. from bs4 import BeautifulSoup
  3. from selenium import webdriver
  4. from selenium.webdriver.common.by import By
  5. from selenium.webdriver.support.ui import WebDriverWait
  6. from selenium.webdriver.support import expected_conditions as EC
  7. import pandas as pd
  8. import matplotlib.pyplot as plt
  9.  
  10. def scrape_stock_data(stock_symbol):
  11.     url = f'https://finance.yahoo.com/quote/{stock_symbol}'
  12.    
  13.     # Use a headless browser for dynamic content
  14.     options = webdriver.ChromeOptions()
  15.     options.add_argument('--headless')
  16.    
  17.     driver = webdriver.Chrome(options=options)
  18.     driver.get(url)
  19.    
  20.     try:
  21.         # Wait for the stock price to load (adjust timeout if needed)
  22.         stock_price_element = WebDriverWait(driver, 10).until(
  23.             EC.presence_of_element_located((By.CSS_SELECTOR, 'span[data-reactid*="50"]'))
  24.             # You may need to modify the CSS selector based on your findings
  25.         )
  26.        
  27.         stock_price = stock_price_element.text
  28.         return {'stock_symbol': stock_symbol, 'stock_price': stock_price}
  29.     except Exception as e:
  30.         print(f"Failed to find stock price for {stock_symbol}: {e}")
  31.         return None
  32.     finally:
  33.         driver.quit()
  34.  
  35. def analyze_stock_data(data_frame):
  36.     # Perform statistical analysis using pandas
  37.     # Example: Calculate the mean, standard deviation
  38.     mean_price = data_frame['stock_price'].mean()
  39.     std_dev_price = data_frame['stock_price'].std()
  40.    
  41.     return mean_price, std_dev_price
  42.  
  43. def visualize_data(data_frame):
  44.     # Example: Create a simple bar plot
  45.     data_frame.plot(x='stock_symbol', y='stock_price', kind='bar', title='Stock Prices')
  46.     plt.show()
  47.  
  48. def main():
  49.     stock_symbols = ['AAPL', 'GOOGL', 'MSFT']  # Add more symbols as needed
  50.     stock_data_list = []
  51.  
  52.     for symbol in stock_symbols:
  53.         stock_data = scrape_stock_data(symbol)
  54.         if stock_data:
  55.             stock_data_list.append(stock_data)
  56.  
  57.     # Create a pandas DataFrame from the collected data
  58.     data_frame = pd.DataFrame(stock_data_list)
  59.  
  60.     # Check if the DataFrame is not empty before proceeding
  61.     if not data_frame.empty:
  62.         # Analyze and visualize the data
  63.         mean_price, std_dev_price = analyze_stock_data(data_frame)
  64.         print(f"Mean Stock Price: {mean_price}")
  65.         print(f"Standard Deviation of Stock Price: {std_dev_price}")
  66.  
  67.         visualize_data(data_frame)
  68.     else:
  69.         print("No data available.")
  70.  
  71. if __name__ == "__main__":
  72.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement