Below is a Python code outline for creating a simple stock screener that identifies stocks consolidating above a support level:
pythonimport yfinance as yf
import pandas as pd
# Define function to check if stock is consolidating
def is_consolidating(data, percentage=2):
recent_candlesticks = data[-15:]
support_level = min(recent_candlesticks['Low'])
resistance_level = max(recent_candlesticks['High'])
range = resistance_level - support_level
if abs((resistance_level - data['Close'].iloc[-1]) / range * 100) < percentage and abs((data['Close'].iloc[-1] - support_level) / range * 100) < percentage:
return True
return False
# Define function to screen stocks
def stock_screener(tickers):
consolidating_stocks = []
for ticker in tickers:
try:
data = yf.download(ticker, period="1d", interval="1d")
if is_consolidating(data):
consolidating_stocks.append(ticker)
except Exception as e:
print(f"Error processing {ticker}: {e}")
return consolidating_stocks
# Example usage
tickers = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'FB']
consolidating_stocks = stock_screener(tickers)
print("Consolidating stocks:", consolidating_stocks)
This code uses the Yahoo Finance API (yfinance) to fetch stock data and pandas for data manipulation. It defines a function is_consolidating to check if a stock is consolidating and another function stock_screener to screen a list of tickers for consolidating stocks. The is_consolidating function determines if the stock is consolidating by checking if the recent candlesticks are within a certain percentage range of
==========================================
Here's Python code for a stock screener that identifies stocks consolidating in pre-market or above a support level using technical analysis indicators:
Explanation:
- The code uses
yfinanceto download pre-market and historical stock data. - The
get_premarket_datafunction retrieves the latest pre-market data point (if available) usingyfinance. - The
is_consolidatingfunction calculates the Average True Range (ATR) to estimate volatility and checks if the recent price movement falls within a certain threshold, indicating consolidation. - The
identify_consolidating_stocksfunction iterates through a list of tickers, downloads data, and checks for consolidation in pre-market or above a support level (if provided). - The example usage demonstrates how to call the function with a list of tickers and an optional
Here's Python code for a stock screener that identifies stocks consolidating in pre-market or above a support level:
Explanation:
-
The code defines functions for:
- Downloading pre-market data using
yfinance. - Calculating support levels (replace the placeholder with your logic or technical analysis libraries).
- Identifying consolidating stocks based on pre-market price range and/or price above a support level (adjust the criteria as needed).
- Downloading pre-market data using
-
The main section defines a list of symbols to scan, downloads pre-market data, calculates support levels, and identifies consolidating stocks.
Improvements:
- Support Level Calculation: Replace the placeholder function with your strategy for calculating support levels based on historical data (e.g., moving averages, Bollinger Bands).
- Consolidation Criteria: Adjust the consolidation criteria (pre-market price range or support level) based on your trading strategy.
- Technical Analysis Libraries: Consider using libraries like
TA-LiborpyTAfor more advanced technical analysis calculations. - Data Filtering and Sorting: You can further filter and sort the results based on additional factors like average daily trading volume or market capitalization.
Disclaimer: This is for educational purposes only. Always do your own research before making any investment decisions.
======================================
Here's Python code for a stock screener that identifies stocks consolidating in pre-market or above a support level:
import yfinance as yf
import pandas as pd
def is_consolidating(symbol, premarket_data=False, support_level=None):
"""
Checks if a stock is consolidating based on pre-market data or above a support level.
Args:
symbol (str): The stock ticker symbol.
premarket_data (bool, optional): If True, uses pre-market data (if available). Defaults to False.
support_level (float, optional): The support level for consolidation. Defaults to None.
Returns:
bool: True if the stock is consolidating, False otherwise.
"""
# Download historical data (replace with your preferred time period)
data = yf.download(symbol, period="1d", premarket=premarket_data)
# Check if pre-market data is available
if premarket_data and not data.empty:
# Calculate pre-market high-low range
premarket_range = data["High"] - data["Low"]
else:
# Use regular market data
premarket_range = None
# Check for consolidation based on pre-market data
if premarket_range is not None:
# Replace 0.05 with your desired percentage threshold for consolidation range
consolidated_premarket = premarket_range <= data["Close"] * 0.05
if consolidated_premarket:
return True
# Check for consolidation above support level (if provided)
if support_level is not None:
consolidated_above_support = data["Low"] >= support_level
if consolidated_above_support:
return True
# Stock is not consolidating
return False
def screen_stocks(symbols, premarket_data=False, support_level=None):
"""
Screens a list of stocks for consolidation.
Args:
symbols (list): List of stock ticker symbols.
premarket_data (bool, optional): If True, uses pre-market data (if available). Defaults to False.
support_level (float, optional): The support level for consolidation. Defaults to None.
Returns:
list: List of symbols that are consolidating.
"""
consolidated_stocks = []
for symbol in symbols:
if is_consolidating(symbol, premarket_data, support_level):
consolidated_stocks.append(symbol)
return consolidated_stocks
# Example usage
symbols = ["AAPL", "GOOG", "TSLA"] # Replace with your list of symbols
premarket_data = True # Set to True to use pre-market data (if available)
support_level = 100 # Optional support level for consolidation
consolidated_list = screen_stocks(symbols, premarket_data, support_level)
if consolidated_list:
print("Consolidating stocks:")
for stock in consolidated_list:
print(stock)
else:
print("No consolidating stocks found.")
Explanation:
- The
is_consolidatingfunction checks for consolidation based on two criteria:- Pre-market data (if available): It calculates the pre-market high-low range and compares it to a percentage threshold of the previous day's closing price (adjustable).
- Support level (if provided): It checks if the stock's intraday low is above the specified support level.
- The
screen_stocksfunction iterates through a list of symbols and callsis_consolidatingfor each one. It returns a list of symbols that meet the consolidation criteria. - The example usage demonstrates screening a list of symbols and printing the results.
Additional Notes:
- You can replace
yfinancewith other stock data providers (adjust code accordingly). - Adjust the consolidation criteria (pre-market range threshold, support level) based on your strategy.
- This code provides a basic framework. You can extend it to incorporate additional technical indicators or filtering criteria.
- Consider using a scheduled task to run the screener periodically and update your stock watchlist.

No comments:
Post a Comment