📄 market_briefing.py 2,489 bytes Apr 27, 2026 📋 Raw

"""Market sentiment Telegram handler.

Commands:
/briefing — Generate and send market briefing
/watchlist — Show/edit watchlist
"""

import logging

from icarus.core.market.sentiment import (
_load_watchlist,
_save_watchlist,
generate_briefing,
format_briefing,
)

async def handle_briefing_command(message: dict, bot) -> None:
"""Handle /briefing command."""
chat_id = message["chat"]["id"]

# Send loading message
loading = await bot.send_message(
    chat_id=chat_id,
    text="📊 Fetching market data..."
)

try:
    # Generate briefing
    tickers = _load_watchlist()
    briefing = await generate_briefing(tickers)
    text = format_briefing(briefing)

    # Edit loading message
    await bot.edit_message_text(
        chat_id=chat_id,
        message_id=loading["message_id"],
        text=text,
    )

except Exception as e:
    logging.error("Failed to generate briefing: %s", e)
    await bot.edit_message_text(
        chat_id=chat_id,
        message_id=loading["message_id"],
        text=f"❌ Error generating briefing: {e}"
    )

async def handle_watchlist_command(message: dict, bot) -> None:
"""Handle /watchlist command — show current list."""
tickers = _load_watchlist()
text = (
"📋 Current Watchlist:\n\n"
+ "\n".join(f" {i+1}. {t}" for i, t in enumerate(tickers))
+ "\n\nTo update, reply with:\n"
+ "watchlist AAPL MSFT TSLA NVDA"
)
await bot.send_message(
chat_id=message["chat"]["id"],
text=text,
)

async def handle_watchlist_update(message: dict, bot) -> None:
"""Handle 'watchlist TICKER TICKER ...' message."""
text = message.get("text", "")
parts = text.split()

if len(parts) < 2:
    await bot.send_message(
        chat_id=message["chat"]["id"],
        text="Usage: `watchlist AAPL MSFT TSLA`"
    )
    return

new_tickers = [p.upper() for p in parts[1:] if p.isalpha()]

if not new_tickers:
    await bot.send_message(
        chat_id=message["chat"]["id"],
        text="❌ No valid tickers found. Use format: `watchlist AAPL MSFT`"
    )
    return

_save_watchlist(new_tickers)

await bot.send_message(
    chat_id=message["chat"]["id"],
    text=f"✅ Watchlist updated ({len(new_tickers)} tickers):\n" + ", ".join(new_tickers)
)