openclawversion unknown

Finance News & Portfolio Tracker

kesslerio@kesslerio⭐ 16 stars· last commit 8d ago· 6 open issues

Market news briefings with AI summaries and price alerts. Aggregates headlines from US/Europe/Japan markets. Use when: 'stock news', 'market updates', 'morning briefing', 'evening market wrap', 'financial headlines', 'price alerts', 'what happened in the market'. Supports WhatsApp delivery and English/German output. NOT for fundamental analysis or scoring (use equity-research). NOT for raw financial data queries (use openbb).

Choose how to use this skill

You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.

1. Native installer

This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.

Do not guess an installer command or replace an existing version without reviewing the diff.

2. Complete package recommended

Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.

No complete ProSkills package is published for this listing yet.

3. Prompt-only

Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.

Need only the instruction file?

Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.

No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.

7.6/10
Verified
Mar 9, 2026

// RATINGS

⭐GitHub Stars
⭐⭐ 16 on GitHubGitHub ↗

Growing

🟢ProSkills ScoreAI Verified
7.6/10
📍

Not yet listed on ClawHub or SkillsMP

// README

Finance News Skill for OpenClaw

AI-powered market news briefings with configurable language output and automated delivery.

Features

  • Multi-source aggregation: Reuters, WSJ, FT, Bloomberg, CNBC, Yahoo Finance, Tagesschau, Handelsblatt
  • Global markets: US (S&P, Dow, NASDAQ), Europe (DAX, STOXX, FTSE), Japan (Nikkei)
  • AI summaries: LLM-powered analysis in German or English
  • Automated briefings: Morning (market open) and evening (market close)
  • WhatsApp/Telegram delivery: Send briefings via openclaw
  • Portfolio tracking: Personalized news for your stocks with price alerts
  • Lobster workflows: Approval gates before sending

Quick Start

Docker (Recommended)

# Build the Docker image
docker build -t finance-news-briefing .

# Generate a briefing
docker run --rm -v "$PWD/config:/app/config:ro" \
  finance-news-briefing python3 scripts/briefing.py \
  --time morning --lang de --json --fast

If you change ranking, attribution, or source-quality logic, rebuild the image before smoke tests so cron-style runs do not use stale code.

Lobster Workflow

# Set required environment variables
export FINANCE_NEWS_TARGET="[email protected]"  # WhatsApp JID or Telegram chat ID
export FINANCE_NEWS_CHANNEL="whatsapp"            # or "telegram"

# Run workflow (halts for approval before sending)
lobster run workflows/briefing.yaml --args-json '{"time":"morning","lang":"de"}'

CLI (Legacy)

# Generate a briefing
finance-news briefing --morning --lang de

# Use fast mode + deadline (recommended)
finance-news briefing --morning --lang de --fast --deadline 300

Environment Variables

VariableDescriptionExample
FINANCE_NEWS_TARGETDelivery target (WhatsApp JID, group name, or Telegram chat ID)Required
FINANCE_NEWS_CHANNELDelivery channelwhatsapp or telegram
KALLIOPE_SERVING_API_KEYBearer token for the scheduled Kalliope Ornith route (required)Required
FINANCE_NEWS_ORNITH_BASE_URLScheduled Kalliope route base URLhttp://100.124.155.99:4000/v1
FINANCE_NEWS_ORNITH_MODELScheduled model; non-Ornith values are rejectedornith-1.5:35b-medium
FINANCE_NEWS_DS4_BASE_URLDS4 route base URL (manual writer override / deep-research primary)http://100.120.26.16:8888/v1
FINANCE_NEWS_DS4_MODELDS4 modeldeepseek-v4-flash-0731
FINANCE_NEWS_DS4_API_KEYOptional bearer token for the DS4 route(unset)
SKILL_DIRPath to skill directory (for Lobster)$HOME/projects/finance-news-openclaw-skill

Summaries, headline selection, and translation use Ornith 1.5 exclusively (ornith-1.5:35b-medium on Kalliope). Legacy FINANCE_NEWS_QWEN_* variables and the qwen route value remain compatibility aliases, but a non-Ornith model value is rejected before network I/O. DS4 is available only through an explicit manual --model ds4 call. Deep research (research.py) is also an explicit CLI action and uses DS4-high as its primary. All routes are OpenAI-compatible tailnet endpoints; there is no cloud fallback.

Installation

Option 1: Docker (Recommended)

git clone https://github.com/kesslerio/finance-news-openclaw-skill.git
cd finance-news-openclaw-skill
docker build -t finance-news-briefing .

Option 2: Native Python

# Clone repository
git clone https://github.com/kesslerio/finance-news-openclaw-skill.git \
    ~/openclaw/skills/finance-news

# Create virtual environment
cd ~/openclaw/skills/finance-news
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

# Create CLI symlink
ln -sf ~/openclaw/skills/finance-news/scripts/finance-news ~/.local/bin/finance-news

Configuration

Configuration is stored in config/config.json:

  • RSS Feeds: Enable/disable news sources per region
  • Markets: Choose which indices to track
  • Delivery: WhatsApp/Telegram settings
  • Language: German (de) or English (en) output
  • Schedule: Cron times for morning/evening briefings
  • LLM: Model order preference for headlines, summaries, translations

Run the setup wizard for interactive configuration:

finance-news setup

Lobster Workflow

The skill includes a Lobster workflow (workflows/briefing.yaml) that:

  1. Generates briefing via Docker
  2. Translates portfolio headlines (German only, via openclaw)
  3. Halts for approval (shows preview)
  4. Sends macro briefing to channel
  5. Sends portfolio briefing to channel

Workflow Arguments

ArgDefaultDescription
timemorningBriefing type: morning or evening
langdeLanguage: en or de
channelenv varwhatsapp or telegram
targetenv varGroup JID/name or chat ID
fastfalseUse fast mode (shorter timeouts)

Portfolio

Manage your stock watchlist. Every reader and writer resolves one file: $PORTFOLIOS_DIR/watchlists/portfolio.csv when PORTFOLIOS_DIR is set, otherwise config/portfolio.csv. A missing or header-only file is an empty watchlist: briefings omit the portfolio section and keep the rest.

finance-news portfolio-list              # View portfolio
finance-news portfolio-add NVDA          # Add stock
finance-news portfolio-remove TSLA       # Remove stock
finance-news portfolio-import stocks.csv # Import from CSV

Portfolio briefings show:

  • Top gainers and losers from your holdings
  • Relevant news articles with translations
  • Shortened hyperlinks for easy access

Dependencies

  • Python 3.10+
  • Docker (recommended)
  • openclaw CLI (for message delivery and LLM)
  • Lobster (for workflow automation)

Optional

  • OpenBB (openbb-quote) for enhanced market data

License

Apache 2.0 - See LICENSE file for details.

Related Skills

  • task-tracker: Personal task management with daily standups

Degraded Yahoo data

Quote fetching shares a 30-second budget per briefing deadline. The yfinance fallback runs in an isolated process with a maximum 10-second batch budget; timed-out fetch process groups are terminated, including wrapper children. RSS HTTP 404 and 429 responses are skipped without retries. Available headlines and quotes remain usable; unavailable quotes are omitted rather than invented.

// HOW IT'S BUILT

TECHNOLOGY STACK

Docker
Python

This skill is built with Docker, Python., with containerization support, and includes automated tests.

// FILES

75 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.

  • SKILL.md2.9 KBdcb4628ea49cupstream ↗
    ---
    name: finance-news
    description: "Market news briefings with AI summaries and price alerts. Aggregates headlines from US/Europe/Japan markets. Use when: 'stock news', 'market updates', 'morning briefing', 'evening market wrap', 'financial headlines', 'price alerts', 'what happened in the market'. Supports WhatsApp delivery and English/German output. NOT for fundamental analysis or scoring (use equity-research). NOT for raw financial data queries (use openbb)."
    ---
    
    # Finance News Skill
    
    AI-powered market news briefings with configurable language output and automated delivery via WhatsApp/Telegram.
    
    ## First-Time Setup
    
    Run the interactive setup wizard:
    
    ```bash
    finance-news setup
    ```
    
    The wizard configures RSS feeds, markets (US/Europe/Japan/Asia), delivery channels (WhatsApp/Telegram), language (English/German), and cron schedule.
    
    Configure individual sections:
    
    ```bash
    finance-news setup --section feeds     # Just RSS feeds
    finance-news setup --section delivery  # Just delivery channels
    finance-news setup --section schedule  # Just cron schedule
    finance-news setup --reset             # Reset to defaults
    ```
    
    Verify setup completed correctly:
    
    ```bash
    finance-news config                    # Show current config
    finance-news briefing --morning        # Test a dry-run briefing
    ```
    
    ## Quick Start
    
    ```bash
    finance-news briefing --morning                                  # Morning briefing
    finance-news briefing --evening --send --group "Market Briefing" # Evening + WhatsApp
    finance-news market                                              # Market overview
    finance-news portfolio                                           # Portfolio news
    finance-news news AAPL                                           # Ticker-specific news
    ```
    
    See [COMMANDS.md](COMMANDS.md) for the full CLI reference including portfolio management, cron setup, and configuration details.
    
    ## Cron Jobs
    
    Scheduled morning/evening briefings run via `openclaw cron` — the add/verify commands (and the manual crontab fallback) live in [COMMANDS.md](COMMANDS.md) → Cron Jobs. Quick check: `openclaw cron list`.
    
    ## Integration
    
    Combine with OpenBB for detailed quotes before news:
    
    ```bash
    openbb-quote AAPL && finance-news news AAPL
    ```
    
    Run briefings via [Lobster](https://github.com/openclaw/lobster) for approval gates and resumability — see [workflows/README.md](workflows/README.md) for full documentation:
    
    ```bash
    lobster "workflows.run --file workflows/briefing.yaml"
    ```
    
    ## Troubleshooting
    
    | Issue | Fix |
    |-------|-----|
    | Briefing writer failing | Verify `KALLIOPE_SERVING_API_KEY` is set and the Kalliope Ornith route (`http://100.124.155.99:4000/v1`) is reachable; scheduled runs fail closed and do not select another model |
    | RSS feeds timing out | Check network; WSJ/Barron's may need subscription cookies; CNBC/Yahoo always work |
    | WhatsApp delivery failing | Verify group exists and bot has access; run `openclaw doctor` |
    
  • README.md6.1 KBa911f2acb94bupstream ↗
    # Finance News Skill for OpenClaw
    
    AI-powered market news briefings with configurable language output and automated delivery.
    
    ## Features
    
    - **Multi-source aggregation:** Reuters, WSJ, FT, Bloomberg, CNBC, Yahoo Finance, Tagesschau, Handelsblatt
    - **Global markets:** US (S&P, Dow, NASDAQ), Europe (DAX, STOXX, FTSE), Japan (Nikkei)
    - **AI summaries:** LLM-powered analysis in German or English
    - **Automated briefings:** Morning (market open) and evening (market close)
    - **WhatsApp/Telegram delivery:** Send briefings via openclaw
    - **Portfolio tracking:** Personalized news for your stocks with price alerts
    - **Lobster workflows:** Approval gates before sending
    
    ## Quick Start
    
    ### Docker (Recommended)
    
    ```bash
    # Build the Docker image
    docker build -t finance-news-briefing .
    
    # Generate a briefing
    docker run --rm -v "$PWD/config:/app/config:ro" \
      finance-news-briefing python3 scripts/briefing.py \
      --time morning --lang de --json --fast
    ```
    
    If you change ranking, attribution, or source-quality logic, rebuild the image before smoke tests so cron-style runs do not use stale code.
    
    ### Lobster Workflow
    
    ```bash
    # Set required environment variables
    export FINANCE_NEWS_TARGET="[email protected]"  # WhatsApp JID or Telegram chat ID
    export FINANCE_NEWS_CHANNEL="whatsapp"            # or "telegram"
    
    # Run workflow (halts for approval before sending)
    lobster run workflows/briefing.yaml --args-json '{"time":"morning","lang":"de"}'
    ```
    
    ### CLI (Legacy)
    
    ```bash
    # Generate a briefing
    finance-news briefing --morning --lang de
    
    # Use fast mode + deadline (recommended)
    finance-news briefing --morning --lang de --fast --deadline 300
    ```
    
    ## Environment Variables
    
    | Variable | Description | Example |
    |----------|-------------|---------|
    | `FINANCE_NEWS_TARGET` | Delivery target (WhatsApp JID, group name, or Telegram chat ID) | *Required* |
    | `FINANCE_NEWS_CHANNEL` | Delivery channel | `whatsapp` or `telegram` |
    | `KALLIOPE_SERVING_API_KEY` | Bearer token for the scheduled Kalliope Ornith route (required) | *Required* |
    | `FINANCE_NEWS_ORNITH_BASE_URL` | Scheduled Kalliope route base URL | `http://100.124.155.99:4000/v1` |
    | `FINANCE_NEWS_ORNITH_MODEL` | Scheduled model; non-Ornith values are rejected | `ornith-1.5:35b-medium` |
    | `FINANCE_NEWS_DS4_BASE_URL` | DS4 route base URL (manual writer override / deep-research primary) | `http://100.120.26.16:8888/v1` |
    | `FINANCE_NEWS_DS4_MODEL` | DS4 model | `deepseek-v4-flash-0731` |
    | `FINANCE_NEWS_DS4_API_KEY` | Optional bearer token for the DS4 route | *(unset)* |
    | `SKILL_DIR` | Path to skill directory (for Lobster) | `$HOME/projects/finance-news-openclaw-skill` |
    
    Summaries, headline selection, and translation use **Ornith 1.5** exclusively
    (`ornith-1.5:35b-medium` on Kalliope). Legacy `FINANCE_NEWS_QWEN_*` variables and
    the `qwen` route value remain compatibility aliases, but a non-Ornith model value
    is rejected before network I/O. DS4 is available only through an explicit manual
    `--model ds4` call. Deep research (`research.py`) is also an explicit CLI action
    and uses DS4-high as its primary. All routes are OpenAI-compatible tailnet
    endpoints; there is no cloud fallback.
    
    ## Installation
    
    ### Option 1: Docker (Recommended)
    
    ```bash
    git clone https://github.com/kesslerio/finance-news-openclaw-skill.git
    cd finance-news-openclaw-skill
    docker build -t finance-news-briefing .
    ```
    
    ### Option 2: Native Python
    
    ```bash
    # Clone repository
    git clone https://github.com/kesslerio/finance-news-openclaw-skill.git \
        ~/openclaw/skills/finance-news
    
    # Create virtual environment
    cd ~/openclaw/skills/finance-news
    python3 -m venv .venv
    source .venv/bin/activate
    pip install -r requirements.txt
    
    # Create CLI symlink
    ln -sf ~/openclaw/skills/finance-news/scripts/finance-news ~/.local/bin/finance-news
    ```
    
    ## Configuration
    
    Configuration is stored in `config/config.json`:
    
    - **RSS Feeds:** Enable/disable news sources per region
    - **Markets:** Choose which indices to track
    - **Delivery:** WhatsApp/Telegram settings
    - **Language:** German (`de`) or English (`en`) output
    - **Schedule:** Cron times for morning/evening briefings
    - **LLM:** Model order preference for headlines, summaries, translations
    
    Run the setup wizard for interactive configuration:
    
    ```bash
    finance-news setup
    ```
    
    ## Lobster Workflow
    
    The skill includes a Lobster workflow (`workflows/briefing.yaml`) that:
    
    1. **Generates** briefing via Docker
    2. **Translates** portfolio headlines (German only, via openclaw)
    3. **Halts** for approval (shows preview)
    4. **Sends** macro briefing to channel
    5. **Sends** portfolio briefing to channel
    
    ### Workflow Arguments
    
    | Arg | Default | Description |
    |-----|---------|-------------|
    | `time` | `morning` | Briefing type: `morning` or `evening` |
    | `lang` | `de` | Language: `en` or `de` |
    | `channel` | env var | `whatsapp` or `telegram` |
    | `target` | env var | Group JID/name or chat ID |
    | `fast` | `false` | Use fast mode (shorter timeouts) |
    
    ## Portfolio
    
    Manage your stock watchlist in `config/portfolio.csv`:
    
    ```bash
    finance-news portfolio-list              # View portfolio
    finance-news portfolio-add NVDA          # Add stock
    finance-news portfolio-remove TSLA       # Remove stock
    finance-news portfolio-import stocks.csv # Import from CSV
    ```
    
    Portfolio briefings show:
    - Top gainers and losers from your holdings
    - Relevant news articles with translations
    - Shortened hyperlinks for easy access
    
    ## Dependencies
    
    - Python 3.10+
    - Docker (recommended)
    - openclaw CLI (for message delivery and LLM)
    - Lobster (for workflow automation)
    
    ### Optional
    
    - OpenBB (`openbb-quote`) for enhanced market data
    
    ## License
    
    Apache 2.0 - See [LICENSE](LICENSE) file for details.
    
    ## Related Skills
    
    - **[task-tracker](https://github.com/kesslerio/task-tracker-openclaw-skill):** Personal task management with daily standups
    
    ### Degraded Yahoo data
    
    Quote fetching shares a 30-second budget per briefing deadline. The yfinance
    fallback runs in an isolated process with a maximum 10-second batch budget;
    timed-out fetch process groups are terminated, including wrapper children.
    RSS HTTP 404 and 429 responses are skipped without retries. Available headlines
    and quotes remain usable; unavailable quotes are omitted rather than invented.
    
  • tests/README.md712 B6abf41c1f6baupstream ↗
    # Unit Tests
    
    ## Setup
    
    ```bash
    # Install test dependencies
    pip install -r requirements-test.txt
    
    # Run tests
    pytest
    
    # Run with coverage
    pytest --cov=scripts --cov-report=html
    
    # Run specific test file
    pytest tests/test_portfolio.py
    ```
    
    ## Test Structure
    
    - `test_portfolio.py` - Portfolio CRUD operations
    - `test_fetch_news.py` - RSS feed parsing with mocked responses
    - `test_setup.py` - Setup wizard validation
    - `fixtures/` - Sample RSS and portfolio data
    
    ## Coverage Target
    
    60%+ coverage for core functions (portfolio, fetch_news, setup).
    
    ## Notes
    
    - Tests use `tmp_path` for file isolation
    - Network calls are mocked with `unittest.mock`
    - `pytest-mock` provides `mocker` fixture for advanced mocking
    
  • workflows/README.md3.9 KB6ebfe6951037upstream ↗
    # Lobster Workflows
    
    This directory contains [Lobster](https://github.com/openclaw/lobster) workflow definitions for the finance-news skill.
    
    ## Available Workflows
    
    ### `briefing.yaml` - Market Briefing with Approval
    
    Generates a market briefing and sends to WhatsApp with an approval gate.
    
    **Usage:**
    ```bash
    # Run via Lobster CLI
    lobster "workflows.run --file ~/projects/finance-news-openclaw-skill/workflows/briefing.yaml"
    
    # With custom args
    lobster "workflows.run --file workflows/briefing.yaml --args-json '{\"time\":\"evening\",\"lang\":\"en\"}'"
    ```
    
    **Arguments:**
    | Arg | Default | Description |
    |-----|---------|-------------|
    | `time` | `morning` | Briefing type: `morning` or `evening` |
    | `lang` | `de` | Language: `en` or `de` |
    | `channel` | `whatsapp` | Delivery channel: `whatsapp` or `telegram` |
    | `target` | env var | Group name, JID, phone number, or Telegram chat ID |
    | `fast` | `false` | Use fast mode (shorter timeouts) |
    
    **Environment Variables:**
    | Variable | Description |
    |----------|-------------|
    | `FINANCE_NEWS_CHANNEL` | Default channel: `whatsapp` or `telegram` |
    | `FINANCE_NEWS_TARGET` | Default target (group name, phone, chat ID) |
    | `KALLIOPE_SERVING_API_KEY` | Bearer token for the scheduled Kalliope Ornith route (required inside Docker) |
    | `FINANCE_NEWS_ORNITH_BASE_URL` | Override the scheduled Kalliope route base URL (default `http://100.124.155.99:4000/v1`) |
    | `FINANCE_NEWS_ORNITH_MODEL` | Override the scheduled Ornith model (default `ornith-1.5:35b-medium`; non-Ornith values are rejected) |
    
    The briefing workflows do not pass DS4 configuration into their containers.
    DS4 remains available only through an explicit manual CLI call.
    
    **Examples:**
    ```bash
    # WhatsApp group (default)
    lobster "workflows.run --file workflows/briefing.yaml"
    
    # Telegram group
    lobster "workflows.run --file workflows/briefing.yaml --args-json '{\"channel\":\"telegram\",\"target\":\"-1001234567890\"}'"
    
    # WhatsApp DM to phone number
    lobster "workflows.run --file workflows/briefing.yaml --args-json '{\"target\":\"+15551234567\"}'"
    
    # Telegram DM to user
    lobster "workflows.run --file workflows/briefing.yaml --args-json '{\"channel\":\"telegram\",\"target\":\"@username\"}'"
    ```
    
    **Flow:**
    1. **Generate** - Runs Docker container to produce briefing JSON
    2. **Approve** - Halts for human review (shows briefing preview)
    3. **Send** - Delivers to channel (WhatsApp/Telegram) after approval
    
    **Requirements:**
    - Docker with `finance-news-briefing` image built
    - `jq` for JSON parsing
    - `openclaw` CLI for message delivery
    
    ## Adding to Lobster Registry
    
    To make these workflows available as named workflows in Lobster:
    
    ```typescript
    // In lobster/src/workflows/registry.ts
    export const workflowRegistry = {
      // ... existing workflows
      'finance.briefing': {
        name: 'finance.briefing',
        description: 'Generate market briefing with approval gate for WhatsApp/Telegram',
        argsSchema: {
          type: 'object',
          properties: {
            time: { type: 'string', enum: ['morning', 'evening'], default: 'morning' },
            lang: { type: 'string', enum: ['en', 'de'], default: 'de' },
            channel: { type: 'string', enum: ['whatsapp', 'telegram'], default: 'whatsapp' },
            target: { type: 'string', description: 'Group name, JID, phone, or chat ID' },
            fast: { type: 'boolean', default: false },
          },
        },
        examples: [
          { args: { time: 'morning', lang: 'de' }, description: 'German morning briefing to WhatsApp' },
          { args: { channel: 'telegram', target: '-1001234567890' }, description: 'Send to Telegram group' },
        ],
        sideEffects: ['message.send'],
      },
    };
    ```
    
    ## Why Lobster?
    
    Using Lobster instead of direct cron execution provides:
    
    - **Approval gates** - Review briefing before it's sent
    - **Resumability** - If interrupted, continue from last step
    - **Token efficiency** - One workflow call vs. multiple LLM tool calls
    - **Determinism** - Same inputs = same outputs
    
  • scripts/_openbb_common.sh1.1 KB41dc6d72723dupstream ↗
    #!/usr/bin/env bash
    set -euo pipefail
    
    resolve_openbb_python() {
        if [[ -n "${OPENBB_PYTHON:-}" ]]; then
            if [[ -x "${OPENBB_PYTHON}" ]]; then
                printf "%s\n" "${OPENBB_PYTHON}"
                return 0
            fi
            echo "OPENBB_PYTHON is set but not executable: ${OPENBB_PYTHON}" >&2
            return 1
        fi
    
        local venv_python="${HOME}/.local/venvs/openbb/bin/python3"
        if [[ -x "${venv_python}" ]]; then
            printf "%s\n" "${venv_python}"
            return 0
        fi
    
        if command -v python3 >/dev/null 2>&1; then
            command -v python3
            return 0
        fi
    
        echo "No usable python3 found for OpenBB wrappers." >&2
        return 1
    }
    
    resolve_openbb_provider() {
        local explicit="${1:-}"
        local fallback="${2:-yfinance}"
        if [[ -n "${explicit}" ]]; then
            printf "%s\n" "${explicit}"
        elif [[ -n "${OPENBB_DEFAULT_PROVIDER:-}" ]]; then
            printf "%s\n" "${OPENBB_DEFAULT_PROVIDER}"
        else
            printf "%s\n" "${fallback}"
        fi
    }
    
    run_openbb_python() {
        local script=""
        script="$(cat)"
        local py=""
        py="$(resolve_openbb_python)" || return 1
        "${py}" 2>&1 <<<"${script}"
    }
    
  • scripts/alerts.py16 KBf14b4e91d7ecupstream ↗
    #!/usr/bin/env python3
    """
    Price Target Alerts - Track buy zone alerts for stocks.
    
    Features:
    - Set price target alerts (buy zone triggers)
    - Check alerts against current prices
    - Snooze, update, delete alerts
    - Multi-currency support (USD, EUR, JPY, SGD, MXN)
    
    Usage:
        alerts.py list                           # Show all alerts
        alerts.py set CRWD 400 --note 'Kaufzone' # Set alert
        alerts.py check                          # Check triggered alerts
        alerts.py delete CRWD                    # Delete alert
        alerts.py snooze CRWD --days 7           # Snooze for 7 days
        alerts.py update CRWD 380                # Update target price
    """
    
    import argparse
    import json
    import sys
    from datetime import datetime, timedelta
    from pathlib import Path
    
    from utils import ensure_venv
    
    ensure_venv()
    
    # Lazy import to avoid numpy issues at module load
    fetch_market_data = None
    
    def get_fetch_market_data():
        global fetch_market_data
        if fetch_market_data is None:
            from fetch_news import fetch_market_data as fmd
            fetch_market_data = fmd
        return fetch_market_data
    
    SCRIPT_DIR = Path(__file__).parent
    CONFIG_DIR = SCRIPT_DIR.parent / "config"
    ALERTS_FILE = CONFIG_DIR / "alerts.json"
    
    SUPPORTED_CURRENCIES = ["USD", "EUR", "JPY", "SGD", "MXN"]
    
    
    def load_alerts() -> dict:
        """Load alerts from JSON file."""
        if not ALERTS_FILE.exists():
            return {"_meta": {"version": 1, "supported_currencies": SUPPORTED_CURRENCIES}, "alerts": []}
        return json.loads(ALERTS_FILE.read_text())
    
    
    def save_alerts(data: dict) -> None:
        """Save alerts to JSON file."""
        data["_meta"]["updated_at"] = datetime.now().isoformat()
        ALERTS_FILE.write_text(json.dumps(data, indent=2))
    
    
    def get_alert_by_ticker(alerts: list, ticker: str) -> dict | None:
        """Find alert by ticker."""
        ticker = ticker.upper()
        for alert in alerts:
            if alert["ticker"] == ticker:
                return alert
        return None
    
    
    def format_price(price: float, currency: str) -> str:
        """Format price with currency symbol."""
        symbols = {"USD": "$", "EUR": "€", "JPY": "¥", "SGD": "S$", "MXN": "MX$"}
        symbol = symbols.get(currency, currency + " ")
        if currency == "JPY":
            return f"{symbol}{price:,.0f}"
        return f"{symbol}{price:,.2f}"
    
    
    def cmd_list(args) -> None:
        """List all alerts."""
        data = load_alerts()
        alerts = data.get("alerts", [])
        
        if not alerts:
            print("📭 No price alerts set")
            return
        
        print(f"📊 Price Alerts ({len(alerts)} total)\n")
        
        now = datetime.now()
        active = []
        snoozed = []
        
        for alert in alerts:
            snooze_until = alert.get("snooze_until")
            if snooze_until and datetime.fromisoformat(snooze_until) > now:
                snoozed.append(alert)
            else:
                active.append(alert)
        
        if active:
            print("### Active Alerts")
            for a in active:
                target = format_price(a["target_price"], a.get("currency", "USD"))
                note = f' — "{a["note"]}"' if a.get("note") else ""
                user = f" (by {a['set_by']})" if a.get("set_by") else ""
                print(f"  • {a['ticker']}: {target}{note}{user}")
            print()
        
        if snoozed:
            print("### Snoozed")
            for a in snoozed:
                target = format_price(a["target_price"], a.get("currency", "USD"))
                until = datetime.fromisoformat(a["snooze_until"]).strftime("%Y-%m-%d")
                print(f"  • {a['ticker']}: {target} (until {until})")
            print()
    
    
    def cmd_set(args) -> None:
        """Set a new alert."""
        data = load_alerts()
        alerts = data.get("alerts", [])
        ticker = args.ticker.upper()
        
        # Check if alert exists
        existing = get_alert_by_ticker(alerts, ticker)
        if existing:
            print(f"⚠️ Alert for {ticker} already exists. Use 'update' to change target.")
            return
        
        # Validate target price
        if args.target <= 0:
            print(f"❌ Target price must be greater than 0")
            return
        
        currency = args.currency.upper() if args.currency else "USD"
        if currency not in SUPPORTED_CURRENCIES:
            print(f"❌ Currency {currency} not supported. Use: {', '.join(SUPPORTED_CURRENCIES)}")
            return
        
        # Warn about currency mismatch based on ticker suffix
        ticker_currency_map = {
            ".T": "JPY",      # Tokyo
            ".SI": "SGD",     # Singapore
            ".MX": "MXN",     # Mexico
            ".DE": "EUR", ".F": "EUR", ".PA": "EUR",  # Europe
        }
        expected_currency = "USD"  # Default for US stocks
        for suffix, curr in ticker_currency_map.items():
            if ticker.endswith(suffix):
                expected_currency = curr
                break
        
        if currency != expected_currency:
            print(f"⚠️ Warning: {ticker} trades in {expected_currency}, but alert set in {currency}")
        
        # Fetch current price (optional - may fail if numpy broken)
        current_price = None
        try:
            quotes = get_fetch_market_data()([ticker], timeout=10)
            if ticker in quotes and quotes[ticker].get("price"):
                current_price = quotes[ticker]["price"]
        except Exception as e:
            print(f"⚠️ Could not fetch current price: {e}", file=sys.stderr)
        
        alert = {
            "ticker": ticker,
            "target_price": args.target,
            "currency": currency,
            "note": args.note or "",
            "set_by": args.user or "",
            "set_date": datetime.now().strftime("%Y-%m-%d"),
            "status": "active",
            "snooze_until": None,
            "triggered_count": 0,
            "last_triggered": None,
        }
        
        alerts.append(alert)
        data["alerts"] = alerts
        save_alerts(data)
        
        target_str = format_price(args.target, currency)
        print(f"✅ Alert set: {ticker} under {target_str}")
        if current_price:
            pct_diff = ((current_price - args.target) / current_price) * 100
            current_str = format_price(current_price, currency)
            print(f"   Current: {current_str} ({pct_diff:+.1f}% to target)")
    
    
    def cmd_delete(args) -> None:
        """Delete an alert."""
        data = load_alerts()
        alerts = data.get("alerts", [])
        ticker = args.ticker.upper()
        
        new_alerts = [a for a in alerts if a["ticker"] != ticker]
        if len(new_alerts) == len(alerts):
            print(f"❌ No alert found for {ticker}")
            return
        
        data["alerts"] = new_alerts
        save_alerts(data)
        print(f"🗑️ Alert deleted: {ticker}")
    
    
    def cmd_snooze(args) -> None:
        """Snooze an alert."""
        data = load_alerts()
        alerts = data.get("alerts", [])
        ticker = args.ticker.upper()
        
        alert = get_alert_by_ticker(alerts, ticker)
        if not alert:
            print(f"❌ No alert found for {ticker}")
            return
        
        days = args.days or 7
        snooze_until = datetime.now() + timedelta(days=days)
        alert["snooze_until"] = snooze_until.isoformat()
        save_alerts(data)
        print(f"😴 Alert snoozed: {ticker} until {snooze_until.strftime('%Y-%m-%d')}")
    
    
    def cmd_update(args) -> None:
        """Update alert target price."""
        data = load_alerts()
        alerts = data.get("alerts", [])
        ticker = args.ticker.upper()
        
        alert = get_alert_by_ticker(alerts, ticker)
        if not alert:
            print(f"❌ No alert found for {ticker}")
            return
        
        # Validate target price
        if args.target <= 0:
            print(f"❌ Target price must be greater than 0")
            return
        
        old_target = alert["target_price"]
        alert["target_price"] = args.target
        if args.note:
            alert["note"] = args.note
        save_alerts(data)
        
        currency = alert.get("currency", "USD")
        old_str = format_price(old_target, currency)
        new_str = format_price(args.target, currency)
        print(f"✏️ Alert updated: {ticker} {old_str} → {new_str}")
    
    
    def cmd_check(args) -> None:
        """Check alerts against current prices."""
        data = load_alerts()
        alerts = data.get("alerts", [])
        
        if not alerts:
            if args.json:
                print(json.dumps({"triggered": [], "watching": []}))
            else:
                print("📭 No alerts to check")
            return
        
        now = datetime.now()
        active_alerts = []
        for alert in alerts:
            snooze_until = alert.get("snooze_until")
            if snooze_until and datetime.fromisoformat(snooze_until) > now:
                continue
            active_alerts.append(alert)
        
        if not active_alerts:
            if args.json:
                print(json.dumps({"triggered": [], "watching": []}))
            else:
                print("📭 All alerts snoozed")
            return
        
        # Fetch prices for all active alerts
        tickers = [a["ticker"] for a in active_alerts]
        quotes = get_fetch_market_data()(tickers, timeout=30)
        
        triggered = []
        watching = []
        
        for alert in active_alerts:
            ticker = alert["ticker"]
            target = alert["target_price"]
            currency = alert.get("currency", "USD")
            
            quote = quotes.get(ticker, {})
            price = quote.get("price")
            
            if price is None:
                continue
            
            # Divide-by-zero protection
            if target == 0:
                pct_diff = 0
            else:
                pct_diff = ((price - target) / target) * 100
            
            result = {
                "ticker": ticker,
                "target_price": target,
                "current_price": price,
                "currency": currency,
                "pct_from_target": round(pct_diff, 2),
                "note": alert.get("note", ""),
                "set_by": alert.get("set_by", ""),
            }
            
            if price <= target:
                triggered.append(result)
                # Update triggered count (only once per day to avoid inflation)
                last_triggered = alert.get("last_triggered")
                today = now.strftime("%Y-%m-%d")
                if not last_triggered or not last_triggered.startswith(today):
                    alert["triggered_count"] = alert.get("triggered_count", 0) + 1
                alert["last_triggered"] = now.isoformat()
            else:
                watching.append(result)
        
        save_alerts(data)
        
        if args.json:
            print(json.dumps({"triggered": triggered, "watching": watching}, indent=2))
            return
    
        # Translations
        lang = getattr(args, 'lang', 'en')
        if lang == "de":
            labels = {
                "title": "PREISWARNUNGEN",
                "in_zone": "IN KAUFZONE",
                "buy": "KAUFEN!",
                "target": "Ziel",
                "watching": "BEOBACHTUNG",
                "to_target": "noch",
                "no_data": "Keine Preisdaten für Alerts verfügbar",
            }
        else:
            labels = {
                "title": "PRICE ALERTS",
                "in_zone": "IN BUY ZONE",
                "buy": "BUY SIGNAL",
                "target": "target",
                "watching": "WATCHING",
                "to_target": "to target",
                "no_data": "No price data available for alerts",
            }
    
        # Date header
        date_str = datetime.now().strftime("%b %d, %Y") if lang == "en" else datetime.now().strftime("%d. %b %Y")
        print(f"📊 {labels['title']} — {date_str}\n")
    
        # Human-readable output
        if triggered:
            print(f"🟢 {labels['in_zone']}:\n")
            for t in triggered:
                target_str = format_price(t["target_price"], t["currency"])
                current_str = format_price(t["current_price"], t["currency"])
                note = f'\n   "{t["note"]}"' if t.get("note") else ""
                user = f" — {t['set_by']}" if t.get("set_by") else ""
                print(f"• {t['ticker']}: {current_str} ({labels['target']}: {target_str}) ← {labels['buy']}{note}{user}")
            print()
    
        if watching:
            print(f"⏳ {labels['watching']}:\n")
            for w in sorted(watching, key=lambda x: x["pct_from_target"]):
                target_str = format_price(w["target_price"], w["currency"])
                current_str = format_price(w["current_price"], w["currency"])
                print(f"• {w['ticker']}: {current_str} ({labels['target']}: {target_str}) — {labels['to_target']} {abs(w['pct_from_target']):.1f}%")
            print()
    
        if not triggered and not watching:
            print(f"📭 {labels['no_data']}")
    
    
    def check_alerts() -> dict:
        """
        Check alerts and return results for briefing integration.
        Returns: {"triggered": [...], "watching": [...]}
        """
        data = load_alerts()
        alerts = data.get("alerts", [])
        
        if not alerts:
            return {"triggered": [], "watching": []}
        
        now = datetime.now()
        active_alerts = [
            a for a in alerts
            if not a.get("snooze_until") or datetime.fromisoformat(a["snooze_until"]) <= now
        ]
        
        if not active_alerts:
            return {"triggered": [], "watching": []}
        
        tickers = [a["ticker"] for a in active_alerts]
        quotes = get_fetch_market_data()(tickers, timeout=30)
        
        triggered = []
        watching = []
        
        for alert in active_alerts:
            ticker = alert["ticker"]
            target = alert["target_price"]
            currency = alert.get("currency", "USD")
            
            quote = quotes.get(ticker, {})
            price = quote.get("price")
            
            if price is None:
                continue
            
            # Divide-by-zero protection
            if target == 0:
                pct_diff = 0
            else:
                pct_diff = ((price - target) / target) * 100
            
            result = {
                "ticker": ticker,
                "target_price": target,
                "current_price": price,
                "currency": currency,
                "pct_from_target": round(pct_diff, 2),
                "note": alert.get("note", ""),
                "set_by": alert.get("set_by", ""),
            }
            
            if price <= target:
                triggered.append(result)
                # Update triggered count (only once per day to avoid inflation)
                last_triggered = alert.get("last_triggered")
                today = now.strftime("%Y-%m-%d")
                if not last_triggered or not last_triggered.startswith(today):
                    alert["triggered_count"] = alert.get("triggered_count", 0) + 1
                alert["last_triggered"] = now.isoformat()
            else:
                watching.append(result)
        
        save_alerts(data)
        return {"triggered": triggered, "watching": watching}
    
    
    def main():
        parser = argparse.ArgumentParser(description="Price target alerts")
        subparsers = parser.add_subparsers(dest="command", required=True)
        
        # list
        subparsers.add_parser("list", help="List all alerts")
        
        # set
        set_parser = subparsers.add_parser("set", help="Set new alert")
        set_parser.add_argument("ticker", help="Stock ticker")
        set_parser.add_argument("target", type=float, help="Target price")
        set_parser.add_argument("--note", help="Note/reason")
        set_parser.add_argument("--user", help="Who set the alert")
        set_parser.add_argument("--currency", default="USD", help="Currency (USD, EUR, JPY, SGD, MXN)")
        
        # delete
        del_parser = subparsers.add_parser("delete", help="Delete alert")
        del_parser.add_argument("ticker", help="Stock ticker")
        
        # snooze
        snooze_parser = subparsers.add_parser("snooze", help="Snooze alert")
        snooze_parser.add_argument("ticker", help="Stock ticker")
        snooze_parser.add_argument("--days", type=int, default=7, help="Days to snooze")
        
        # update
        update_parser = subparsers.add_parser("update", help="Update alert target")
        update_parser.add_argument("ticker", help="Stock ticker")
        update_parser.add_argument("target", type=float, help="New target price")
        update_parser.add_argument("--note", help="Update note")
        
        # check
        check_parser = subparsers.add_parser("check", help="Check alerts against prices")
        check_parser.add_argument("--json", action="store_true", help="JSON output")
        check_parser.add_argument("--lang", default="en", help="Output language (en, de)")
        
        args = parser.parse_args()
        
        if args.command == "list":
            cmd_list(args)
        elif args.command == "set":
            cmd_set(args)
        elif args.command == "delete":
            cmd_delete(args)
        elif args.command == "snooze":
            cmd_snooze(args)
        elif args.command == "update":
            cmd_update(args)
        elif args.command == "check":
            cmd_check(args)
    
    
    if __name__ == "__main__":
        main()
    
  • scripts/briefing.py5.6 KB1965ff4bbc4cupstream ↗
    #!/usr/bin/env python3
    """
    Briefing Generator - Main entry point for market briefings.
    Generates and optionally sends to WhatsApp group.
    """
    
    import argparse
    import json
    import os
    import subprocess
    import sys
    from datetime import datetime
    from pathlib import Path
    
    from utils import ensure_venv
    
    SCRIPT_DIR = Path(__file__).parent
    
    ensure_venv()
    
    
    def send_to_whatsapp(message: str, group_name: str | None = None):
        """Send message to WhatsApp group via openclaw message tool."""
        if not group_name:
            group_name = os.environ.get('FINANCE_NEWS_TARGET', '')
        if not group_name:
            print("❌ No target specified. Set FINANCE_NEWS_TARGET env var or use --group", file=sys.stderr)
            return False
        # Use openclaw message tool
        try:
            result = subprocess.run(
                [
                    'openclaw', 'message', 'send',
                    '--channel', 'whatsapp',
                    '--target', group_name,
                    '--message', message
                ],
                capture_output=True,
                text=True,
                timeout=30
            )
            
            if result.returncode == 0:
                print(f"✅ Sent to WhatsApp group: {group_name}", file=sys.stderr)
                return True
            else:
                print(f"⚠️ WhatsApp send failed: {result.stderr}", file=sys.stderr)
                return False
        
        except Exception as e:
            print(f"❌ WhatsApp error: {e}", file=sys.stderr)
            return False
    
    
    def generate_and_send(args):
        """Generate briefing and optionally send to WhatsApp."""
        
        # Determine briefing type based on current time or args
        if args.time:
            briefing_time = args.time
        else:
            hour = datetime.now().hour
            briefing_time = 'morning' if hour < 12 else 'evening'
        
        # Generate the briefing
        cmd = [
            sys.executable, SCRIPT_DIR / 'summarize.py',
            '--time', briefing_time,
            '--style', args.style,
            '--lang', args.lang
        ]
    
        if args.deadline is not None:
            cmd.extend(['--deadline', str(args.deadline)])
    
        if args.fast:
            cmd.append('--fast')
    
        force_llm = bool(args.llm or args.style == 'briefing')
        if force_llm:
            cmd.append('--llm')
        cmd.extend(['--model', args.model])
    
        if args.debug:
            cmd.append('--debug')
        
        # Always use JSON for internal processing to handle splits
        cmd.append('--json')
        
        print(f"📊 Generating {briefing_time} briefing...", file=sys.stderr)
        
        timeout = args.deadline if args.deadline is not None else 300
        timeout = max(1, int(timeout))
        if args.deadline is not None:
            timeout = timeout + 5
        result = subprocess.run(
            cmd,
            stdout=subprocess.PIPE,
            stderr=None,
            text=True,
            stdin=subprocess.DEVNULL,
            timeout=timeout
        )
        
        if result.returncode != 0:
            print("❌ Briefing generation failed", file=sys.stderr)
            sys.exit(1)
        
        try:
            data = json.loads(result.stdout.strip())
        except json.JSONDecodeError:
            # Fallback if not JSON (shouldn't happen with --json)
            print(f"⚠️ Failed to parse briefing JSON", file=sys.stderr)
            print(result.stdout)
            return result.stdout
    
        # Output handling
        if args.json:
            print(json.dumps(data, indent=2))
        else:
            # Print for humans
            if data.get('macro_message'):
                 print(data['macro_message'])
            if data.get('portfolio_message'):
                 print("\n" + "="*20 + "\n")
                 print(data['portfolio_message'])
        
        # Send to WhatsApp if requested
        if args.send and args.group:
            # Message 1: Macro
            macro_msg = data.get('macro_message') or data.get('summary', '')
            if macro_msg:
                send_to_whatsapp(macro_msg, args.group)
            
            # Message 2: Portfolio (if exists)
            portfolio_msg = data.get('portfolio_message')
            if portfolio_msg:
                send_to_whatsapp(portfolio_msg, args.group)
                
        return data.get('macro_message', '')
    
    
    def main():
        parser = argparse.ArgumentParser(description='Briefing Generator')
        parser.add_argument('--time', choices=['morning', 'evening'],
                            help='Briefing type (auto-detected if not specified)')
        parser.add_argument('--style', choices=['briefing', 'analysis', 'headlines'],
                            default='briefing', help='Summary style')
        parser.add_argument('--lang', choices=['de', 'en'], default='en',
                            help='Output language')
        parser.add_argument('--send', action='store_true',
                            help='Send to WhatsApp group')
        parser.add_argument('--group', default=os.environ.get('FINANCE_NEWS_TARGET', ''),
                            help='WhatsApp group name or JID (default: FINANCE_NEWS_TARGET env var)')
        parser.add_argument('--json', action='store_true',
                            help='Output as JSON')
        parser.add_argument('--deadline', type=int, default=None,
                            help='Overall deadline in seconds')
        parser.add_argument('--llm', action='store_true', help='Force LLM summary for non-briefing styles')
        parser.add_argument('--model', choices=['ornith', 'qwen', 'ds4'],
                            default='ornith',
                            help='Writer route (ornith; qwen is a legacy alias; ds4 is manual-only)')
        parser.add_argument('--fast', action='store_true',
                            help='Use fast mode (shorter timeouts, fewer items)')
        parser.add_argument('--debug', action='store_true',
                            help='Write debug log with sources')
        
        args = parser.parse_args()
        generate_and_send(args)
    
    
    if __name__ == '__main__':
        main()
    
  • scripts/earnings.py21 KB02db633804fcupstream ↗
    #!/usr/bin/env python3
    """
    Earnings Calendar - Track earnings dates for portfolio stocks.
    
    Features:
    - Fetch earnings dates from FMP API
    - Show upcoming earnings in daily briefing
    - Alert 24h before earnings release
    - Cache results to avoid API spam
    
    Usage:
        earnings.py list              # Show all upcoming earnings
        earnings.py check             # Check what's reporting today/this week
        earnings.py refresh           # Force refresh earnings data
    """
    
    import argparse
    import csv
    import json
    import os
    import shutil
    import subprocess
    import sys
    from datetime import datetime, timedelta
    from pathlib import Path
    from urllib.request import urlopen, Request
    from urllib.error import URLError, HTTPError
    
    # Paths
    SCRIPT_DIR = Path(__file__).parent
    CONFIG_DIR = SCRIPT_DIR.parent / "config"
    CACHE_DIR = SCRIPT_DIR.parent / "cache"
    
    
    def _get_portfolio_file() -> Path:
        """Get portfolio CSV path with PORTFOLIOS_DIR env var support.
    
        Priority:
        1. Shared location ($PORTFOLIOS_DIR/watchlists/portfolio.csv) if env var set
        2. Legacy config/portfolio.csv (backward compatibility)
        """
        env_dir = os.environ.get("PORTFOLIOS_DIR", "").strip()
        if env_dir:
            # If env var is set, always use shared path (even if file doesn't exist yet)
            return Path(os.path.expanduser(env_dir)) / "watchlists" / "portfolio.csv"
        # Fallback to legacy path
        return CONFIG_DIR / "portfolio.csv"
    
    
    PORTFOLIO_FILE = _get_portfolio_file()
    EARNINGS_CACHE = CACHE_DIR / "earnings_calendar.json"
    MANUAL_EARNINGS = CONFIG_DIR / "manual_earnings.json"  # For JP/other stocks not in Finnhub
    
    # OpenBB binary path
    OPENBB_BINARY = None
    try:
        env_path = os.environ.get('OPENBB_QUOTE_BIN')
        if env_path and os.path.isfile(env_path) and os.access(env_path, os.X_OK):
            OPENBB_BINARY = env_path
        else:
            OPENBB_BINARY = shutil.which('openbb-quote')
    except Exception:
        pass
    
    # API Keys
    def get_fmp_key() -> str:
        """Get FMP API key from environment or .env file."""
        key = os.environ.get("FMP_API_KEY", "")
        if not key:
            env_file = Path.home() / ".openclaw" / ".env"
            if env_file.exists():
                for line in env_file.read_text().splitlines():
                    if line.startswith("FMP_API_KEY="):
                        key = line.split("=", 1)[1].strip()
                        break
        return key
    
    
    def load_portfolio() -> list[dict]:
        """Load portfolio from CSV."""
        if not PORTFOLIO_FILE.exists():
            return []
        with open(PORTFOLIO_FILE, 'r') as f:
            reader = csv.DictReader(f)
            return list(reader)
    
    
    def load_earnings_cache() -> dict:
        """Load cached earnings data."""
        if EARNINGS_CACHE.exists():
            try:
                return json.loads(EARNINGS_CACHE.read_text())
            except Exception:
                pass
        return {"last_updated": None, "earnings": {}}
    
    
    def load_manual_earnings() -> dict:
        """
        Load manually-entered earnings dates (for JP stocks not in Finnhub).
        Format: {"6857.T": {"date": "2026-01-30", "time": "amc", "note": "Q3 FY2025"}, ...}
        """
        if MANUAL_EARNINGS.exists():
            try:
                data = json.loads(MANUAL_EARNINGS.read_text())
                # Filter out metadata keys (starting with _)
                return {k: v for k, v in data.items() if not k.startswith("_") and isinstance(v, dict)}
            except Exception:
                pass
        return {}
    
    
    def save_earnings_cache(data: dict):
        """Save earnings data to cache."""
        CACHE_DIR.mkdir(exist_ok=True)
        EARNINGS_CACHE.write_text(json.dumps(data, indent=2, default=str))
    
    
    def get_finnhub_key() -> str:
        """Get Finnhub API key from environment or .env file."""
        key = os.environ.get("FINNHUB_API_KEY", "")
        if not key:
            env_file = Path.home() / ".openclaw" / ".env"
            if env_file.exists():
                for line in env_file.read_text().splitlines():
                    if line.startswith("FINNHUB_API_KEY="):
                        key = line.split("=", 1)[1].strip()
                        break
        return key
    
    
    def fetch_all_earnings_finnhub(days_ahead: int = 60) -> dict:
        """
        Fetch all earnings for the next N days from Finnhub.
        Returns dict keyed by symbol: {"AAPL": {...}, ...}
        """
        finnhub_key = get_finnhub_key()
        if not finnhub_key:
            return {}
        
        from_date = datetime.now().strftime("%Y-%m-%d")
        to_date = (datetime.now() + timedelta(days=days_ahead)).strftime("%Y-%m-%d")
        
        url = f"https://finnhub.io/api/v1/calendar/earnings?from={from_date}&to={to_date}&token={finnhub_key}"
        
        try:
            req = Request(url, headers={"User-Agent": "finance-news/1.0"})
            with urlopen(req, timeout=30) as resp:
                data = json.loads(resp.read().decode("utf-8"))
                
                earnings_by_symbol = {}
                for entry in data.get("earningsCalendar", []):
                    symbol = entry.get("symbol")
                    if symbol:
                        earnings_by_symbol[symbol] = {
                            "date": entry.get("date"),
                            "time": entry.get("hour", ""),  # bmo/amc
                            "eps_estimate": entry.get("epsEstimate"),
                            "revenue_estimate": entry.get("revenueEstimate"),
                            "quarter": entry.get("quarter"),
                            "year": entry.get("year"),
                        }
                return earnings_by_symbol
        except Exception as e:
            print(f"❌ Finnhub error: {e}", file=sys.stderr)
            return {}
    
    
    def normalize_ticker_for_lookup(ticker: str) -> list[str]:
        """
        Convert portfolio ticker to possible Finnhub symbols.
        Returns list of possible formats to try.
        """
        variants = [ticker]
        
        # Japanese stocks: 6857.T -> try 6857
        if ticker.endswith('.T'):
            base = ticker.replace('.T', '')
            variants.extend([base, f"{base}.T"])
        
        # Singapore stocks: D05.SI -> try D05
        elif ticker.endswith('.SI'):
            base = ticker.replace('.SI', '')
            variants.extend([base, f"{base}.SI"])
        
        return variants
    
    
    def fetch_earnings_for_portfolio(portfolio: list[dict]) -> dict:
        """
        Fetch earnings dates for portfolio stocks using Finnhub bulk API.
        More efficient than per-ticker calls.
        """
        # Get all earnings for next 60 days
        all_earnings = fetch_all_earnings_finnhub(days_ahead=60)
        
        if not all_earnings:
            return {}
        
        # Match portfolio tickers to earnings data
        results = {}
        for stock in portfolio:
            ticker = stock["symbol"]
            variants = normalize_ticker_for_lookup(ticker)
            
            for variant in variants:
                if variant in all_earnings:
                    results[ticker] = all_earnings[variant]
                    break
        
        return results
    
    
    def refresh_earnings(portfolio: list[dict], force: bool = False) -> dict:
        """Refresh earnings data for all portfolio stocks."""
        finnhub_key = get_finnhub_key()
        if not finnhub_key:
            print("❌ FINNHUB_API_KEY not found", file=sys.stderr)
            return {}
        
        cache = load_earnings_cache()
        
        # Check if cache is fresh (< 6 hours old)
        if not force and cache.get("last_updated"):
            try:
                last = datetime.fromisoformat(cache["last_updated"])
                if datetime.now() - last < timedelta(hours=6):
                    print(f"📦 Using cached data (updated {last.strftime('%H:%M')})")
                    return cache
            except Exception:
                pass
        
        print(f"🔄 Fetching earnings calendar from Finnhub...")
        
        # Use bulk fetch - much more efficient
        earnings = fetch_earnings_for_portfolio(portfolio)
        
        # Merge manual earnings (for JP stocks not in Finnhub)
        manual = load_manual_earnings()
        if manual:
            print(f"📝 Merging {len(manual)} manual entries...")
            for ticker, data in manual.items():
                if ticker not in earnings:  # Manual data fills gaps
                    earnings[ticker] = data
        
        found = len(earnings)
        total = len(portfolio)
        print(f"✅ Found earnings data for {found}/{total} stocks")
        
        if earnings:
            for ticker, data in sorted(earnings.items(), key=lambda x: x[1].get("date", "")):
                print(f"  • {ticker}: {data.get('date', '?')}")
        
        cache = {
            "last_updated": datetime.now().isoformat(),
            "earnings": earnings
        }
        save_earnings_cache(cache)
        
        return cache
    
    
    def list_earnings(args):
        """List all upcoming earnings for portfolio."""
        portfolio = load_portfolio()
        if not portfolio:
            print("📂 Portfolio empty")
            return
        
        cache = refresh_earnings(portfolio, force=args.refresh)
        earnings = cache.get("earnings", {})
        
        if not earnings:
            print("\n❌ No earnings dates found")
            return
        
        # Sort by date
        sorted_earnings = sorted(
            [(ticker, data) for ticker, data in earnings.items() if data.get("date")],
            key=lambda x: x[1]["date"]
        )
        
        print(f"\n📅 Upcoming Earnings ({len(sorted_earnings)} stocks)\n")
        
        today = datetime.now().date()
        
        for ticker, data in sorted_earnings:
            date_str = data["date"]
            try:
                ed = datetime.strptime(date_str, "%Y-%m-%d").date()
                days_until = (ed - today).days
                
                # Emoji based on timing
                if days_until < 0:
                    emoji = "✅"  # Past
                    timing = f"{-days_until}d ago"
                elif days_until == 0:
                    emoji = "🔴"  # Today!
                    timing = "TODAY"
                elif days_until == 1:
                    emoji = "🟡"  # Tomorrow
                    timing = "TOMORROW"
                elif days_until <= 7:
                    emoji = "🟠"  # This week
                    timing = f"in {days_until}d"
                else:
                    emoji = "⚪"  # Later
                    timing = f"in {days_until}d"
                
                # Time of day
                time_str = ""
                if data.get("time") == "bmo":
                    time_str = " (pre-market)"
                elif data.get("time") == "amc":
                    time_str = " (after-close)"
                
                # EPS estimate
                eps_str = ""
                if data.get("eps_estimate"):
                    eps_str = f" | Est: ${data['eps_estimate']:.2f}"
                
                # Stock name from portfolio
                stock_name = next((s["name"] for s in portfolio if s["symbol"] == ticker), ticker)
                
                print(f"{emoji} {date_str} ({timing}): **{ticker}** — {stock_name}{time_str}{eps_str}")
                
            except ValueError:
                print(f"⚪ {date_str}: {ticker}")
        
        print()
    
    
    def check_earnings(args):
        """Check earnings for today and this week (briefing format)."""
        portfolio = load_portfolio()
        if not portfolio:
            return
    
        cache = load_earnings_cache()
    
        # Auto-refresh if cache is stale
        if not cache.get("last_updated"):
            cache = refresh_earnings(portfolio, force=False)
        else:
            try:
                last = datetime.fromisoformat(cache["last_updated"])
                if datetime.now() - last > timedelta(hours=12):
                    cache = refresh_earnings(portfolio, force=False)
            except Exception:
                cache = refresh_earnings(portfolio, force=False)
    
        earnings = cache.get("earnings", {})
        if not earnings:
            return
    
        today = datetime.now().date()
        week_only = getattr(args, 'week', False)
    
        # For weekly mode (Sunday cron), show Mon-Fri of upcoming week
        # Calculation: weekday() returns 0=Mon, 6=Sun. (7 - weekday) % 7 gives days until next Monday.
        # Special case: if today is Monday (result=0), we want next Monday (7 days), not today.
        if week_only:
            days_until_monday = (7 - today.weekday()) % 7
            if days_until_monday == 0 and today.weekday() != 0:
                days_until_monday = 7
            week_start = today + timedelta(days=days_until_monday)
            week_end = week_start + timedelta(days=4)  # Mon-Fri
        else:
            week_end = today + timedelta(days=7)
    
        today_list = []
        week_list = []
    
        for ticker, data in earnings.items():
            if not data.get("date"):
                continue
            try:
                ed = datetime.strptime(data["date"], "%Y-%m-%d").date()
                stock = next((s for s in portfolio if s["symbol"] == ticker), None)
                name = stock["name"] if stock else ticker
                category = stock.get("category", "") if stock else ""
    
                entry = {
                    "ticker": ticker,
                    "name": name,
                    "date": ed,
                    "time": data.get("time", ""),
                    "eps_estimate": data.get("eps_estimate"),
                    "category": category,
                }
    
                if week_only:
                    # Weekly mode: only show week range
                    if week_start <= ed <= week_end:
                        week_list.append(entry)
                else:
                    # Daily mode: today + this week
                    if ed == today:
                        today_list.append(entry)
                    elif today < ed <= week_end:
                        week_list.append(entry)
            except ValueError:
                continue
        
        # Handle JSON output
        if getattr(args, 'json', False):
            if week_only:
                result = {
                    "week_start": week_start.isoformat(),
                    "week_end": week_end.isoformat(),
                    "earnings": [
                        {
                            "ticker": e["ticker"],
                            "name": e["name"],
                            "date": e["date"].isoformat(),
                            "time": e["time"],
                            "eps_estimate": e.get("eps_estimate"),
                            "category": e.get("category", ""),
                        }
                        for e in sorted(week_list, key=lambda x: x["date"])
                    ],
                }
            else:
                result = {
                    "today": [
                        {
                            "ticker": e["ticker"],
                            "name": e["name"],
                            "date": e["date"].isoformat(),
                            "time": e["time"],
                            "eps_estimate": e.get("eps_estimate"),
                            "category": e.get("category", ""),
                        }
                        for e in sorted(today_list, key=lambda x: x.get("time", "zzz"))
                    ],
                    "this_week": [
                        {
                            "ticker": e["ticker"],
                            "name": e["name"],
                            "date": e["date"].isoformat(),
                            "time": e["time"],
                            "eps_estimate": e.get("eps_estimate"),
                            "category": e.get("category", ""),
                        }
                        for e in sorted(week_list, key=lambda x: x["date"])
                    ],
                }
            print(json.dumps(result, indent=2))
            return
    
        # Translations
        lang = getattr(args, 'lang', 'en')
        if lang == "de":
            labels = {
                "today": "EARNINGS HEUTE",
                "week": "EARNINGS DIESE WOCHE",
                "week_preview": "EARNINGS NÄCHSTE WOCHE",
                "pre": "vor Börseneröffnung",
                "post": "nach Börsenschluss",
                "pre_short": "vor",
                "post_short": "nach",
                "est": "Erw",
                "none": "Keine Earnings diese Woche",
                "none_week": "Keine Earnings nächste Woche",
            }
        else:
            labels = {
                "today": "EARNINGS TODAY",
                "week": "EARNINGS THIS WEEK",
                "week_preview": "EARNINGS NEXT WEEK",
                "pre": "pre-market",
                "post": "after-close",
                "pre_short": "pre",
                "post_short": "post",
                "est": "Est",
                "none": "No earnings this week",
                "none_week": "No earnings next week",
            }
    
        # Date header
        date_str = datetime.now().strftime("%b %d, %Y") if lang == "en" else datetime.now().strftime("%d. %b %Y")
    
        # Output for briefing
        output = []
    
        # Daily mode: show today's earnings
        if not week_only and today_list:
            output.append(f"📅 {labels['today']} — {date_str}\n")
            for e in sorted(today_list, key=lambda x: x.get("time", "zzz")):
                time_str = f" ({labels['pre']})" if e["time"] == "bmo" else f" ({labels['post']})" if e["time"] == "amc" else ""
                eps_str = f" — {labels['est']}: ${e['eps_estimate']:.2f}" if e.get("eps_estimate") else ""
                output.append(f"• {e['ticker']} — {e['name']}{time_str}{eps_str}")
            output.append("")
    
        if week_list:
            # Use different header for weekly preview mode
            week_label = labels['week_preview'] if week_only else labels['week']
            if week_only:
                # Show date range for weekly preview
                week_range = f"{week_start.strftime('%b %d')} - {week_end.strftime('%b %d')}"
                output.append(f"📅 {week_label} ({week_range})\n")
            else:
                output.append(f"📅 {week_label}\n")
            for e in sorted(week_list, key=lambda x: x["date"]):
                day_name = e["date"].strftime("%a %d.%m")
                time_str = f" ({labels['pre_short']})" if e["time"] == "bmo" else f" ({labels['post_short']})" if e["time"] == "amc" else ""
                output.append(f"• {day_name}: {e['ticker']} — {e['name']}{time_str}")
            output.append("")
    
        if output:
            print("\n".join(output))
        else:
            if args.verbose:
                no_earnings_label = labels['none_week'] if week_only else labels['none']
                print(f"📅 {no_earnings_label}")
    
    
    def get_briefing_section() -> str:
        """Get earnings section for daily briefing (called by briefing.py)."""
        from io import StringIO
        import contextlib
    
        # Capture check output
        class Args:
            verbose = False
    
        f = StringIO()
        with contextlib.redirect_stdout(f):
            check_earnings(Args())
    
        return f.getvalue()
    
    
    def get_earnings_context(symbols: list[str]) -> list[dict]:
        """
        Get recent earnings data (beats/misses) for symbols using OpenBB.
    
        Returns list of dicts with: symbol, eps_actual, eps_estimate, surprise, revenue_actual, revenue_estimate
        """
        if not OPENBB_BINARY:
            return []
    
        results = []
        for symbol in symbols[:10]:  # Limit to 10 symbols
            try:
                result = subprocess.run(
                    [OPENBB_BINARY, symbol, '--earnings'],
                    capture_output=True,
                    text=True,
                    timeout=30
                )
                if result.returncode == 0:
                    try:
                        data = json.loads(result.stdout)
                        if isinstance(data, list) and data:
                            results.append({
                                'symbol': symbol,
                                'earnings': data[0] if isinstance(data[0], dict) else {}
                            })
                    except json.JSONDecodeError:
                        pass
            except Exception:
                pass
        return results
    
    
    def get_analyst_ratings(symbols: list[str]) -> list[dict]:
        """
        Get analyst upgrades/downgrades for symbols using OpenBB.
    
        Returns list of dicts with: symbol, rating, target_price, firm, direction
        """
        if not OPENBB_BINARY:
            return []
    
        results = []
        for symbol in symbols[:10]:  # Limit to 10 symbols
            try:
                result = subprocess.run(
                    [OPENBB_BINARY, symbol, '--rating'],
                    capture_output=True,
                    text=True,
                    timeout=30
                )
                if result.returncode == 0:
                    try:
                        data = json.loads(result.stdout)
                        if isinstance(data, list) and data:
                            results.append({
                                'symbol': symbol,
                                'rating': data[0] if isinstance(data[0], dict) else {}
                            })
                    except json.JSONDecodeError:
                        pass
            except Exception:
                pass
        return results
    
    
    def main():
        parser = argparse.ArgumentParser(description="Earnings Calendar Tracker")
        subparsers = parser.add_subparsers(dest="command", help="Commands")
        
        # list command
        list_parser = subparsers.add_parser("list", help="List all upcoming earnings")
        list_parser.add_argument("--refresh", "-r", action="store_true", help="Force refresh")
        list_parser.set_defaults(func=list_earnings)
        
        # check command
        check_parser = subparsers.add_parser("check", help="Check today/this week")
        check_parser.add_argument("--verbose", "-v", action="store_true")
        check_parser.add_argument("--json", action="store_true", help="JSON output")
        check_parser.add_argument("--lang", default="en", help="Output language (en, de)")
        check_parser.add_argument("--week", action="store_true", help="Show full week preview (for weekly cron)")
        check_parser.set_defaults(func=check_earnings)
        
        # refresh command
        refresh_parser = subparsers.add_parser("refresh", help="Force refresh all data")
        refresh_parser.set_defaults(func=lambda a: refresh_earnings(load_portfolio(), force=True))
        
        args = parser.parse_args()
        
        if not args.command:
            parser.print_help()
            return
        
        args.func(args)
    
    
    if __name__ == "__main__":
        main()
    
  • scripts/fetch_news.py45 KBb2fa3c3e9b83upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/finance-news5.6 KBfd484d4420ecupstream ↗
    #!/usr/bin/env bash
    # Finance News CLI - Main entry point
    # Usage: finance-news <command> [options]
    
    set -e
    
    # Resolve symlinks to find actual script directory
    SOURCE="${BASH_SOURCE[0]}"
    while [ -h "$SOURCE" ]; do
      DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
      SOURCE="$(readlink "$SOURCE")"
      [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
    done
    SCRIPT_DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
    BASE_DIR="$( cd -P "${SCRIPT_DIR}/.." && pwd )"
    
    # NixOS Fix: Ensure libstdc++.so.6 is in LD_LIBRARY_PATH for numpy/yfinance
    # NixOS/Linuxbrew Fix: Ensure libstdc++.so.6 is available for numpy/yfinance
    # Note: Avoid trailing colon in LD_LIBRARY_PATH (security: empty entry = cwd)
    prepend_ld_path() {
      local new_path="$1"
      if [[ -z "${LD_LIBRARY_PATH:-}" ]]; then
        export LD_LIBRARY_PATH="$new_path"
      else
        export LD_LIBRARY_PATH="$new_path:$LD_LIBRARY_PATH"
      fi
    }
    
    if [[ -d "/nix/store" ]]; then
      # Priority 1: Linuxbrew (most reliable)
      if [[ -d "/home/linuxbrew/.linuxbrew/lib" ]]; then
        prepend_ld_path "/home/linuxbrew/.linuxbrew/lib"
      # Priority 2: User Linuxbrew
      elif [[ -d "$HOME/.linuxbrew/lib" ]]; then
        prepend_ld_path "$HOME/.linuxbrew/lib"
      # Priority 3: Nix store (slow fallback)
      else
        LIBPATH=$(find /nix/store -maxdepth 2 -name "*-gcc-*-lib" -print -quit 2>/dev/null)/lib
        if [[ -d "$LIBPATH" ]]; then
          prepend_ld_path "$LIBPATH"
        fi
      fi
    fi
    
    # Auto-activate local venv if present (prevents missing deps in cron/gateway runs)
    VENV_DIR="${BASE_DIR}/venv"
    if [[ -z "${VIRTUAL_ENV:-}" && -x "${VENV_DIR}/bin/python3" ]]; then
      export VIRTUAL_ENV="${VENV_DIR}"
      export PATH="${VIRTUAL_ENV}/bin:${PATH}"
    else
      if [[ ! -x "${VENV_DIR}/bin/python3" ]]; then
        echo "⚠️ Local venv missing at ${VENV_DIR}; install deps to avoid runtime errors." >&2
      fi
    fi
    
    PYTHON_BIN="${PYTHON_BIN:-python3}"
    
    # Ensure CA certificates are available for HTTPS feeds
    if [[ -z "${SSL_CERT_FILE:-}" ]]; then
      if [[ -f /etc/ssl/certs/ca-bundle.crt ]]; then
        export SSL_CERT_FILE=/etc/ssl/certs/ca-bundle.crt
      elif [[ -f /etc/ssl/certs/ca-certificates.crt ]]; then
        export SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt
      fi
    fi
    if [[ -n "${SSL_CERT_FILE:-}" && -z "${REQUESTS_CA_BUNDLE:-}" ]]; then
      export REQUESTS_CA_BUNDLE="${SSL_CERT_FILE}"
    fi
    
    usage() {
        cat << EOM
    📈 Finance News CLI
    
    Usage: finance-news <command> [options]
    
    Commands:
      install                         Install/rebuild Python venv (NixOS-compatible)
      setup                           Interactive setup wizard
      config                          Show current configuration
    
      briefing [--morning|--evening]  Generate market briefing
      market                          Market overview (indices + headlines)
      portfolio                       News for portfolio stocks
      portfolio-only                  Top gainers/losers from portfolio with news
      news <SYMBOL>                   News for specific ticker
    
      alerts <subcommand>             Price target alerts (list, set, check, delete, snooze, update)
      earnings <subcommand>           Earnings calendar (list, check, refresh)
    
      portfolio-list                  List portfolio stocks
      portfolio-add <SYMBOL>          Add stock to portfolio
      portfolio-remove <SYMBOL>       Remove stock from portfolio
      portfolio-import <file.csv>     Import portfolio from CSV
    
    Options:
      --lang <de|en>     Output language (default: de)
      --json             Output as JSON
      --send             Send to WhatsApp group
      --deadline <sec>   Overall deadline in seconds
      --fast             Fast mode (shorter timeouts, fewer items)
      --help             Show this help
    
    Examples:
      finance-news briefing --morning
      finance-news market --lang en
      finance-news news AAPL
      finance-news portfolio-add NVDA --name "NVIDIA Corporation" --category Tech
    EOM
    }
    
    case "${1:-}" in
      briefing)
        shift
        "$PYTHON_BIN" "$SCRIPT_DIR/briefing.py" "$@"
        ;;
      
      market)
        shift
        "$PYTHON_BIN" "$SCRIPT_DIR/fetch_news.py" market "$@"
        ;;
      
      portfolio)
        shift
        "$PYTHON_BIN" "$SCRIPT_DIR/fetch_news.py" portfolio "$@"
        ;;
    
      portfolio-only)
        shift
        "$PYTHON_BIN" "$SCRIPT_DIR/fetch_news.py" portfolio-only "$@"
        ;;
      
      news)
        shift
        if [[ -z "$1" ]]; then
          echo "❌ Usage: finance-news news <SYMBOL>"
          exit 1
        fi
        # Fetch news for specific ticker
        symbol="$1"
        shift
        "$PYTHON_BIN" -c "
    import sys
    sys.path.insert(0, '$SCRIPT_DIR')
    from fetch_news import fetch_ticker_news
    import json
    
    articles = fetch_ticker_news('$symbol', 10)
    print(f'\n📰 News for $symbol\n')
    for a in articles:
        print(f\"• {a['title']}\")
        print(f\"  {a['link']}\n\")
    "
        ;;
      
      portfolio-list)
        "$PYTHON_BIN" "$SCRIPT_DIR/portfolio.py" list
        ;;
      
      portfolio-add)
        shift
        "$PYTHON_BIN" "$SCRIPT_DIR/portfolio.py" add "$@"
        ;;
      
      portfolio-remove)
        shift
        "$PYTHON_BIN" "$SCRIPT_DIR/portfolio.py" remove "$@"
        ;;
      
      portfolio-import)
        shift
        "$PYTHON_BIN" "$SCRIPT_DIR/portfolio.py" import "$@"
        ;;
      
      portfolio-create)
        "$PYTHON_BIN" "$SCRIPT_DIR/portfolio.py" create
        ;;
    
      alerts)
        shift
        "$PYTHON_BIN" "$SCRIPT_DIR/alerts.py" "$@"
        ;;
    
      earnings)
        shift
        "$PYTHON_BIN" "$SCRIPT_DIR/earnings.py" "$@"
        ;;
    
      install)
        shift
        bash "$SCRIPT_DIR/venv-setup.sh" "$@"
        ;;
    
      setup)
        shift
        "$PYTHON_BIN" "$SCRIPT_DIR/setup.py" "$@"
        ;;
      
      setup-wizard)
        "$PYTHON_BIN" "$SCRIPT_DIR/setup.py" wizard
        ;;
      
      config)
        "$PYTHON_BIN" "$SCRIPT_DIR/setup.py" show
        ;;
      
      --help|-h|help|"")
        usage
        ;;
      
      *)
        echo "❌ Unknown command: $1"
        echo "Run 'finance-news --help' for usage."
        exit 1
        ;;
    esac
    
  • scripts/openbb-quote2.9 KB6ccb6557c463upstream ↗
    #!/usr/bin/env bash
    set -euo pipefail
    
    SCRIPT_DIR="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)"
    # shellcheck source=/dev/null
    source "${SCRIPT_DIR}/_openbb_common.sh"
    
    if [[ $# -lt 1 ]]; then
        echo "Usage: openbb-quote SYMBOL [SYMBOL2 ...] [provider]" >&2
        exit 1
    fi
    
    EXPLICIT_PROVIDER=""
    TICKERS=()
    for arg in "$@"; do
        case "${arg}" in
            fmp|intrinio|yfinance|tiingo|polygon|alphavantage)
                EXPLICIT_PROVIDER="${arg}"
                ;;
            *)
                TICKERS+=("${arg}")
                ;;
        esac
    done
    
    PROVIDER="$(resolve_openbb_provider "${EXPLICIT_PROVIDER}" "yfinance")"
    
    export _OPENBB_PROVIDER="${PROVIDER}"
    export _OPENBB_TICKERS
    _OPENBB_TICKERS="$(printf '%s\n' "${TICKERS[@]}")"
    
    raw_output="$(
    run_openbb_python << 'PYTHON'
    from __future__ import annotations
    
    import json
    import os
    import sys
    
    from openbb import obb
    
    provider = os.environ.get("_OPENBB_PROVIDER", "yfinance")
    tickers = [t.strip().upper() for t in os.environ.get("_OPENBB_TICKERS", "").split("\n") if t.strip()]
    
    results = []
    for symbol in tickers:
        try:
            response = obb.equity.price.quote(symbol=symbol, provider=provider)
            if not response.results:
                results.append({"symbol": symbol, "error": "no quote"})
                continue
            item = response.results[0]
            results.append(
                {
                    "symbol": symbol,
                    "price": float(item.last_price) if item.last_price is not None else None,
                    "open": float(item.open) if getattr(item, "open", None) is not None else None,
                    "high": float(item.high) if getattr(item, "high", None) is not None else None,
                    "low": float(item.low) if getattr(item, "low", None) is not None else None,
                    "volume": int(item.volume) if getattr(item, "volume", None) is not None else None,
                    "prev_close": float(item.prev_close) if getattr(item, "prev_close", None) is not None else None,
                    "change": float(item.change) if getattr(item, "change", None) is not None else None,
                    "change_percent": float(item.change_percent) if getattr(item, "change_percent", None) is not None else None,
                }
            )
        except Exception as exc:
            results.append({"symbol": symbol, "error": str(exc)})
    
    print(json.dumps(results, ensure_ascii=False))
    sys.exit(0)
    PYTHON
    )"
    
    printf '%s' "${raw_output}" | python3 -c '
    from __future__ import annotations
    import json
    import sys
    
    text = sys.stdin.read()
    decoder = json.JSONDecoder()
    for idx, ch in enumerate(text):
        if ch not in "[{":
            continue
        try:
            obj, _ = decoder.raw_decode(text[idx:])
        except Exception:
            continue
        if isinstance(obj, dict):
            obj = [obj]
        print(json.dumps(obj, ensure_ascii=False))
        raise SystemExit(0)
    print("openbb-quote: unable to parse OpenBB JSON output", file=sys.stderr)
    raise SystemExit(1)
    '
    
  • scripts/portfolio.py10 KBc0acc0828a77upstream ↗
    #!/usr/bin/env python3
    """
    Portfolio Manager - CRUD operations for stock watchlist.
    """
    
    import argparse
    import csv
    import os
    import sys
    from pathlib import Path
    
    
    def _get_portfolio_file() -> Path:
        """Get portfolio CSV path with PORTFOLIOS_DIR env var support.
    
        Priority:
        1. Shared location ($PORTFOLIOS_DIR/watchlists/portfolio.csv) if env var set
        2. Legacy config/portfolio.csv (backward compatibility)
        """
        env_dir = os.environ.get("PORTFOLIOS_DIR", "").strip()
        if env_dir:
            # If env var is set, always use shared path (even if file doesn't exist yet)
            return Path(os.path.expanduser(env_dir)) / "watchlists" / "portfolio.csv"
        # Fallback to legacy path
        return Path(__file__).parent.parent / "config" / "portfolio.csv"
    
    
    PORTFOLIO_FILE = _get_portfolio_file()
    REQUIRED_COLUMNS = ['symbol', 'name']
    DEFAULT_COLUMNS = ['symbol', 'name', 'category', 'notes', 'type']
    
    
    def validate_portfolio_csv(path: Path) -> tuple[bool, list[str]]:
        """
        Validate portfolio CSV file for common issues.
    
        Returns:
            Tuple of (is_valid, list of warnings)
        """
        warnings = []
    
        if not path.exists():
            return True, warnings
    
        try:
            with open(path, 'r', encoding='utf-8') as f:
                # Check for encoding issues
                content = f.read()
    
            with open(path, 'r', encoding='utf-8') as f:
                reader = csv.DictReader(f)
    
                # Check required columns
                if reader.fieldnames is None:
                    warnings.append("CSV appears to be empty")
                    return False, warnings
    
                missing_cols = set(REQUIRED_COLUMNS) - set(reader.fieldnames or [])
                if missing_cols:
                    warnings.append(f"Missing required columns: {', '.join(missing_cols)}")
    
                # Check for duplicate symbols
                symbols = []
                for row in reader:
                    symbol = row.get('symbol', '').strip().upper()
                    if symbol:
                        symbols.append(symbol)
    
                duplicates = [s for s in set(symbols) if symbols.count(s) > 1]
                if duplicates:
                    warnings.append(f"Duplicate symbols found: {', '.join(duplicates)}")
    
        except UnicodeDecodeError:
            warnings.append("File encoding issue - try saving as UTF-8")
        except Exception as e:
            warnings.append(f"Error reading portfolio: {e}")
            return False, warnings
    
        return True, warnings
    
    
    def load_portfolio() -> list[dict]:
        """Load portfolio from CSV with validation."""
        if not PORTFOLIO_FILE.exists():
            return []
    
        # Validate first
        is_valid, warnings = validate_portfolio_csv(PORTFOLIO_FILE)
        for warning in warnings:
            print(f"⚠️ Portfolio warning: {warning}", file=sys.stderr)
    
        if not is_valid:
            print("⚠️ Portfolio has errors - returning empty", file=sys.stderr)
            return []
    
        try:
            with open(PORTFOLIO_FILE, 'r', encoding='utf-8') as f:
                reader = csv.DictReader(f)
    
                # Normalize data
                portfolio = []
                seen_symbols = set()
    
                for row in reader:
                    symbol = row.get('symbol', '').strip().upper()
                    if not symbol:
                        continue
    
                    # Skip duplicates (keep first occurrence)
                    if symbol in seen_symbols:
                        continue
                    seen_symbols.add(symbol)
    
                    portfolio.append({
                        'symbol': symbol,
                        'name': row.get('name', symbol) or symbol,
                        'category': row.get('category', '') or '',
                        'notes': row.get('notes', '') or '',
                        'type': row.get('type', 'Watchlist') or 'Watchlist'
                    })
    
                return portfolio
    
        except Exception as e:
            print(f"⚠️ Error loading portfolio: {e}", file=sys.stderr)
            return []
    
    
    def save_portfolio(portfolio: list[dict]):
        """Save portfolio to CSV."""
        # Ensure parent directory exists (needed for shared portfolio location)
        PORTFOLIO_FILE.parent.mkdir(parents=True, exist_ok=True)
        
        if not portfolio:
            PORTFOLIO_FILE.write_text("symbol,name,category,notes,type\n")
            return
        
        with open(PORTFOLIO_FILE, 'w', newline='') as f:
            writer = csv.DictWriter(f, fieldnames=['symbol', 'name', 'category', 'notes', 'type'])
            writer.writeheader()
            writer.writerows(portfolio)
    
    
    def list_portfolio(args):
        """List all stocks in portfolio."""
        portfolio = load_portfolio()
        
        if not portfolio:
            print("📂 Portfolio is empty. Use 'portfolio add <SYMBOL>' to add stocks.")
            return
        
        print(f"\n📊 Portfolio ({len(portfolio)} stocks)\n")
        
        # Group by Type then Category
        by_type = {}
        for stock in portfolio:
            t = stock.get('type', 'Watchlist') or 'Watchlist'
            if t not in by_type:
                by_type[t] = []
            by_type[t].append(stock)
            
        for t, type_stocks in by_type.items():
            print(f"# {t}")
            categories = {}
            for stock in type_stocks:
                cat = stock.get('category', 'Other') or 'Other'
                if cat not in categories:
                    categories[cat] = []
                categories[cat].append(stock)
            
            for cat, stocks in categories.items():
                print(f"### {cat}")
                for s in stocks:
                    notes = f" — {s['notes']}" if s.get('notes') else ""
                    print(f"  • {s['symbol']}: {s['name']}{notes}")
                print()
    
    
    def add_stock(args):
        """Add a stock to portfolio."""
        portfolio = load_portfolio()
        
        # Check if already exists
        if any(s['symbol'].upper() == args.symbol.upper() for s in portfolio):
            print(f"⚠️ {args.symbol.upper()} already in portfolio")
            return
        
        new_stock = {
            'symbol': args.symbol.upper(),
            'name': args.name or args.symbol.upper(),
            'category': args.category or '',
            'notes': args.notes or '',
            'type': args.type
        }
        
        portfolio.append(new_stock)
        save_portfolio(portfolio)
        print(f"✅ Added {args.symbol.upper()} to portfolio ({args.type})")
    
    
    def remove_stock(args):
        """Remove a stock from portfolio."""
        portfolio = load_portfolio()
        
        original_len = len(portfolio)
        portfolio = [s for s in portfolio if s['symbol'].upper() != args.symbol.upper()]
        
        if len(portfolio) == original_len:
            print(f"⚠️ {args.symbol.upper()} not found in portfolio")
            return
        
        save_portfolio(portfolio)
        print(f"✅ Removed {args.symbol.upper()} from portfolio")
    
    
    def import_csv(args):
        """Import portfolio from external CSV."""
        import_path = Path(args.file)
        
        if not import_path.exists():
            print(f"❌ File not found: {args.file}")
            sys.exit(1)
        
        with open(import_path, 'r') as f:
            reader = csv.DictReader(f)
            imported = list(reader)
        
        # Normalize fields
        normalized = []
        for row in imported:
            normalized.append({
                'symbol': row.get('symbol', row.get('Symbol', row.get('ticker', ''))).upper(),
                'name': row.get('name', row.get('Name', row.get('company', ''))),
                'category': row.get('category', row.get('Category', row.get('sector', ''))),
                'notes': row.get('notes', row.get('Notes', '')),
                'type': row.get('type', 'Watchlist')
            })
        
        save_portfolio(normalized)
        print(f"✅ Imported {len(normalized)} stocks from {args.file}")
    
    
    def create_interactive(args):
        """Interactive portfolio creation."""
        print("\n📊 Portfolio Creator\n")
        print("Enter stocks one per line (format: SYMBOL or SYMBOL,Name,Category)")
        print("Type 'done' when finished.\n")
        
        portfolio = []
        
        while True:
            try:
                line = input("> ").strip()
            except (EOFError, KeyboardInterrupt):
                break
            
            if line.lower() == 'done':
                break
            
            if not line:
                continue
            
            parts = line.split(',')
            symbol = parts[0].strip().upper()
            name = parts[1].strip() if len(parts) > 1 else symbol
            category = parts[2].strip() if len(parts) > 2 else ''
            
            portfolio.append({
                'symbol': symbol,
                'name': name,
                'category': category,
                'notes': '',
                'type': 'Watchlist'
            })
            print(f"  Added: {symbol}")
        
        if portfolio:
            save_portfolio(portfolio)
            print(f"\n✅ Created portfolio with {len(portfolio)} stocks")
        else:
            print("\n⚠️ No stocks added")
    
    
    def get_symbols(args=None):
        """Get list of symbols (for other scripts to use)."""
        portfolio = load_portfolio()
        symbols = [s['symbol'] for s in portfolio]
        
        if args and args.json:
            import json
            print(json.dumps(symbols))
        else:
            print(','.join(symbols))
    
    
    def main():
        parser = argparse.ArgumentParser(description='Portfolio Manager')
        subparsers = parser.add_subparsers(dest='command', required=True)
        
        # List command
        list_parser = subparsers.add_parser('list', help='List portfolio')
        list_parser.set_defaults(func=list_portfolio)
        
        # Add command
        add_parser = subparsers.add_parser('add', help='Add stock')
        add_parser.add_argument('symbol', help='Stock symbol')
        add_parser.add_argument('--name', help='Company name')
        add_parser.add_argument('--category', help='Category (e.g., Tech, Finance)')
        add_parser.add_argument('--notes', help='Notes')
        add_parser.add_argument('--type', choices=['Holding', 'Watchlist'], default='Watchlist', help='Portfolio type')
        add_parser.set_defaults(func=add_stock)
        
        # Remove command
        remove_parser = subparsers.add_parser('remove', help='Remove stock')
        remove_parser.add_argument('symbol', help='Stock symbol')
        remove_parser.set_defaults(func=remove_stock)
        
        # Import command
        import_parser = subparsers.add_parser('import', help='Import from CSV')
        import_parser.add_argument('file', help='CSV file path')
        import_parser.set_defaults(func=import_csv)
        
        # Create command
        create_parser = subparsers.add_parser('create', help='Interactive creation')
        create_parser.set_defaults(func=create_interactive)
        
        # Symbols command (for other scripts)
        symbols_parser = subparsers.add_parser('symbols', help='Get symbols list')
        symbols_parser.add_argument('--json', action='store_true', help='Output as JSON')
        symbols_parser.set_defaults(func=get_symbols)
        
        args = parser.parse_args()
        args.func(args)
    
    
    if __name__ == '__main__':
        main()
    
  • scripts/portfolio_attribution.py21 KBdff97e300562upstream ↗
    from __future__ import annotations
    
    import json
    import math
    import re
    import time
    from dataclasses import dataclass
    from datetime import datetime
    from pathlib import Path
    from urllib.parse import urlparse
    
    SCRIPT_DIR = Path(__file__).parent
    CONFIG_DIR = SCRIPT_DIR.parent / "config"
    DEFAULT_BENCHMARK_CONFIG = CONFIG_DIR / "portfolio_benchmarks.json"
    
    CLASSIFICATION_ORDER = {
        "idiosyncratic": 0,
        "mixed": 1,
        "sector_theme": 2,
        "market": 3,
        "fx": 4,
        "unexplained": 5,
    }
    
    CATALYST_KEYWORDS = {
        "acquisition",
        "analyst",
        "antitrust",
        "buyback",
        "capex",
        "capital markets day",
        "cuts guidance",
        "demand",
        "downgrade",
        "earnings",
        "export controls",
        "forecast",
        "guidance",
        "investigation",
        "lawsuit",
        "margin",
        "merger",
        "outlook",
        "pricing",
        "profit",
        "q1",
        "q2",
        "q3",
        "q4",
        "rating",
        "recall",
        "regulator",
        "revenue",
        "sales",
        "supply",
        "target cut",
        "trading update",
        "upgrade",
        "absatz",
        "analyst",
        "ausblick",
        "herabstufung",
        "ergebnis",
        "ergebnisse",
        "gewinn",
        "hochgestuft",
        "marge",
        "margen",
        "prognose",
        "q1",
        "q2",
        "q3",
        "q4",
        "quartal",
        "trading update",
        "umsatz",
    }
    
    GENERIC_ARTICLE_PATTERNS = (
        "stock is moving",
        "stock is down",
        "stock is up",
        "stocks to watch",
        "best stocks",
        "buy now",
        "could be a millionaire",
    )
    
    EXCEPTION_MOVE_THRESHOLD_PCT = 9.0
    
    
    @dataclass(frozen=True)
    class BenchmarkMapping:
        benchmark_ticker: str
        benchmark_label: str
        market_ticker: str
        market_label: str
        currency_ticker: str | None
        currency_label: str | None
        reason: str
        uncertain: bool
    
    
    @dataclass(frozen=True)
    class Evidence:
        title: str
        title_de: str | None
        source: str
        link: str
        confidence: str
    
    
    @dataclass(frozen=True)
    class EvidenceCandidateAudit:
        title: str
        source: str
        link: str
        status: str
        reason: str
        score: float | None = None
        confidence: str | None = None
    
    
    @dataclass(frozen=True)
    class EvidenceAudit:
        status: str
        checked_count: int
        selected: Evidence | None
        candidates: tuple[EvidenceCandidateAudit, ...]
    
    
    @dataclass(frozen=True)
    class AttributionResult:
        symbol: str
        display_symbol: str
        price: float | None
        currency: str
        change_pct: float
        benchmark_ticker: str
        benchmark_label: str
        benchmark_change_pct: float | None
        market_ticker: str
        market_change_pct: float | None
        currency_ticker: str | None
        currency_change_pct: float | None
        residual_pct: float | None
        classification: str
        evidence: Evidence | None
        evidence_audit: EvidenceAudit
        mapping_uncertain: bool
        relevance_score: float
    
        @property
        def has_high_confidence_evidence(self) -> bool:
            return self.evidence is not None and self.evidence.confidence == "HIGH"
    
        @property
        def is_unresolved_exception(self) -> bool:
            return not self.has_high_confidence_evidence and abs(self.change_pct) >= EXCEPTION_MOVE_THRESHOLD_PCT
    
    
    def load_benchmark_config(path: Path | None = None) -> dict:
        config_path = path or DEFAULT_BENCHMARK_CONFIG
        return json.loads(config_path.read_text(encoding="utf-8"))
    
    
    def _ticker_region(symbol: str, config: dict) -> str:
        suffixes = config.get("ticker_suffix_regions", {})
        for suffix, region in suffixes.items():
            if symbol.endswith(suffix):
                return str(region)
        return "US" if "." not in symbol else "default"
    
    
    def _entry_from(mapping: dict, key: str) -> tuple[str, str] | None:
        entry = mapping.get(key)
        if not isinstance(entry, dict):
            return None
        ticker = str(entry.get("ticker") or "").strip().upper()
        label = str(entry.get("label") or ticker).strip()
        if not ticker:
            return None
        return ticker, label
    
    
    def _currency_proxy(symbol: str, config: dict) -> tuple[str, str] | None:
        proxies = config.get("currency_proxies", {})
        for suffix, entry in proxies.items():
            if symbol.endswith(suffix) and isinstance(entry, dict):
                ticker = str(entry.get("ticker") or "").strip().upper()
                label = str(entry.get("label") or ticker).strip()
                return (ticker, label) if ticker else None
        return None
    
    
    def _theme_tokens(info: dict) -> list[str]:
        raw_values = [
            str(info.get("investment_theme") or ""),
            str(info.get("theme") or ""),
            str(info.get("notes") or ""),
        ]
        tokens: list[str] = []
        for raw_value in raw_values:
            for token in raw_value.replace(",", "|").split("|"):
                cleaned = token.strip()
                if cleaned and cleaned not in tokens:
                    tokens.append(cleaned)
        return tokens
    
    
    def _theme_entry(info: dict, config: dict) -> tuple[str, str] | None:
        themes = config.get("themes", {})
        for token in _theme_tokens(info):
            entry = _entry_from(themes, token)
            if entry:
                return entry
        return None
    
    
    def resolve_benchmark_mapping(symbol: str, info: dict | None, config: dict) -> BenchmarkMapping:
        symbol_upper = symbol.upper()
        info = info or {}
        region = _ticker_region(symbol_upper, config)
        market = _entry_from(config.get("broad_markets", {}), region)
        if market is None:
            market = _entry_from(config.get("broad_markets", {}), "default") or ("ACWI", "Global equities")
    
        override = _entry_from(config.get("ticker_overrides", {}), symbol_upper)
        if override:
            benchmark = override
            reason = "ticker_override"
            uncertain = False
        else:
            benchmark = _theme_entry(info, config)
            if benchmark:
                reason = "theme"
                uncertain = False
            else:
                category = str(info.get("sector_specific") or info.get("category") or "").strip()
                benchmark = _entry_from(config.get("categories", {}), category)
                reason = "category" if benchmark else "market_fallback"
                uncertain = benchmark is None
    
        if benchmark is None:
            benchmark = market
    
        currency = _currency_proxy(symbol_upper, config)
        return BenchmarkMapping(
            benchmark_ticker=benchmark[0],
            benchmark_label=benchmark[1],
            market_ticker=market[0],
            market_label=market[1],
            currency_ticker=currency[0] if currency else None,
            currency_label=currency[1] if currency else None,
            reason=reason,
            uncertain=uncertain,
        )
    
    
    def benchmark_tickers_for_portfolio(stocks: dict, config: dict) -> list[str]:
        tickers: list[str] = []
        for symbol, data in stocks.items():
            if not isinstance(data, dict):
                continue
            mapping = resolve_benchmark_mapping(str(symbol), data.get("info") or {}, config)
            for ticker in (mapping.market_ticker, mapping.benchmark_ticker, mapping.currency_ticker):
                if ticker and ticker not in tickers:
                    tickers.append(ticker)
        return tickers
    
    
    def _change_pct(raw: dict | None) -> float | None:
        if not isinstance(raw, dict):
            return None
        value = raw.get("change_percent")
        return round(float(value), 1) if isinstance(value, (int, float)) else None
    
    
    def _domain(link: str) -> str:
        host = urlparse(link).netloc.lower()
        return host[4:] if host.startswith("www.") else host
    
    
    def _domain_matches(domain: str, candidates: list[str]) -> bool:
        return any(domain == item or domain.endswith(f".{item}") for item in candidates)
    
    
    def _has_catalyst(title: str) -> bool:
        normalized = title.lower()
        return any(keyword in normalized for keyword in CATALYST_KEYWORDS)
    
    
    def _is_generic_article(title: str) -> bool:
        normalized = title.lower()
        if normalized.startswith("why ") and "stock" in normalized:
            price_action = ("is moving", "is down", "is up", "moving lower", "moving higher")
            if any(pattern in normalized for pattern in price_action):
                return True
        return any(pattern in normalized for pattern in GENERIC_ARTICLE_PATTERNS)
    
    
    def _confidence_for_source(source: str, domain: str, quality: dict) -> str:
        high_sources = [str(item).lower() for item in quality.get("high_confidence_sources", [])]
        high_domains = [str(item).lower() for item in quality.get("high_confidence_domains", [])]
        if source.lower() in high_sources or (domain and _domain_matches(domain, high_domains)):
            return "HIGH"
        return "MEDIUM"
    
    
    def _article_timestamp(article: dict) -> float | None:
        raw = article.get("published_at")
        if isinstance(raw, (int, float)):
            return float(raw)
        if isinstance(raw, str):
            value = raw.strip()
            if not value:
                return None
            try:
                return float(value)
            except ValueError:
                pass
            try:
                return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()
            except ValueError:
                return None
        return None
    
    
    def _compile_patterns(raw_patterns: list[object]) -> list[re.Pattern[str]]:
        compiled: list[re.Pattern[str]] = []
        for item in raw_patterns:
            token = str(item).strip()
            if not token:
                continue
            try:
                compiled.append(re.compile(token, re.IGNORECASE))
            except re.error:
                continue
        return compiled
    
    
    def _template_hit_count(title: str, patterns: list[re.Pattern[str]]) -> int:
        return sum(1 for pattern in patterns if pattern.search(title))
    
    
    def _recency_bonus(
        published_at: float | None,
        *,
        max_bonus: float,
        half_life_hours: float,
    ) -> float:
        if published_at is None:
            return 0.0
        age_hours = max(0.0, (time.time() - published_at) / 3600.0)
        if half_life_hours <= 0:
            return 0.0
        decay = math.exp(-math.log(2.0) * (age_hours / half_life_hours))
        return max_bonus * decay
    
    
    def evaluate_article_evidence(articles: list[dict], config: dict) -> EvidenceAudit:
        quality = config.get("source_quality", {})
        blocked_domains = [str(item).lower() for item in quality.get("blocked_domains", [])]
        allowed_domains = [str(item).lower() for item in quality.get("allowed_domains", [])]
        allowed_sources = [str(item).lower() for item in quality.get("allowed_sources", [])]
        scoring = quality.get("quality_scoring", {})
        min_score = float(scoring.get("minimum_score", 1.0))
        allowed_source_bonus = float(scoring.get("allowed_source_bonus", 0.5))
        catalyst_bonus = float(scoring.get("catalyst_bonus", 1.0))
        recency_max_bonus = float(scoring.get("recency_max_bonus", 0.4))
        recency_half_life_hours = float(scoring.get("recency_half_life_hours", 24.0))
        low_value_template_penalty = float(scoring.get("low_value_template_penalty", 1.5))
        low_value_patterns = _compile_patterns(scoring.get("low_value_template_patterns", []))
        candidates: list[tuple[float, float, int, Evidence]] = []
        audits: list[EvidenceCandidateAudit] = []
    
        for index, article in enumerate(articles):
            title = str(article.get("title") or "").strip()
            link = str(article.get("link") or "").strip()
            domain = _domain(link)
            source = str(article.get("source") or domain or "Source").strip()
            if not title:
                audits.append(EvidenceCandidateAudit(title="", source=source, link=link, status="rejected", reason="missing_title"))
                continue
            if _is_generic_article(title):
                audits.append(EvidenceCandidateAudit(title=title, source=source, link=link, status="rejected", reason="generic_price_action"))
                continue
            has_catalyst = _has_catalyst(title)
            if not has_catalyst:
                audits.append(EvidenceCandidateAudit(title=title, source=source, link=link, status="rejected", reason="no_direct_catalyst"))
                continue
            if domain and _domain_matches(domain, blocked_domains):
                audits.append(EvidenceCandidateAudit(title=title, source=source, link=link, status="rejected", reason="blocked_domain"))
                continue
            source_l = source.lower()
            allowed = source_l in allowed_sources or (domain and _domain_matches(domain, allowed_domains))
            if not allowed:
                audits.append(EvidenceCandidateAudit(title=title, source=source, link=link, status="rejected", reason="source_not_allowed"))
                continue
            published_at = _article_timestamp(article)
            score = 0.0
            score += allowed_source_bonus
            if has_catalyst:
                score += catalyst_bonus
            score += _recency_bonus(
                published_at,
                max_bonus=recency_max_bonus,
                half_life_hours=recency_half_life_hours,
            )
            score -= _template_hit_count(title, low_value_patterns) * low_value_template_penalty
            if score < min_score:
                audits.append(
                    EvidenceCandidateAudit(
                        title=title,
                        source=source,
                        link=link,
                        status="rejected",
                        reason="below_quality_threshold",
                        score=round(score, 3),
                    )
                )
                continue
            confidence = _confidence_for_source(source, domain, quality)
            if confidence != "HIGH":
                audits.append(
                    EvidenceCandidateAudit(
                        title=title,
                        source=source,
                        link=link,
                        status="context",
                        reason="not_high_confidence_source",
                        score=round(score, 3),
                        confidence=confidence,
                    )
                )
                continue
            evidence = Evidence(
                title=title,
                title_de=(str(article.get("title_de") or "").strip() or None),
                source=source,
                link=link,
                confidence=confidence,
            )
            audits.append(
                EvidenceCandidateAudit(
                    title=title,
                    source=source,
                    link=link,
                    status="eligible",
                    reason="direct_catalyst",
                    score=round(score, 3),
                    confidence=confidence,
                )
            )
            candidates.append(
                (
                    score,
                    published_at or 0.0,
                    index,
                    evidence,
                )
            )
    
        if not candidates:
            status = "no_source_coverage" if not articles else "no_high_confidence_evidence"
            return EvidenceAudit(status=status, checked_count=len(articles), selected=None, candidates=tuple(audits))
        candidates.sort(key=lambda item: (-item[0], -item[1], item[2]))
        selected = candidates[0][3]
        selected_audits = [
            EvidenceCandidateAudit(
                title=audit.title,
                source=audit.source,
                link=audit.link,
                status="selected" if audit.title == selected.title and audit.link == selected.link else audit.status,
                reason=audit.reason,
                score=audit.score,
                confidence=audit.confidence,
            )
            for audit in audits
        ]
        return EvidenceAudit(
            status="selected",
            checked_count=len(articles),
            selected=selected,
            candidates=tuple(selected_audits),
        )
    
    
    def evidence_for_articles(articles: list[dict], config: dict) -> Evidence | None:
        return evaluate_article_evidence(articles, config).selected
    
    
    def _classification(
        change_pct: float,
        benchmark_change: float | None,
        market_change: float | None,
        currency_change: float | None,
        residual: float | None,
        mapping_uncertain: bool,
    ) -> str:
        if currency_change is not None and abs(currency_change) >= 1.0 and abs(change_pct - currency_change) <= 1.2:
            return "fx"
        if benchmark_change is not None and residual is not None:
            if abs(benchmark_change) >= 1.0 and abs(residual) <= 1.0:
                return "sector_theme"
            if abs(residual) >= 3.0:
                return "unexplained" if mapping_uncertain else "idiosyncratic"
            if market_change is not None and abs(market_change) >= 1.0 and abs(change_pct - market_change) <= 1.0:
                return "market"
            if abs(benchmark_change) >= 1.0 and abs(residual) <= 2.0:
                return "mixed"
        if market_change is not None and abs(market_change) >= 1.0 and abs(change_pct - market_change) <= 1.0:
            return "market"
        return "unexplained"
    
    
    def _display_symbol(symbol: str, info: dict) -> str:
        name = str(info.get("name") or "").strip()
        return f"{name} ({symbol})" if name and "." in symbol else symbol
    
    
    def _currency_for_symbol(symbol: str, quote: dict) -> str:
        raw_currency = str(quote.get("currency") or "").strip().upper()
        if raw_currency:
            return raw_currency
        if symbol.endswith(".T"):
            return "JPY"
        if symbol.endswith((".TO", ".V")):
            return "CAD"
        if symbol.endswith(".SW"):
            return "CHF"
        if symbol.endswith((".DE", ".PA", ".AS")):
            return "EUR"
        if symbol.endswith(".TW"):
            return "TWD"
        return "USD"
    
    
    def _target_weight(info: dict) -> float:
        try:
            return float(info.get("target_weight") or 0.0)
        except (TypeError, ValueError):
            return 0.0
    
    
    def build_attributions(stocks: dict, benchmark_quotes: dict, config: dict) -> list[AttributionResult]:
        results: list[AttributionResult] = []
        for symbol, data in stocks.items():
            if not isinstance(data, dict):
                continue
            quote = data.get("quote") or {}
            change = quote.get("change_percent")
            if not isinstance(change, (int, float)):
                continue
            info = data.get("info") or {}
            mapping = resolve_benchmark_mapping(str(symbol), info, config)
            benchmark_change = _change_pct(benchmark_quotes.get(mapping.benchmark_ticker))
            market_change = _change_pct(benchmark_quotes.get(mapping.market_ticker))
            currency_change = _change_pct(benchmark_quotes.get(mapping.currency_ticker))
            residual = round(float(change) - benchmark_change, 1) if benchmark_change is not None else None
            classification = _classification(float(change), benchmark_change, market_change, currency_change, residual, mapping.uncertain)
            evidence_audit = evaluate_article_evidence(data.get("articles") or [], config)
            evidence = evidence_audit.selected
            score = abs(float(change)) + (_target_weight(info) * 100)
            results.append(
                AttributionResult(
                    symbol=str(symbol),
                    display_symbol=_display_symbol(str(symbol), info),
                    price=quote.get("price") if isinstance(quote.get("price"), (int, float)) else None,
                    currency=_currency_for_symbol(str(symbol), quote),
                    change_pct=round(float(change), 1),
                    benchmark_ticker=mapping.benchmark_ticker,
                    benchmark_label=mapping.benchmark_label,
                    benchmark_change_pct=benchmark_change,
                    market_ticker=mapping.market_ticker,
                    market_change_pct=market_change,
                    currency_ticker=mapping.currency_ticker,
                    currency_change_pct=currency_change,
                    residual_pct=residual,
                    classification=classification,
                    evidence=evidence,
                    evidence_audit=evidence_audit,
                    mapping_uncertain=mapping.uncertain,
                    relevance_score=score,
                )
            )
    
        results.sort(key=lambda item: (-item.relevance_score, CLASSIFICATION_ORDER.get(item.classification, 9)))
        return results
    
    
    def evidence_audit_payload(results: list[AttributionResult]) -> list[dict]:
        payload = []
        for result in results:
            payload.append(
                {
                    "symbol": result.symbol,
                    "display_symbol": result.display_symbol,
                    "change_pct": result.change_pct,
                    "classification": result.classification,
                    "visible_normal": result.has_high_confidence_evidence,
                    "visible_exception": result.is_unresolved_exception,
                    "evidence_status": result.evidence_audit.status,
                    "selected_evidence": _evidence_payload(result.evidence_audit.selected),
                    "candidates": [
                        {
                            "title": candidate.title,
                            "source": candidate.source,
                            "link": candidate.link,
                            "status": candidate.status,
                            "reason": candidate.reason,
                            "score": candidate.score,
                            "confidence": candidate.confidence,
                        }
                        for candidate in result.evidence_audit.candidates
                    ],
                    "attribution": {
                        "benchmark_ticker": result.benchmark_ticker,
                        "benchmark_label": result.benchmark_label,
                        "benchmark_change_pct": result.benchmark_change_pct,
                        "market_ticker": result.market_ticker,
                        "market_change_pct": result.market_change_pct,
                        "currency_ticker": result.currency_ticker,
                        "currency_change_pct": result.currency_change_pct,
                        "residual_pct": result.residual_pct,
                        "mapping_uncertain": result.mapping_uncertain,
                    },
                }
            )
        return payload
    
    
    def _evidence_payload(evidence: Evidence | None) -> dict | None:
        if evidence is None:
            return None
        return {
            "title": evidence.title,
            "title_de": evidence.title_de,
            "source": evidence.source,
            "link": evidence.link,
            "confidence": evidence.confidence,
        }
    
  • scripts/ranking.py13 KB7563039c0a3dupstream ↗
    #!/usr/bin/env python3
    """
    Deterministic Headline Ranking - Impact-based ranking policy.
    
    Implements #53: Deterministic impact-based ranking for headline selection.
    
    Scoring Rubric (weights):
    - Market Impact (40%): CB decisions, earnings, sanctions, oil spikes
    - Novelty (20%): New vs recycled news
    - Breadth (20%): Sector-wide vs single-stock
    - Credibility (10%): Source reliability
    - Diversity Bonus (10%): Underrepresented categories
    
    Output:
    - MUST_READ: Top 5 stories
    - SCAN: 3-5 additional stories (if quality threshold met)
    """
    
    import re
    from datetime import datetime
    from difflib import SequenceMatcher
    
    
    # Category keywords for classification
    CATEGORY_KEYWORDS = {
        "macro": ["fed", "ecb", "boj", "central bank", "rate", "inflation", "gdp", "unemployment", "treasury", "yield", "bond"],
        "equity_broad": ["s&p 500", "nasdaq", "dow", "stoxx", "equities", "stocks", "sector", "market breadth", "magnificent 7", "mag7"],
        "geopolitics": ["sanction", "tariff", "war", "conflict", "embargo", "trump", "china", "russia", "ukraine", "iran", "trade war"],
        "energy": ["oil", "opec", "crude", "gas", "energy", "brent", "wti"],
        "tech": ["ai", "chip", "semiconductor", "nvidia", "apple", "google", "microsoft", "meta", "amazon"],
    }
    
    BROAD_EARNINGS_CONTEXT = [
        "s&p", "nasdaq", "dow", "stoxx", "index", "indices", "sector", "market", "mag7", "magnificent 7"
    ]
    
    COMPANY_SPECIFIC_KEYWORDS = [
        "ceo", "cfo", "executive", "compensation", "pay rise", "buyback",
        "dividend", "guidance", "earnings", "eps", "revenue", "profit",
        "upgrade", "downgrade", "target", "lawsuit", "sues", "acquisition",
        "merger", "announces", "reports",
    ]
    
    
    def has_term(text: str, term: str) -> bool:
        """Check term match with token boundaries to avoid substring false positives."""
        if not term:
            return False
        pattern = rf"(?<![a-z0-9]){re.escape(term.lower())}(?![a-z0-9])"
        return bool(re.search(pattern, text))
    
    
    def has_any_term(text: str, terms: list[str]) -> bool:
        """Check whether text contains any term using boundary-aware matching."""
        return any(has_term(text, term) for term in terms)
    
    
    # Source credibility scores (0-1)
    SOURCE_CREDIBILITY = {
        "Wall Street Journal": 0.95,
        "WSJ": 0.95,
        "Bloomberg": 0.95,
        "Reuters": 0.90,
        "Financial Times": 0.90,
        "CNBC": 0.80,
        "Yahoo Finance": 0.70,
        "MarketWatch": 0.75,
        "Barron's": 0.85,
        "Seeking Alpha": 0.60,
        "Tagesschau": 0.85,
        "Handelsblatt": 0.80,
    }
    
    # Default config
    DEFAULT_CONFIG = {
        "dedupe_threshold": 0.7,
        "must_read_count": 5,
        "scan_count": 5,
        "must_read_min_score": 0.4,
        "scan_min_score": 0.25,
        "source_cap": 2,
        "weights": {
            "market_impact": 0.40,
            "novelty": 0.20,
            "breadth": 0.20,
            "credibility": 0.10,
            "diversity": 0.10,
        },
    }
    
    
    def normalize_title(title: str) -> str:
        """Normalize title for comparison."""
        if not title:
            return ""
        cleaned = re.sub(r"[^a-z0-9\s]", " ", title.lower())
        tokens = cleaned.split()
        return " ".join(tokens)
    
    
    def title_similarity(a: str, b: str) -> float:
        """Calculate title similarity using SequenceMatcher."""
        if not a or not b:
            return 0.0
        return SequenceMatcher(None, normalize_title(a), normalize_title(b)).ratio()
    
    
    def deduplicate_headlines(headlines: list[dict], threshold: float = 0.7) -> list[dict]:
        """Remove duplicate headlines by title similarity."""
        if not headlines:
            return []
        
        unique = []
        for article in headlines:
            title = article.get("title", "")
            is_dupe = False
            for existing in unique:
                if title_similarity(title, existing.get("title", "")) > threshold:
                    is_dupe = True
                    break
            if not is_dupe:
                unique.append(article)
        
        return unique
    
    
    def classify_category(title: str, description: str = "") -> list[str]:
        """Classify headline into categories based on keywords."""
        text = f"{title} {description}".lower()
        categories = []
        
        for category, keywords in CATEGORY_KEYWORDS.items():
            for keyword in keywords:
                if has_term(text, keyword):
                    categories.append(category)
                    break
    
        has_broad_equity_context = has_any_term(text, BROAD_EARNINGS_CONTEXT)
        has_company_specific_signal = has_any_term(text, COMPANY_SPECIFIC_KEYWORDS)
        has_ticker_pattern = bool(
            re.search(
                r"\$[A-Z]{1,5}\b|\([A-Z]{1,5}(?:\.[A-Z]{1,3})?\)|\b[A-Z]{1,5}\.[A-Z]{1,3}\b",
                f"{title} {description}",
            )
        )
        if (
            (has_company_specific_signal or has_ticker_pattern)
            and not has_broad_equity_context
            and "macro" not in categories
            and "geopolitics" not in categories
        ):
            categories.append("company_specific")
        
        deduped = []
        for cat in categories:
            if cat not in deduped:
                deduped.append(cat)
        return deduped if deduped else ["general"]
    
    
    def score_market_impact(title: str, description: str = "") -> float:
        """Score market impact (0-1)."""
        text = f"{title} {description}".lower()
        score = 0.3  # Base score
        
        # High impact indicators
        high_impact = ["fed", "rate cut", "rate hike", "sanctions", "war", "oil", "recession"]
        for term in high_impact:
            if has_term(text, term):
                score += 0.15
    
        has_earnings = has_any_term(text, ["earnings", "guidance", "eps", "revenue", "profit"])
        has_broad_context = has_any_term(text, BROAD_EARNINGS_CONTEXT)
        if has_earnings and has_broad_context:
            score += 0.12
        
        # Medium impact
        medium_impact = ["profit", "revenue", "gdp", "inflation", "tariff", "merger", "acquisition"]
        for term in medium_impact:
            if has_term(text, term):
                score += 0.1
        
        return min(score, 1.0)
    
    
    def score_novelty(article: dict) -> float:
        """Score novelty based on recency (0-1)."""
        published_at = article.get("published_at")
        if not published_at:
            return 0.5  # Unknown = medium
        
        try:
            if isinstance(published_at, str):
                pub_time = datetime.fromisoformat(published_at.replace("Z", "+00:00"))
            else:
                pub_time = published_at
            
            hours_old = (datetime.now(pub_time.tzinfo) - pub_time).total_seconds() / 3600
            
            if hours_old < 2:
                return 1.0
            elif hours_old < 6:
                return 0.8
            elif hours_old < 12:
                return 0.6
            elif hours_old < 24:
                return 0.4
            else:
                return 0.2
        except Exception:
            return 0.5
    
    
    def score_breadth(categories: list[str]) -> float:
        """Score breadth - sector-wide vs single-stock (0-1)."""
        # More categories = broader impact
        if "company_specific" in categories and "equity_broad" not in categories:
            return 0.2
        if "macro" in categories or "geopolitics" in categories:
            return 0.9
        if "equity_broad" in categories or "energy" in categories:
            return 0.7
        if len(categories) > 1:
            return 0.6
        return 0.4
    
    
    def score_credibility(source: str) -> float:
        """Score source credibility (0-1)."""
        return SOURCE_CREDIBILITY.get(source, 0.5)
    
    
    def calculate_score(article: dict, weights: dict, category_counts: dict) -> float:
        """Calculate overall score for a headline."""
        title = article.get("title", "")
        description = article.get("description", "")
        source = article.get("source", "")
        categories = classify_category(title, description)
        article["_categories"] = categories  # Store for later use
        pure_company_specific = (
            "company_specific" in categories
            and "equity_broad" not in categories
            and "macro" not in categories
            and "geopolitics" not in categories
        )
        article["_pure_company_specific"] = pure_company_specific
        
        # Component scores
        impact = score_market_impact(title, description)
        novelty = score_novelty(article)
        breadth = score_breadth(categories)
        credibility = score_credibility(source)
        
        # Diversity bonus - boost underrepresented categories
        diversity = 0.0
        for cat in categories:
            if category_counts.get(cat, 0) < 1:
                diversity = 0.5
                break
            elif category_counts.get(cat, 0) < 2:
                diversity = 0.3
        
        # Weighted sum
        score = (
            impact * weights.get("market_impact", 0.4) +
            novelty * weights.get("novelty", 0.2) +
            breadth * weights.get("breadth", 0.2) +
            credibility * weights.get("credibility", 0.1) +
            diversity * weights.get("diversity", 0.1)
        )
        if pure_company_specific:
            score -= 0.15
        
        article["_score"] = round(score, 3)
        article["_impact"] = round(impact, 3)
        article["_novelty"] = round(novelty, 3)
        
        return score
    
    
    def apply_source_cap(ranked: list[dict], cap: int = 2) -> list[dict]:
        """Apply source cap - max N items per outlet."""
        source_counts = {}
        result = []
        
        for article in ranked:
            source = article.get("source", "Unknown")
            if source_counts.get(source, 0) < cap:
                result.append(article)
                source_counts[source] = source_counts.get(source, 0) + 1
        
        return result
    
    
    def ensure_diversity(selected: list[dict], candidates: list[dict], required: list[str]) -> list[dict]:
        """Ensure at least one headline from required categories if available."""
        result = list(selected)
        covered = set()
        
        for article in result:
            for cat in article.get("_categories", []):
                covered.add(cat)
        
        for req_cat in required:
            if req_cat not in covered:
                # Find candidate from this category
                for candidate in candidates:
                    if candidate not in result and req_cat in candidate.get("_categories", []):
                        result.append(candidate)
                        covered.add(req_cat)
                        break
        
        return result
    
    
    def rank_headlines(headlines: list[dict], config: dict | None = None) -> dict:
        """
        Rank headlines deterministically.
        
        Args:
            headlines: List of headline dicts with title, source, description, etc.
            config: Optional config overrides
        
        Returns:
            {"must_read": [...], "scan": [...]}
        """
        cfg = {**DEFAULT_CONFIG, **(config or {})}
        weights = cfg.get("weights", DEFAULT_CONFIG["weights"])
        
        if not headlines:
            return {"must_read": [], "scan": []}
        
        # Step 1: Deduplicate
        unique = deduplicate_headlines(headlines, cfg["dedupe_threshold"])
        
        # Step 2: Score all headlines
        category_counts = {}
        for article in unique:
            calculate_score(article, weights, category_counts)
            for cat in article.get("_categories", []):
                category_counts[cat] = category_counts.get(cat, 0) + 1
        
        # Step 3: Sort by score
        ranked = sorted(unique, key=lambda x: x.get("_score", 0), reverse=True)
        
        # Step 4: Apply source cap
        capped = apply_source_cap(ranked, cfg["source_cap"])
        
        # Step 5: Select must_read with diversity quota
        # Leave room for diversity additions by taking count-1 initially
        must_read_candidates = [a for a in capped if a.get("_score", 0) >= cfg["must_read_min_score"]]
        broad_candidates = [a for a in must_read_candidates if not a.get("_pure_company_specific")]
        if len(broad_candidates) >= max(1, cfg["must_read_count"] - 1):
            must_read_candidates = broad_candidates
        must_read_count = cfg["must_read_count"]
        must_read = must_read_candidates[:max(1, must_read_count - 2)]  # Reserve 2 slots for diversity
        diversity_pool = broad_candidates if broad_candidates else capped
        must_read = ensure_diversity(must_read, diversity_pool, ["macro", "equity_broad", "geopolitics"])
        if len(must_read) < must_read_count:
            for candidate in capped:
                if candidate not in must_read:
                    must_read.append(candidate)
                if len(must_read) >= must_read_count:
                    break
        must_read = must_read[:must_read_count]  # Final trim to exact count
        
        # Step 6: Select scan (additional items)
        scan_candidates = [a for a in capped if a not in must_read and a.get("_score", 0) >= cfg["scan_min_score"]]
        scan = scan_candidates[:cfg["scan_count"]]
        
        return {
            "must_read": must_read,
            "scan": scan,
            "total_processed": len(headlines),
            "after_dedupe": len(unique),
        }
    
    
    if __name__ == "__main__":
        # Test with sample data
        test_headlines = [
            {"title": "Fed signals rate cut in March", "source": "WSJ", "description": "Federal Reserve hints at policy shift"},
            {"title": "Apple earnings beat expectations", "source": "CNBC", "description": "Revenue up 15%"},
            {"title": "Oil prices surge on OPEC cuts", "source": "Reuters", "description": "Brent crude hits $90"},
            {"title": "China-US trade tensions escalate", "source": "Bloomberg", "description": "New tariffs announced"},
            {"title": "Tech stocks rally on AI optimism", "source": "Yahoo Finance", "description": "Nvidia leads gains"},
            {"title": "Fed hints at rate reduction", "source": "MarketWatch", "description": "Same story as WSJ"},  # Dupe
        ]
        
        result = rank_headlines(test_headlines)
        print("MUST_READ:")
        for h in result["must_read"]:
            print(f"  [{h['_score']:.2f}] {h['title']} ({h['source']})")
        print("\nSCAN:")
        for h in result["scan"]:
            print(f"  [{h['_score']:.2f}] {h['title']} ({h['source']})")
    
  • scripts/research.py11 KB69b5eaf813c4upstream ↗
    #!/usr/bin/env python3
    """
    Research Module - Manual deep research using the local DeepSeek-V4-Flash
    (DS4) route, with local Kalliope Ornith as fallback.
    Crawls articles, finds correlations, researches companies.
    Outputs research_report.md for later analysis.
    """
    
    import argparse
    import json
    import os
    import sys
    from datetime import datetime
    from pathlib import Path
    
    from utils import call_openai_chat, ensure_venv
    
    from fetch_news import PortfolioError, get_market_news, get_portfolio_news
    
    SCRIPT_DIR = Path(__file__).parent
    CONFIG_DIR = SCRIPT_DIR.parent / "config"
    OUTPUT_DIR = SCRIPT_DIR.parent / "research"
    # Deep research is a genuinely complex / materiality task -> DS4-high primary,
    # local Ornith fallback. Both are OpenAI-compatible tailnet routes.
    DEFAULT_DS4_BASE_URL = "http://100.120.26.16:8888/v1"
    DEFAULT_DS4_MODEL = "deepseek-v4-flash-0731"
    DEFAULT_ORNITH_BASE_URL = "http://100.124.155.99:4000/v1"
    DEFAULT_ORNITH_MODEL = "ornith-1.5:35b-medium"
    RESEARCH_MAX_TOKENS = int(os.getenv("FINANCE_NEWS_RESEARCH_MAX_TOKENS", "2048"))
    RESEARCH_TIMEOUT = int(os.getenv("FINANCE_NEWS_RESEARCH_TIMEOUT", "120"))
    
    
    ensure_venv()
    
    
    def format_market_data(market_data: dict) -> str:
        """Format market data for research prompt."""
        lines = ["## Market Data\n"]
        
        for region, data in market_data.get('markets', {}).items():
            lines.append(f"### {data['name']}")
            for symbol, idx in data.get('indices', {}).items():
                if 'data' in idx and idx['data']:
                    price = idx['data'].get('price', 'N/A')
                    change_pct = idx['data'].get('change_percent', 0)
                    emoji = '📈' if change_pct >= 0 else '📉'
                    lines.append(f"- {idx['name']}: {price} ({change_pct:+.2f}%) {emoji}")
            lines.append("")
        
        return '\n'.join(lines)
    
    
    def format_headlines(headlines: list) -> str:
        """Format headlines for research prompt."""
        lines = ["## Current Headlines\n"]
        
        for article in headlines[:20]:
            source = article.get('source', 'Unknown')
            title = article.get('title', '')
            link = article.get('link', '')
            lines.append(f"- [{source}] {title}")
            if link:
                lines.append(f"  URL: {link}")
        
        return '\n'.join(lines)
    
    
    def format_portfolio_news(portfolio_data: dict) -> str:
        """Format portfolio news for research prompt."""
        lines = ["## Portfolio Analysis\n"]
        
        for symbol, data in portfolio_data.get('stocks', {}).items():
            quote = data.get('quote', {})
            price = quote.get('price', 'N/A')
            change_pct = quote.get('change_percent', 0)
            
            lines.append(f"### {symbol} (${price}, {change_pct:+.2f}%)")
            
            for article in data.get('articles', [])[:5]:
                title = article.get('title', '')
                link = article.get('link', '')
                lines.append(f"- {title}")
                if link:
                    lines.append(f"  URL: {link}")
            lines.append("")
        
        return '\n'.join(lines)
    
    
    def get_ds4_base_url() -> str:
        return (os.getenv("FINANCE_NEWS_DS4_BASE_URL") or DEFAULT_DS4_BASE_URL).strip()
    
    
    def get_ds4_model() -> str:
        return (
            os.getenv("FINANCE_NEWS_DS4_MODEL")
            or os.getenv("DS4_MODEL")
            or DEFAULT_DS4_MODEL
        ).strip()
    
    
    def get_ornith_base_url() -> str:
        return (
            os.getenv("FINANCE_NEWS_ORNITH_BASE_URL")
            or os.getenv("FINANCE_NEWS_QWEN_BASE_URL")
            or DEFAULT_ORNITH_BASE_URL
        ).strip()
    
    
    def get_ornith_model() -> str:
        model = (
            os.getenv("FINANCE_NEWS_ORNITH_MODEL")
            or os.getenv("FINANCE_NEWS_QWEN_MODEL")
            or os.getenv("QWEN_MODEL")
            or DEFAULT_ORNITH_MODEL
        ).strip()
        if not model.startswith("ornith-1.5:"):
            raise ValueError(f"Ornith fallback rejected model override: {model}")
        return model
    
    
    def build_research_prompt(content: str, focus_areas: list | None = None) -> str:
        focus_prompt = ""
        if focus_areas:
            focus_prompt = f"""
    Focus areas for the research:
    {', '.join(f'- {area}' for area in focus_areas)}
    
    Go deep on each area.
    """
        
        prompt = f"""You are an experienced investment research analyst.
    
    Your task is to deliver deep research on current market developments.
    
    {focus_prompt}
    Please analyze the following market data:
    
    {content}
    
    ## Analysis Requirements:
    
    1. **Macro Trends**: What is driving the market today? Which economic data/decisions matter?
    
    2. **Sector Analysis**: Which sectors are performing best/worst? Why?
    
    3. **Company News**: Relevant earnings, M&A, product launches?
    
    4. **Risks**: What downside risks should be noted?
    
    5. **Opportunities**: Which positive developments offer opportunities?
    
    6. **Correlations**: Are there links between different news items/asset classes?
    
    7. **Trade Ideas**: Concrete setups based on the analysis (not financial advice!)
    
    8. **Sources**: Original links for further research
    
    Be analytical, objective, and opinionated where appropriate.
    Deliver a substantial report (500-800 words).
    """
        return prompt
    
    
    def research_with_ds4(content: str, focus_areas: list | None = None) -> str:
        """Perform deep research using the local DS4-high route (primary)."""
        prompt = build_research_prompt(content, focus_areas)
        api_key = (os.getenv("FINANCE_NEWS_DS4_API_KEY") or "").strip() or None
        return call_openai_chat(
            prompt,
            base_url=get_ds4_base_url(),
            model=get_ds4_model(),
            api_key=api_key,
            max_tokens=RESEARCH_MAX_TOKENS,
            timeout=RESEARCH_TIMEOUT,
            error_label="DS4 research error",
        )
    
    
    def research_with_ornith(content: str, focus_areas: list | None = None) -> str:
        """Perform deep research using the local Ornith fallback route."""
        prompt = build_research_prompt(content, focus_areas)
        api_key = (os.getenv("KALLIOPE_SERVING_API_KEY") or "").strip()
        if not api_key:
            return "⚠️ Ornith research error: KALLIOPE_SERVING_API_KEY not set"
        try:
            model = get_ornith_model()
        except ValueError as exc:
            return f"⚠️ Ornith research error: {exc}"
        return call_openai_chat(
            prompt,
            base_url=get_ornith_base_url(),
            model=model,
            api_key=api_key,
            max_tokens=RESEARCH_MAX_TOKENS,
            timeout=RESEARCH_TIMEOUT,
            error_label="Ornith research error",
            reasoning_effort=(
                os.getenv("FINANCE_NEWS_ORNITH_REASONING_EFFORT")
                or os.getenv("FINANCE_NEWS_QWEN_REASONING_EFFORT")
                or None
            ),
        )
    
    
    def format_raw_data_report(market_data: dict, portfolio_data: dict) -> str:
        parts = []
        if market_data:
            parts.append(format_market_data(market_data))
            if market_data.get('headlines'):
                parts.append(format_headlines(market_data['headlines']))
        if portfolio_data and 'error' not in portfolio_data:
            parts.append(format_portfolio_news(portfolio_data))
        return '\n\n'.join(parts)
    
    
    def generate_research_content(market_data: dict, portfolio_data: dict, focus_areas: list = None) -> dict:
        raw_report = format_raw_data_report(market_data, portfolio_data)
        if not raw_report.strip():
            return {
                'report': '',
                'source': 'none'
            }
        report = research_with_ds4(raw_report, focus_areas)
        if not report.startswith("⚠️"):
            return {
                'report': report,
                'source': 'ds4'
            }
        print(f"  ↳ {report}; falling back to Ornith route", file=sys.stderr)
        report = research_with_ornith(raw_report, focus_areas)
        if not report.startswith("⚠️"):
            return {
                'report': report,
                'source': 'ornith'
            }
        print(f"  ↳ {report}; using raw data report", file=sys.stderr)
        return {
            'report': raw_report,
            'source': 'raw'
        }
    
    
    def generate_research_report(args):
        """Generate full research report."""
        OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
        
        config_path = CONFIG_DIR / "config.json"
        if not config_path.exists():
            print("⚠️ No config found. Run 'finance-news wizard' first.", file=sys.stderr)
            sys.exit(1)
        
        # Fetch fresh data
        print("📡 Fetching market data...", file=sys.stderr)
        
        # Get market overview
        market_data = get_market_news(
            args.limit if hasattr(args, 'limit') else 5,
            regions=args.regions.split(',') if hasattr(args, 'regions') else ["us", "europe"],
            max_indices_per_region=2
        )
        
        # Get portfolio news
        try:
            portfolio_data = get_portfolio_news(
                args.limit if hasattr(args, 'limit') else 5,
                args.max_stocks if hasattr(args, 'max_stocks') else 10
            )
        except PortfolioError as exc:
            print(f"⚠️ Skipping portfolio: {exc}", file=sys.stderr)
            portfolio_data = None
        
        # Build report
        focus_areas = None
        if hasattr(args, 'focus') and args.focus:
            focus_areas = args.focus.split(',')
    
        research_result = generate_research_content(market_data, portfolio_data, focus_areas)
        research_report = research_result['report']
        source = research_result['source']
    
        if not research_report.strip():
            print("⚠️ No data available for research", file=sys.stderr)
            return
    
        if source == 'ds4':
            print("🔬 Running deep research with DS4-high route...", file=sys.stderr)
        elif source == 'ornith':
            print("🔬 Running deep research with Ornith route...", file=sys.stderr)
        else:
            print("🧾 LLM research unavailable; using raw data report", file=sys.stderr)
        
        # Add metadata header
        timestamp = datetime.now().isoformat()
        date_str = datetime.now().strftime("%Y-%m-%d %H:%M")
        
        full_report = f"""# Market Research Report
    **Generiert:** {date_str}
    **Quelle:** Finance News Skill
    
    ---
    
    {research_report}
    
    ---
    
    *This report was generated automatically. Not financial advice.*
    """
        
        # Save to file
        output_file = OUTPUT_DIR / f"research_{datetime.now().strftime('%Y-%m-%d')}.md"
        with open(output_file, 'w') as f:
            f.write(full_report)
        
        print(f"✅ Research report saved to: {output_file}", file=sys.stderr)
        
        # Also output to stdout
        if args.json:
            print(json.dumps({
                'report': research_report,
                'saved_to': str(output_file),
                'timestamp': timestamp
            }))
        else:
            print("\n" + "="*60)
            print("RESEARCH REPORT")
            print("="*60)
            print(research_report)
    
    
    def main():
        parser = argparse.ArgumentParser(description='Deep Market Research')
        parser.add_argument('--limit', type=int, default=5, help='Max headlines per source')
        parser.add_argument('--regions', default='us,europe', help='Comma-separated regions')
        parser.add_argument('--max-stocks', type=int, default=10, help='Max portfolio stocks')
        parser.add_argument('--focus', help='Focus areas (comma-separated)')
        parser.add_argument('--json', action='store_true', help='Output as JSON')
        
        args = parser.parse_args()
        generate_research_report(args)
    
    
    if __name__ == '__main__':
        main()
    
  • scripts/setup.py9.9 KB4f12d6834c26upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/stocks.py11 KBb08436242a9aupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/summarize.py84 KB92dd9d1bb8e2upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/translate_portfolio.py5.9 KBe5b8663173a1upstream ↗
    #!/usr/bin/env python3
    """Translate portfolio headlines in briefing JSON using Kalliope Ornith.
    
    Usage: python3 translate_portfolio.py /path/to/briefing.json [--lang de]
    
    Reads briefing JSON, translates portfolio article headlines via Ornith,
    writes back the modified JSON.
    """
    
    import argparse
    import json
    import os
    import re
    import sys
    
    from utils import call_openai_chat
    
    
    DEFAULT_ORNITH_BASE_URL = "http://100.124.155.99:4000/v1"
    DEFAULT_ORNITH_MODEL = "ornith-1.5:35b-medium"
    
    
    def extract_headlines(portfolio_message: str) -> list[str]:
        """Extract article headlines (lines starting with •) from portfolio message."""
        headlines = []
        for line in portfolio_message.split('\n'):
            line = line.strip()
            if line.startswith('•'):
                # Remove bullet, reference number, and clean up
                # Format: "• Headline text [1]"
                match = re.match(r'•\s*(.+?)\s*\[\d+\]$', line)
                if match:
                    headlines.append(match.group(1))
                else:
                    # No reference number
                    headlines.append(line[1:].strip())
        return headlines
    
    
    def translate_headlines(headlines: list[str], lang: str = "de") -> list[str]:
        """Translate headlines directly through the scheduled Ornith route."""
        if not headlines:
            return []
    
        prompt = """Translate these English headlines to German.
    Return ONLY a JSON array of strings in the same order.
    Example: ["Übersetzung 1", "Übersetzung 2"]
    Do not add commentary.
    
    Headlines:
    """
        for idx, title in enumerate(headlines, start=1):
            prompt += f"{idx}. {title}\n"
    
        api_key = (os.getenv("KALLIOPE_SERVING_API_KEY") or "").strip()
        if not api_key:
            print("⚠️ Translation failed: KALLIOPE_SERVING_API_KEY not set", file=sys.stderr)
            return headlines
    
        model = (
            os.getenv("FINANCE_NEWS_ORNITH_MODEL")
            or os.getenv("FINANCE_NEWS_QWEN_MODEL")
            or DEFAULT_ORNITH_MODEL
        ).strip()
        if not model.startswith("ornith-1.5:"):
            print(f"⚠️ Translation rejected non-Ornith model override: {model}", file=sys.stderr)
            return headlines
    
        reply = call_openai_chat(
            prompt,
            base_url=(
                os.getenv("FINANCE_NEWS_ORNITH_BASE_URL")
                or os.getenv("FINANCE_NEWS_QWEN_BASE_URL")
                or DEFAULT_ORNITH_BASE_URL
            ).strip(),
            model=model,
            api_key=api_key,
            max_tokens=600,
            timeout=60,
            error_label="Ornith translation error",
        )
        if reply.startswith("⚠️"):
            print(f"⚠️ Translation failed: {reply}", file=sys.stderr)
            return headlines
    
        # Parse JSON array from reply
        json_text = reply.strip()
        if "```" in json_text:
            match = re.search(r'```(?:json)?\s*(.*?)```', json_text, re.DOTALL)
            if match:
                json_text = match.group(1).strip()
    
        try:
            translated = json.loads(json_text)
            if isinstance(translated, list) and len(translated) == len(headlines):
                print(f"✅ Translated {len(headlines)} portfolio headlines", file=sys.stderr)
                return translated
        except json.JSONDecodeError as e:
            print(f"⚠️ JSON parse error: {e}", file=sys.stderr)
    
        print("⚠️ Translation failed, using original headlines", file=sys.stderr)
        return headlines
    
    
    def replace_headlines(portfolio_message: str, original: list[str], translated: list[str]) -> str:
        """Replace original headlines with translated ones in portfolio message."""
        result = portfolio_message
        for orig, trans in zip(original, translated):
            if orig != trans:
                # Replace the headline text, preserving bullet and reference
                result = result.replace(f"• {orig}", f"• {trans}")
        return result
    
    
    def has_pretranslated_portfolio(data: dict) -> bool:
        """Return True when all relevant portfolio headlines already have title_de."""
        raw_portfolio = (data.get("raw_data") or {}).get("portfolio") or {}
        saw_relevant_headline = False
        for stock_data in (raw_portfolio.get("stocks") or {}).values():
            for article in stock_data.get("articles", [])[:2]:
                title = (article.get("title") or "").strip()
                if not title:
                    continue
                saw_relevant_headline = True
                if not (article.get("title_de") or "").strip():
                    return False
        return saw_relevant_headline
    
    
    def main():
        parser = argparse.ArgumentParser(description='Translate portfolio headlines')
        parser.add_argument('json_file', help='Path to briefing JSON file')
        parser.add_argument('--lang', default='de', help='Target language (default: de)')
        args = parser.parse_args()
    
        # Read JSON
        try:
            with open(args.json_file, 'r') as f:
                data = json.load(f)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f"❌ Error reading {args.json_file}: {e}", file=sys.stderr)
            sys.exit(1)
    
        portfolio_message = data.get('portfolio_message', '')
        if not portfolio_message:
            print("No portfolio_message to translate", file=sys.stderr)
            print(json.dumps(data, ensure_ascii=False, indent=2))
            return
    
        if has_pretranslated_portfolio(data):
            print("Portfolio headlines already translated; skipping", file=sys.stderr)
            return
    
        # Extract, translate, replace
        headlines = extract_headlines(portfolio_message)
        if not headlines:
            print("No headlines found in portfolio_message", file=sys.stderr)
            print(json.dumps(data, ensure_ascii=False, indent=2))
            return
    
        print(f"📝 Found {len(headlines)} headlines to translate", file=sys.stderr)
        translated = translate_headlines(headlines, args.lang)
    
        # Update portfolio message
        data['portfolio_message'] = replace_headlines(portfolio_message, headlines, translated)
    
        # Write back
        with open(args.json_file, 'w') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
    
        print(f"✅ Updated {args.json_file}", file=sys.stderr)
    
    
    if __name__ == '__main__':
        main()
    
  • scripts/utils.py4.7 KB8ca399b96188upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/venv-setup.sh3.4 KB08ac44178a4cupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • .github/workflows/ci.yml1.3 KB253263c1d6a4upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • .gitignore353 Bdc9452811ed8upstream ↗
    # Cache files
    cache/
    .coverage
    *.pyc
    __pycache__/
    
    # Environment
    .env
    .venv/
    venv/
    
    # IDE
    .idea/
    .vscode/
    *.swp
    *.swo
    
    # OS
    .DS_Store
    Thumbs.db
    
    # Sensitive credentials
    config/cookies.json
    *.cookie
    config/portfolio.csv
    config/sources.json
    config/translations.json
    
    # Personal data
    config/stocks.json
    config/alerts.json
    config/moltbot-cron-backup-*.json
    
  • COMMANDS.md2.4 KB880012f72c78upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • config/alerts.json.example766 B9022b3126d7aupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • config/config.json13 KBbd348b2719b0upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • config/manual_earnings.json5.8 KB33ba2ffbeedbupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • config/portfolio.csv.example1.6 KB9b2b3d6fbb11upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • config/portfolio_benchmarks.json5.3 KBfcc9568c312eupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • cron/alerts.sh709 Bebb2f4807cdbupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • cron/earnings-weekly.sh708 Bb972a17dca8aupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • cron/earnings.sh688 B71f98639203eupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • cron/evening.sh711 B81ce165cd95dupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • cron/morning.sh710 B2bd4a9e70a82upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • Dockerfile1.1 KB429a87ab9f67upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/EQUITY_SHEET_FIXES.md4.8 KB9afa32603165upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/plans/2026-05-01-001-feat-morning-portfolio-attribution-plan.md17 KB6645a9a3f73dupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/plans/2026-05-05-001-fix-portfolio-headline-quality-ranking-plan.md7.5 KB30d6280621ccupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/PREMIUM_SOURCES.md6.2 KB28d6e77e47e3upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • LICENSE11 KB98c71f20f25dupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • nested-clone-source-records-retire.decision.md2.3 KBad0b310427f4upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • pyproject.toml1.1 KB887af2c55e13upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • pytest.ini225 B7c1dd9854daaupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • requirements-test.txt72 Bb1c4294cea7dupstream ↗
    # Test dependencies
    pytest>=7.4.0
    pytest-cov>=4.1.0
    pytest-mock>=3.12.0
    
  • requirements.txt28 B93c304fed4edupstream ↗
    feedparser>=6.0.11
    yfinance
    
  • tests/test_alerts.py4.0 KB06c90417ee17upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_alerts_extended.py13 KB4401937e6b67upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_briefing.py3.8 KB191e3f6058deupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_earnings.py3.7 KBd5224ae16601upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_fetch_budget.py2.3 KB88d6798d068aupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_fetch_news.py7.7 KBfdeb24f0398cupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_finance_news_cli.py2.1 KBa446164319c2upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_portfolio.py2.6 KB1de4b3344587upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_portfolio_attribution.py11 KBaa6350a5d2deupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_ranking.py4.6 KBb7d5affa8a19upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_research.py14 KB455d697a513fupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_setup.py2.5 KBb2b4465a502bupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_stocks.py9.4 KB5fcb5d777497upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_summarize.py61 KB622f8fb1f02cupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_translate_portfolio.py3.2 KBa6a99839e6ccupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • THEORY.MD3.5 KB55c4612ba4e7upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • uv.lock223 KB504bb2f86c8cupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • workflows/alerts-cron.yaml1.6 KBbf08f99e42b4upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • workflows/briefing-cron.yaml4.5 KBc5bc9e1cc83eupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • workflows/briefing.yaml4.9 KB4af33cea92a9upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • workflows/earnings-cron.yaml1.5 KB2175cda1b3abupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • workflows/earnings-weekly-cron.yaml1.5 KB5ad54ad56c4cupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • .coverageupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • .githubupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • configupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • cronupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docsupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scriptsupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • testsupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • workflowsupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

Plain-text copy, no login: /skill-bundles/finance-news-openclaw-skill.md

// REPO STATS

16 stars
6 open issues
Last commit: 8d ago