A comprehensive Python tool to analyze stocks using Yahoo Finance analyst data. Find buying opportunities with undervalued stocks and manage your portfolio with analyst target comparisons.
- Smart Caching: Automatically caches fetched data by date - rerun on the same day to skip API calls
- Date-Based Most Active Tickers: Fetches most active stocks daily with automatic date tracking
- Flexible Input: Automatically fetches S&P 500 + optionally most active stocks (≥$10B market cap)
- Comprehensive Analysis: Retrieves analyst price targets, buy/sell/hold recommendations, and market cap
- Analyst Coverage Filter: Only includes stocks with ≥10 total analyst opinions for reliable data
- Intelligent Filtering: Identifies stocks at or below analyst's low target + 10% (cheaper = better!)
- Multiple Sorting Strategies: Generates 3 different sorted reports based on:
- Sell count → Buy count
- Sell count → Price vs target gap
- Sell count → Market cap
- Multi-Currency Support: Track holdings in USD, CAD, and other currencies
- Real-Time Currency Conversion: Automatically converts analyst targets to your portfolio currency
- Selling Signal Analysis: Identifies when current price exceeds analyst targets
- Performance Tracking: Monitors gains/losses and compares against analyst expectations
- Organized Output: Date-based folders with multiple CSV files for different analyses
.
├── main.py # Main orchestration script
├── src/
│ ├── ticker_fetcher.py # Ticker list management (S&P 500, most active)
│ ├── analyst_data.py # Analyst data fetching with caching & filtering
│ ├── sorting_strategies.py # Multiple sorting strategies (extensible)
│ └── portfolio_analysis.py # Portfolio tracking & selling signals
├── input_tickers/ # Input CSV files (auto-populated)
│ ├── sp500_tickers.csv # S&P 500 stocks (auto-generated)
│ └── most_active_tickers_YYYY-MM-DD.csv # Daily most active stocks
├── portfolio/ # Your portfolio holdings
│ └── my_portfolio.csv # Ticker, purchase price, currency
├── cache/ # Raw data cache (by date)
│ └── raw_data_YYYY-MM-DD.csv
├── output_results/ # Output folder
│ └── YYYY-MM-DD/ # Date-based subfolders
│ ├── by_sell_then_buy.csv
│ ├── by_sell_then_price_gap.csv
│ ├── by_sell_then_market_cap.csv
│ ├── top_10_common_all_strategies.csv
│ └── portfolio_analysis_YYYY-MM-DD.csv
├── requirements.txt # Python dependencies
└── README.md # This file
- Create and activate virtual environment:
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate- Install dependencies:
pip install -r requirements.txtRun the main script:
python main.pyStep 1: Input Ticker Setup
- Checks
input_tickers/folder for CSV files - Checks if today's most active tickers file exists (
most_active_tickers_YYYY-MM-DD.csv) - If folder is empty, automatically creates:
sp500_tickers.csv- S&P 500 stocks (~500 tickers)most_active_tickers_YYYY-MM-DD.csv- Most active stocks (optional, user prompted, filtered ≥$10B)
- If files exist but today's most active is missing, prompts to fetch today's data
Step 2: Fetch & Filter Analyst Data
- Loads all tickers from CSV files in
input_tickers/ - Checks cache first: If raw data exists for today, skips fetching and uses cached data
- If no cache, fetches analyst insights (price targets, recommendations, market cap)
- Saves raw data to
cache/raw_data_YYYY-MM-DD.csv - Step 2-2: Filter by Analyst Coverage - Removes stocks with <10 total analyst opinions
- Step 2-3: Filter by Price Target - Keeps stocks at or below target_low + 10%
Step 3: Apply Sorting Strategies
- Creates date-based output folder:
output_results/YYYY-MM-DD/ - Generates 3 CSV files with different sorting strategies:
by_sell_then_buy.csv- Sorted by total sell (ascending), then total buy (descending)by_sell_then_price_gap.csv- Sorted by total sell (ascending), then price vs target % (ascending)by_sell_then_market_cap.csv- Sorted by total sell (ascending), then market cap (descending)
- Displays top 10 results for each strategy in console
- Analyzes which tickers appear in the top 10 of ALL sorting strategies
- Saves consensus picks to
top_10_common_all_strategies.csv
Step 4: Portfolio Analysis
- Loads your portfolio from
portfolio/my_portfolio.csv - Fetches current analyst data for each holding
- Converts USD analyst targets to your portfolio currency (USD, CAD, etc.)
- Calculates performance metrics and selling signals
- Saves analysis to
portfolio_analysis_YYYY-MM-DD.csv - Displays detailed results sorted by current price performance
Ticker Input (input_tickers/ folder)
The first column must contain ticker symbols. Additional columns are optional:
ticker,name,volume
AAPL,Apple Inc.,50000000
MSFT,Microsoft Corporation,30000000
You can add multiple CSV files to input_tickers/ - all will be processed.
Portfolio Input (portfolio/my_portfolio.csv)
Required columns: ticker, purchase_price, currency
ticker,purchase_price,currency
AAPL,150.00,USD
MSFT,320.00,USD
GOOGL,140.00,CAD
VFV,139.41,CAD
Supported currencies: USD, CAD, EUR, GBP, and any currency pair available on Yahoo Finance (format: USDCAD=X)
Buying Analysis (by_sell_then_*.csv, top_10_common_all_strategies.csv)
Columns include:
ticker- Stock symbolcompany_name- Company namecurrent_price- Current stock pricetarget_low,target_mean,target_high- Analyst price targetsstrong_buy,buy,hold,sell,strong_sell- Recommendation countstotal_buy- sum of strong_buy + buytotal_sell- sum of sell + strong_selltotal_analyst_opinions- Total number of analyst recommendationsmarket_cap- Market capitalizationprice_vs_target_pct- Percentage gap: (current_price - target_low) / current_price * 100- Negative % = trading below analyst's low target (potential bargain!)
- Positive % = trading above analyst's low target
- Lower % = closer to target low (better value)
price_at_low_end- Boolean: is price ≤ target_low + 10%
Portfolio Analysis (portfolio_analysis_YYYY-MM-DD.csv)
Columns include:
ticker- Stock symbolcompany_name- Company namecurrency- Currency (USD, CAD, etc.)purchase_price- Your purchase pricecurrent_price- Current stock price (converted to your currency)target_low,target_mean,target_median,target_high- Analyst targets (converted to your currency)current_price_diff_pct-(Current - Purchase) / Current * 100- Shows your gain/loss percentage
target_mean_diff_pct-(Current - Target Mean) / Target Mean * 100- Positive = Current above target → Consider selling
- Negative = Current below target → Upside potential
target_median_diff_pct-(Current - Target Median) / Target Median * 100- Positive = Current above target → Consider selling
- Negative = Current below target → Upside potential
strong_buy,buy,hold,sell,strong_sell- Recommendation countstotal_opinions- Total analyst recommendationsmarket_cap- Market capitalization
============================================================
STEP 4: Analyzing Portfolio
============================================================
AAPL - Apple Inc [USD]
Purchase Price: USD $150.00
Current Price: USD $175.50
Target Range: USD $180.00 - $200.00 - $220.00
Target Median: USD $200.00
Current Price Diff %: +14.53%
Target Mean Diff %: -12.25%
Target Median Diff %: -12.25%
Analyst Opinions: 35 total (Buy: 28, Hold: 6, Sell: 1)
Interpretation:
- Current Price Diff %: +14.53% means you're up 14.53% from your purchase price
- Target Mean Diff %: -12.25% means current price is 12.25% BELOW the analyst mean target (upside potential)
- Negative Target Diff % suggests holding for more upside
Strategy: By Sell Count (then Price vs Target %)
------------------------------------------------------------
✓ Applied sorting strategy: By Sell Count (then Price vs Target %)
✓ Saved to: output_results/2025-11-03/by_sell_then_price_gap.csv
✓ Total stocks: 150
Top 10 Results:
ticker company_name current_price target_low total_sell total_buy price_vs_target_pct
PG Procter & Gamble 148.60 148.00 0 14 0.40
MA Mastercard 545.50 520.00 0 28 4.67
AMZN Amazon 254.40 240.00 0 65 5.66
...
============================================================
ANALYZING TOP 10 COMMON TICKERS
============================================================
Top 10 tickers per strategy:
by_sell_then_buy:
AMZN, MA, MSFT, PG
by_sell_then_price_gap:
AMZN, MA, MSFT, PG
by_sell_then_market_cap:
AMZN, MA, MSFT, PG
============================================================
✓ Found 4 ticker(s) in TOP 10 of ALL strategies:
============================================================
Detailed Information:
ticker company_name current_price target_low total_sell total_buy price_vs_target_pct
AMZN Amazon 254.40 240.00 0 65 5.66
MSFT Microsoft 518.23 483.00 0 57 6.80
MA Mastercard 545.50 520.00 0 28 4.67
PG Procter & Gamble 148.60 148.00 0 14 0.40
✓ Saved common tickers to: output_results/2025-11-03/top_10_common_all_strategies.csv
The system is designed to be extensible. To add new sorting strategies:
- Edit
src/sorting_strategies.py - Add a new entry to the
SORTING_STRATEGIESdictionary:
'by_custom_logic': {
'name': 'Your Strategy Name',
'description': 'What this strategy does',
'sort_by': [
('column_name', True), # True = ascending, False = descending
('another_column', False),
]
}- Run
python main.py- your new strategy will automatically be applied!
- This tool uses
yfinancewhich unofficially scrapes Yahoo Finance data - Suitable for personal research and educational purposes
- May break if Yahoo Finance changes their website structure
- For production use, consider official APIs (Alpha Vantage, IEX Cloud, Polygon)
- Data fetching can take several minutes depending on number of tickers
MIT License