Notice
Recent Posts
Recent Comments
Link
반응형
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
Archives
Today
Total
관리 메뉴

To Be Develop

How to Build a Stock Screener Using Python 본문

study

How to Build a Stock Screener Using Python

To Be Develop 2024. 11. 26. 22:31
반응형

Overview

A stock screener is an essential tool for investors, enabling them to filter stocks based on specific criteria like financial ratios, technical indicators, or other custom parameters. This guide will walk you through building a Python-based stock screener from scratch. By the end, you’ll have a functional script that fetches stock data, applies filters, and displays relevant results.

We’ll use popular libraries like pandas for data manipulation, yfinance for stock data retrieval, and simple Python logic for filtering criteria.


Prerequisites

Before starting, ensure you have the following:

  1. Python installed: Download Python.
  2. Basic knowledge: Familiarity with Python programming and financial concepts.
  3. Libraries: Install necessary Python packages:
    pip install pandas yfinance matplotlib

Step-by-Step Guide

1. Define the Objective

Our stock screener will:

  1. Fetch real-time or historical stock data.
  2. Filter stocks based on criteria like:
  • PE ratio: Price-to-Earnings ratio.
  • RSI (Relative Strength Index): A technical indicator for momentum.
  • Market capitalization: Total market value of a company.
  1. Display results in a tabular format.

2. Set Up Your Environment

Start by importing necessary libraries:

import pandas as pd
import yfinance as yf
import matplotlib.pyplot as plt

3. Fetch Stock Data

We’ll use the yfinance library to retrieve stock data.

Example: Fetching Data for Multiple Stocks

def fetch_stock_data(tickers):
"""
Fetch historical data for a list of stock tickers.
"""
stock_data = {}
for ticker in tickers:
try:
data = yf.Ticker(ticker).history(period="1y")  # Last 1 year
stock_data[ticker] = data
except Exception as e:
print(f"Error fetching data for {ticker}: {e}")
return stock_data

# Example usage
tickers = ["AAPL", "MSFT", "GOOGL", "AMZN"]
stock_data = fetch_stock_data(tickers)

4. Define Filtering Criteria

Here, we’ll define some common financial filters:

  • PE Ratio: Filter companies with a PE ratio less than a threshold (e.g., 20).
  • Market Cap: Filter companies based on market size.
  • RSI: Identify oversold stocks (RSI < 30).

Example Code

def filter_stocks(tickers):
"""
Filter stocks based on PE ratio, RSI, and market cap.
"""
filtered_stocks = []

for ticker in tickers:
try:
stock = yf.Ticker(ticker)
info = stock.info

# Financial filters
pe_ratio = info.get("trailingPE", None)
market_cap = info.get("marketCap", None)
rsi = calculate_rsi(stock.history(period="1mo")['Close'])

# Apply conditions
if pe_ratio and pe_ratio < 20 and market_cap and market_cap > 1e9 and rsi < 30:
filtered_stocks.append({
"Ticker": ticker,
"PE Ratio": pe_ratio,
"Market Cap": market_cap,
"RSI": rsi
})

except Exception as e:
print(f"Error processing {ticker}: {e}")

return pd.DataFrame(filtered_stocks)

# Example usage
filtered_results = filter_stocks(tickers)
print(filtered_results)

5. Add Technical Indicators

To calculate RSI:

def calculate_rsi(data, window=14):
"""
Calculate Relative Strength Index (RSI).
"""
delta = data.diff(1)
gain = (delta.where(delta > 0, 0)).rolling(window=window).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=window).mean()
rs = gain / loss
rsi = 100 - (100 / (1 + rs))
return rsi.iloc[-1]  # Return the latest RSI value

6. Visualize Results

You can visualize stock trends or filtered results using matplotlib.

Example: Plot Stock Prices

def plot_stock_price(ticker):
"""
Plot historical stock prices for a given ticker.
"""
data = yf.Ticker(ticker).history(period="1y")
data['Close'].plot(title=f"{ticker} Stock Price")
plt.xlabel("Date")
plt.ylabel("Close Price")
plt.show()

# Example usage
plot_stock_price("AAPL")

7. Combine Everything

Here’s how to integrate all the steps into a cohesive script:

if __name__ == "__main__":
# List of tickers to analyze
tickers = ["AAPL", "MSFT", "GOOGL", "AMZN", "TSLA"]

# Step 1: Fetch and filter stock data
print("Fetching data and applying filters...")
results = filter_stocks(tickers)

# Step 2: Display results
print("\nFiltered Stocks:")
print(results)

# Step 3: Visualize one of the stocks
if not results.empty:
plot_stock_price(results.iloc[0]["Ticker"])

Next Steps

  1. Extend Functionality: Add more filters (e.g., Dividend Yield, Debt-to-Equity ratio).
  2. Database Integration: Store data in a database (e.g., SQLite) for future use.
  3. Real-Time Screening: Use APIs like Alpha Vantage for live data.

References


This guide provides you with a strong foundation for building a custom stock screener. By combining financial logic with Python, you can analyze and filter stocks tailored to your investment strategy.

반응형