Added logger.

This commit is contained in:
2025-07-22 15:35:37 +02:00
parent afe3cecb4f
commit d4ed76e153
5 changed files with 88 additions and 34 deletions

View File

@@ -12,17 +12,20 @@ from dotenv import load_dotenv
from . import database
from .ticker_extractor import extract_tickers
from .sentiment_analyzer import get_sentiment_score
from .logger_setup import get_logger
load_dotenv()
MARKET_CAP_REFRESH_INTERVAL = 86400
POST_AGE_LIMIT = 86400
log = get_logger()
def load_subreddits(filepath):
try:
with open(filepath, 'r') as f:
return json.load(f).get("subreddits", [])
except (FileNotFoundError, json.JSONDecodeError) as e:
print(f"Error loading config file '{filepath}': {e}")
log.error(f"Error loading config file '{filepath}': {e}")
return None
def get_financial_data(ticker_symbol):
@@ -52,7 +55,7 @@ def scan_subreddits(reddit, subreddits_list, post_limit=100, comment_limit=100,
post_age_limit = days_to_scan * 86400
current_time = time.time()
print(f"\nScanning {len(subreddits_list)} subreddit(s) for NEW posts in the last {days_to_scan} day(s)...")
log.info(f"\nScanning {len(subreddits_list)} subreddit(s) for NEW posts in the last {days_to_scan} day(s)...")
for subreddit_name in subreddits_list:
try:
# Always use the lowercase version of the name for consistency.
@@ -60,14 +63,12 @@ def scan_subreddits(reddit, subreddits_list, post_limit=100, comment_limit=100,
subreddit_id = database.get_or_create_entity(conn, 'subreddits', 'name', normalized_sub_name)
subreddit = reddit.subreddit(normalized_sub_name)
print(f"Scanning r/{normalized_sub_name}...")
log.info(f"Scanning r/{normalized_sub_name}...")
for submission in subreddit.new(limit=post_limit):
if (current_time - submission.created_utc) > post_age_limit:
print(f" -> Reached posts older than the {days_to_scan}-day limit.")
log.info(f" -> Reached posts older than the {days_to_scan}-day limit.")
break
# --- NEW HYBRID LOGIC ---
tickers_in_title = set(extract_tickers(submission.title))
all_tickers_found_in_post = set(tickers_in_title) # Start a set to track all tickers for financials
@@ -77,7 +78,7 @@ def scan_subreddits(reddit, subreddits_list, post_limit=100, comment_limit=100,
# --- CASE A: Tickers were found in the title ---
if tickers_in_title:
print(f" -> Title Mention(s): {', '.join(tickers_in_title)}. Attributing all comments.")
log.info(f" -> Title Mention(s): {', '.join(tickers_in_title)}. Attributing all comments.")
post_sentiment = get_sentiment_score(submission.title)
# Add one 'post' mention for each title ticker
@@ -109,7 +110,7 @@ def scan_subreddits(reddit, subreddits_list, post_limit=100, comment_limit=100,
ticker_id = database.get_or_create_entity(conn, 'tickers', 'symbol', ticker_symbol)
ticker_info = database.get_ticker_info(conn, ticker_id)
if not ticker_info['last_updated'] or (current_time - ticker_info['last_updated'] > MARKET_CAP_REFRESH_INTERVAL):
print(f" -> Fetching financial data for {ticker_symbol}...")
log.info(f" -> Fetching financial data for {ticker_symbol}...")
financials = get_financial_data(ticker_symbol)
database.update_ticker_financials(
conn, ticker_id,
@@ -129,10 +130,10 @@ def scan_subreddits(reddit, subreddits_list, post_limit=100, comment_limit=100,
database.add_or_update_post_analysis(conn, post_analysis_data)
except Exception as e:
print(f"Could not scan r/{subreddit_name}. Error: {e}")
log.error(f"Could not scan r/{subreddit_name}. Error: {e}")
conn.close()
print("\n--- Scan Complete ---")
log.info("\n--- Scan Complete ---")
def main():
@@ -147,19 +148,18 @@ def main():
parser.add_argument("-l", "--limit", type=int, default=20, help="Number of tickers to show in the CLI report.\n(Default: 20)")
args = parser.parse_args()
# --- THIS IS THE CORRECTED LOGIC BLOCK ---
if args.subreddit:
# If --subreddit is used, create a list with just that one.
subreddits_to_scan = [args.subreddit]
print(f"Targeted Scan Mode: Focusing on r/{args.subreddit}")
log.info(f"Targeted Scan Mode: Focusing on r/{args.subreddit}")
else:
# Otherwise, load from the config file.
print(f"Config Scan Mode: Loading subreddits from {args.config}")
log.info(f"Config Scan Mode: Loading subreddits from {args.config}")
# Use the correct argument name: args.config
subreddits_to_scan = load_subreddits(args.config)
if not subreddits_to_scan:
print("Error: No subreddits to scan. Please check your config file or --subreddit argument.")
log.error("Error: No subreddits to scan. Please check your config file or --subreddit argument.")
return
# --- Initialize and Run ---