Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions NewsAlerts.spec
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ from PyInstaller.utils.hooks import collect_data_files, collect_submodules

block_cipher = None

# Read application version dynamically from root VERSION (SSOT)
_ver_file = Path('VERSION')
app_version = _ver_file.read_text(encoding='utf-8').strip() if _ver_file.is_file() else '2.12.1'

# Collect tzdata for zoneinfo on Windows
tzdata_datas = collect_data_files('tzdata')

Expand Down Expand Up @@ -117,8 +121,8 @@ if sys.platform == 'darwin':
'CFBundleName': 'NewsAlerts',
'CFBundleDisplayName': 'NewsAlerts',
'CFBundleIdentifier': 'com.mlgitdev.newsalerts',
'CFBundleVersion': '2.9.0',
'CFBundleShortVersionString': '2.9.0',
'CFBundleVersion': app_version,
'CFBundleShortVersionString': app_version,
'NSHighResolutionCapable': True,
'LSMinimumSystemVersion': '12.0',
},
Expand Down
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
2.12.0
2.12.1
31 changes: 25 additions & 6 deletions app/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
import json
import logging
import threading
import urllib.parse
import webbrowser

from . import sessions as S
from .borrow import ALPACA_LIVE_API, ALPACA_PAPER_API, alpaca_trading_base
from .news import NewsService
from .sounds import list_sounds
from .version import get_version, get_version_info
Expand Down Expand Up @@ -52,6 +54,7 @@ class Api:
# Attributes prefixed with "_" are not exposed to JS by pywebview.
def __init__(self, app) -> None:
self._app = app
self._focused = True

# ----------------------------------------------------------------- state
def get_state(self):
Expand Down Expand Up @@ -107,6 +110,7 @@ def save_config(self, cfg: dict):
paused=False
)
a.sounds.muted = is_paused
a.sounds.suppressed = bool(self._focused) and bool(ac.get("quiet_when_focused", False))
if "volume" in ac:
a.sounds.set_volume(int(ac["volume"]))
a.screener.poke()
Expand Down Expand Up @@ -136,7 +140,11 @@ def test_alpaca(self, key_id: str = "", secret_key: str = ""):
try:
import requests
headers = {"APCA-API-KEY-ID": kid, "APCA-API-SECRET-KEY": sec}
r = requests.get("https://paper-api.alpaca.markets/v2/account", headers=headers, timeout=6)
base = alpaca_trading_base(kid)
r = requests.get(f"{base}/v2/account", headers=headers, timeout=6)
if r.status_code in (401, 403):
alt_base = ALPACA_LIVE_API if base == ALPACA_PAPER_API else ALPACA_PAPER_API
r = requests.get(f"{alt_base}/v2/account", headers=headers, timeout=6)
if r.status_code == 200:
acc = r.json()
bp = acc.get("buying_power", "0")
Expand All @@ -152,7 +160,8 @@ def test_alpaca(self, key_id: str = "", secret_key: str = ""):

def set_focused(self, focused: bool):
a = self._app
a.sounds.suppressed = bool(focused) and bool(a.cfg["alerts"]["quiet_when_focused"])
self._focused = bool(focused)
a.sounds.suppressed = self._focused and bool(a.cfg["alerts"]["quiet_when_focused"])
return True

# ------------------------------------------------------------------ news
Expand All @@ -170,7 +179,15 @@ def get_story(self, story_id: str):
return self._app.news.story(story_id)

def get_bamsec(self, ticker: str, force: bool = False):
cfg = getattr(self._app, "config", {}).get("news", {})
raw_cfg = None
if hasattr(self._app, "cfg") and hasattr(self._app.cfg, "get"):
cand = self._app.cfg.get()
if isinstance(cand, dict):
raw_cfg = cand
if raw_cfg is None:
cand = getattr(self._app, "config", None)
raw_cfg = cand if isinstance(cand, dict) else {}
cfg = raw_cfg.get("news", {})
if not cfg.get("bamsec_enabled", True):
return {"ticker": ticker, "company": ticker, "bamsec_url": "", "categories": {}, "all_filings": [], "total": 0, "disabled": True}
if hasattr(self._app, "bamsec"):
Expand Down Expand Up @@ -223,12 +240,14 @@ def play_alert(self, kind: str):
return False

def open_url(self, url: str):
if url.startswith("http"):
webbrowser.open(url)
raw = str(url or "").strip()
if raw.lower().startswith(("http://", "https://")):
webbrowser.open(raw)
return True

def open_chart(self, ticker: str):
webbrowser.open(f"https://www.tradingview.com/chart/?symbol={ticker}")
safe_ticker = urllib.parse.quote(str(ticker or "").strip(), safe=":")
webbrowser.open(f"https://www.tradingview.com/chart/?symbol={safe_ticker}")
return True

def open_app_dir(self):
Expand Down
25 changes: 18 additions & 7 deletions app/bamsec.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""BamSEC SEC filings provider, parser, and caching service."""
from __future__ import annotations

from collections import OrderedDict
import html
import logging
import re
Expand Down Expand Up @@ -44,10 +45,11 @@ def form_group(form: str) -> str:
class BamSECService:
"""Fetches, parses, and caches SEC filings directly from BamSEC."""

def __init__(self, ttl: float = 120.0, timeout: float = 7.0) -> None:
def __init__(self, ttl: float = 120.0, timeout: float = 7.0, max_cache: int = 200) -> None:
self.ttl = ttl
self.timeout = timeout
self._cache: dict[str, tuple[float, dict[str, Any]]] = {}
self._max_cache = max_cache
self._cache: OrderedDict[str, tuple[float, float, dict[str, Any]]] = OrderedDict()
self._lock = threading.Lock()

def get_filings(self, ticker: str, force: bool = False) -> dict[str, Any]:
Expand All @@ -67,8 +69,9 @@ def get_filings(self, ticker: str, force: bool = False) -> dict[str, Any]:
now = time.time()
with self._lock:
hit = self._cache.get(sym)
if hit and not force and (now - hit[0] < self.ttl):
return hit[1]
if hit and not force and (now - hit[0] < hit[1]):
self._cache.move_to_end(sym)
return hit[2]

url = f"https://www.bamsec.com/search?q={sym}"
headers = {
Expand All @@ -89,13 +92,21 @@ def get_filings(self, ticker: str, force: bool = False) -> dict[str, Any]:
"total": 0,
"error": f"BamSEC returned HTTP {r.status_code}",
}
with self._lock:
self._cache[sym] = (now, res)
# Do not cache transient 429 / 5xx errors; use short 15s negative TTL for 4xx not-found
if r.status_code not in (429,) and r.status_code < 500:
with self._lock:
self._cache[sym] = (now, min(15.0, self.ttl), res)
self._cache.move_to_end(sym)
while len(self._cache) > self._max_cache:
self._cache.popitem(last=False)
return res

parsed = self.parse_html(sym, r.text, r.url)
with self._lock:
self._cache[sym] = (now, parsed)
self._cache[sym] = (now, self.ttl, parsed)
self._cache.move_to_end(sym)
while len(self._cache) > self._max_cache:
self._cache.popitem(last=False)
return parsed

except Exception as e:
Expand Down
62 changes: 51 additions & 11 deletions app/borrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,17 @@
STATUS_NA: "N/A",
}

ALPACA_PAPER_API = "https://paper-api.alpaca.markets"
ALPACA_LIVE_API = "https://api.alpaca.markets"


def alpaca_trading_base(key_id: str) -> str:
"""Select Paper vs Live Alpaca trading API endpoint based on key prefix (PK=paper, AK=live)."""
kid = (key_id or "").strip().upper()
if kid.startswith("PK"):
return ALPACA_PAPER_API
return ALPACA_LIVE_API


def load_alpaca_secrets() -> tuple[str, str]:
p = find_secrets_file()
Expand Down Expand Up @@ -86,11 +97,15 @@ def update_credentials(self, key_id: str, secret_key: str, mode: str = "auto") -
secret_key = secret_key or s
kid = (key_id or "").strip()
sec = (secret_key or "").strip()
if kid == self.key_id and sec == self.secret_key and mode == self.mode and len(self._cache) > 0:
changed = (kid != self.key_id or sec != self.secret_key or mode != self.mode)
if not changed and len(self._cache) > 0:
return
self.key_id = kid
self.secret_key = sec
self.mode = mode
if changed:
self._cache.clear()
self._details.clear()
if self.key_id and self.secret_key and self.mode in ("auto", "alpaca"):
threading.Thread(target=self._sync_bulk_assets, daemon=True, name="alpaca-bulk-assets").start()

Expand Down Expand Up @@ -131,15 +146,26 @@ def _classify_alpaca_asset(self, a: dict) -> tuple[str, dict]:
def _sync_bulk_assets(self) -> None:
"""Fetch all active US equity assets from Alpaca to pre-populate locate data in memory."""
try:
url = "https://paper-api.alpaca.markets/v2/assets?status=active&asset_class=us_equity"
with self._lock:
kid = self.key_id
sec = self.secret_key
if not (kid and sec):
return
base = alpaca_trading_base(kid)
url = f"{base}/v2/assets?status=active&asset_class=us_equity"
headers = {
"APCA-API-KEY-ID": self.key_id,
"APCA-API-SECRET-KEY": self.secret_key,
"APCA-API-KEY-ID": kid,
"APCA-API-SECRET-KEY": sec,
}
r = requests.get(url, headers=headers, timeout=15)
if r.status_code in (401, 403):
alt_base = ALPACA_LIVE_API if base == ALPACA_PAPER_API else ALPACA_PAPER_API
r = requests.get(f"{alt_base}/v2/assets?status=active&asset_class=us_equity", headers=headers, timeout=15)
if r.status_code == 200:
assets = r.json()
with self._lock:
if self.mode not in ("auto", "alpaca"):
return
for a in assets:
sym = str(a.get("symbol", "")).upper()
st, details = self._classify_alpaca_asset(a)
Expand Down Expand Up @@ -225,15 +251,22 @@ def _estimate(self, sym: str, float_shares: float | None) -> dict:
return {"status": STATUS_EASY, "label": LABEL_MAP[STATUS_EASY], "source": "heuristic"}

def _query_alpaca(self, sym: str) -> dict | None:
if not (self.key_id and self.secret_key):
with self._lock:
kid = self.key_id
sec = self.secret_key
if not (kid and sec):
return None
url = f"https://paper-api.alpaca.markets/v2/assets/{sym}"
base = alpaca_trading_base(kid)
url = f"{base}/v2/assets/{sym}"
headers = {
"APCA-API-KEY-ID": self.key_id,
"APCA-API-SECRET-KEY": self.secret_key,
"APCA-API-KEY-ID": kid,
"APCA-API-SECRET-KEY": sec,
}
try:
r = requests.get(url, headers=headers, timeout=5)
if r.status_code in (401, 403):
alt_base = ALPACA_LIVE_API if base == ALPACA_PAPER_API else ALPACA_PAPER_API
r = requests.get(f"{alt_base}/v2/assets/{sym}", headers=headers, timeout=5)
if r.status_code == 200:
d = r.json()
st, details = self._classify_alpaca_asset(d)
Expand All @@ -251,14 +284,21 @@ def _worker(self) -> None:
while True:
sym, float_shares, cb = self.q.get()
try:
with self._lock:
mode = self.mode
has_keys = bool(self.key_id and self.secret_key)
result = None
if self.key_id and self.secret_key and self.mode in ("auto", "alpaca"):
if has_keys and mode in ("auto", "alpaca"):
result = self._query_alpaca(sym)
if not result:
result = self._estimate(sym, float_shares)
if mode == "alpaca":
result = {"status": STATUS_NA, "label": LABEL_MAP[STATUS_NA], "source": "alpaca"}
else:
result = self._estimate(sym, float_shares)

with self._lock:
self._cache[sym] = result
if self.mode == mode:
self._cache[sym] = result

if cb:
cb(sym, result)
Expand Down
36 changes: 31 additions & 5 deletions app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import os
import sys
import threading
from pathlib import Path
from pathlib import Path, PurePosixPath

def get_app_dir() -> Path:
"""Resolve and ensure the application data directory exists across all operating systems.
Expand Down Expand Up @@ -73,6 +73,19 @@ def get_app_dir() -> Path:
)


def _default_sound_path(win_name: str, mac_name: str, linux_candidates: tuple[str, ...]) -> str:
"""Resolve an OS-native default alert sound path without mixing path separators."""
if sys.platform == "win32":
return str(Path(MEDIA) / win_name)
if sys.platform == "darwin":
return str(PurePosixPath(MEDIA) / mac_name)
for rel in linux_candidates:
candidate = Path(MEDIA) / rel
if candidate.is_file():
return str(candidate)
return ""


def find_secrets_file() -> Path | None:
"""Find keys.toml / secrets.toml in standard locations:
1. %APPDATA%\\NewsAlerts\\keys.toml or secrets.toml
Expand Down Expand Up @@ -128,6 +141,7 @@ def find_secrets_file() -> Path | None:

DEFAULT_HOTKEYS = {
"mute": "m",
"toggle_telegram": "Ctrl+Shift+T",
"popout_tape": "t",
"pause_tape": "Space",
"settings": "s",
Expand All @@ -150,11 +164,23 @@ def find_secrets_file() -> Path | None:
"mute": False,
"volume": 80,
"quiet_when_focused": False,
"sound_new_symbol": MEDIA + r"\Windows Notify System Generic.wav",
"sound_new_symbol": _default_sound_path(
"Windows Notify System Generic.wav",
"Glass.aiff",
("freedesktop/stereo/message-new-instant.oga", "freedesktop/stereo/bell.oga", "alsa/Front_Center.wav"),
),
"news_sound_enabled": True,
"sound_news": MEDIA + r"\Windows Ding.wav",
"sound_news": _default_sound_path(
"Windows Ding.wav",
"Ping.aiff",
("freedesktop/stereo/message.oga", "freedesktop/stereo/complete.oga", "alsa/Front_Center.wav"),
),
"tape_sound_enabled": False,
"sound_tape": MEDIA + r"\Windows Navigation Start.wav",
"sound_tape": _default_sound_path(
"Windows Navigation Start.wav",
"Pop.aiff",
("freedesktop/stereo/audio-volume-change.oga", "freedesktop/stereo/bell.oga", "alsa/Front_Center.wav"),
),
"telegram_enabled": True,
"telegram_tape_enabled": True,
"telegram_tape_cooldown_sec": 60,
Expand Down Expand Up @@ -215,7 +241,7 @@ def _merge(base: dict, override: dict) -> dict:
if isinstance(v, dict) and isinstance(out.get(k), dict):
out[k] = _merge(out[k], v)
else:
out[k] = v
out[k] = copy.deepcopy(v)
# Ensure any new default tape strategies are added to existing configs, respecting user deletions
if "tape" in out and isinstance(out["tape"], dict) and "strategies" in out["tape"]:
deleted = set(out["tape"].get("deleted_strategies", []))
Expand Down
Loading
Loading