This commit is contained in:
2025-07-21 23:44:27 +02:00
parent 728fe43571
commit d330f31950
3 changed files with 190 additions and 96 deletions

View File

@@ -43,6 +43,11 @@ def get_reddit_instance():
return praw.Reddit(client_id=client_id, client_secret=client_secret, user_agent=user_agent)
def scan_subreddits(reddit, subreddits_list, post_limit=100, comment_limit=100, days_to_scan=1):
"""
Scans subreddits with a hybrid mention counting logic.
- If a ticker is in the title, it gets credit for all comments.
- If not, tickers only get credit for direct mentions in comments.
"""
conn = database.get_db_connection()
post_age_limit = days_to_scan * 86400
current_time = time.time()
@@ -56,53 +61,77 @@ def scan_subreddits(reddit, subreddits_list, post_limit=100, comment_limit=100,
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. Moving to next subreddit.")
print(f" -> Reached posts older than the {days_to_scan}-day limit.")
break
post_text = submission.title + " " + submission.selftext
tickers_in_post = extract_tickers(post_text)
if tickers_in_post:
post_sentiment = get_sentiment_score(submission.title)
for ticker_symbol in set(tickers_in_post):
ticker_id = database.get_or_create_entity(conn, 'tickers', 'symbol', ticker_symbol)
database.add_mention(conn, ticker_id, subreddit_id, submission.id, 'post', int(submission.created_utc), post_sentiment)
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}...")
financials = get_financial_data(ticker_symbol)
database.update_ticker_financials(
conn, ticker_id,
financials['market_cap'] or ticker_info['market_cap'],
financials['closing_price'] or ticker_info['closing_price']
)
# --- 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
submission.comments.replace_more(limit=0)
all_comment_sentiments = []
for comment in submission.comments.list()[:comment_limit]:
all_comment_sentiments.append(get_sentiment_score(comment.body))
tickers_in_comment = extract_tickers(comment.body)
if tickers_in_comment:
all_comments = submission.comments.list()[:comment_limit]
# --- CASE A: Tickers were found in the title ---
if tickers_in_title:
print(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
for ticker_symbol in tickers_in_title:
ticker_id = database.get_or_create_entity(conn, 'tickers', 'symbol', ticker_symbol)
database.add_mention(conn, ticker_id, subreddit_id, submission.id, 'post', int(submission.created_utc), post_sentiment)
# Add one 'comment' mention for EACH comment FOR EACH title ticker
for comment in all_comments:
comment_sentiment = get_sentiment_score(comment.body)
for ticker_symbol in set(tickers_in_comment):
for ticker_symbol in tickers_in_title:
ticker_id = database.get_or_create_entity(conn, 'tickers', 'symbol', ticker_symbol)
database.add_mention(conn, ticker_id, subreddit_id, submission.id, 'comment', int(comment.created_utc), comment_sentiment)
# --- CASE B: No tickers in the title, scan comments individually ---
else:
for comment in all_comments:
tickers_in_comment = set(extract_tickers(comment.body))
if tickers_in_comment:
all_tickers_found_in_post.update(tickers_in_comment) # Add to our set for financials
comment_sentiment = get_sentiment_score(comment.body)
for ticker_symbol in tickers_in_comment:
ticker_id = database.get_or_create_entity(conn, 'tickers', 'symbol', ticker_symbol)
database.add_mention(conn, ticker_id, subreddit_id, submission.id, 'comment', int(comment.created_utc), comment_sentiment)
# --- EFFICIENT FINANCIALS UPDATE ---
# Now, update market cap once for every unique ticker found in the whole post
for ticker_symbol in all_tickers_found_in_post:
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}...")
financials = get_financial_data(ticker_symbol)
database.update_ticker_financials(
conn, ticker_id,
financials['market_cap'] or ticker_info['market_cap'],
financials['closing_price'] or ticker_info['closing_price']
)
# --- DEEP DIVE SAVE (Still valuable) ---
all_comment_sentiments = [get_sentiment_score(c.body) for c in all_comments]
avg_sentiment = sum(all_comment_sentiments) / len(all_comment_sentiments) if all_comment_sentiments else 0
post_analysis_data = {
"post_id": submission.id, "title": submission.title,
"post_url": f"https://reddit.com{submission.permalink}",
"subreddit_id": subreddit_id, "post_timestamp": int(submission.created_utc),
"comment_count": len(all_comment_sentiments), "avg_comment_sentiment": avg_sentiment
"post_url": f"https://reddit.com{submission.permalink}", "subreddit_id": subreddit_id,
"post_timestamp": int(submission.created_utc), "comment_count": len(all_comments),
"avg_comment_sentiment": avg_sentiment
}
database.add_or_update_post_analysis(conn, post_analysis_data)
except Exception as e:
print(f"Could not scan r/{subreddit_name}. Error: {e}")
conn.close()
print("\n--- Scan Complete ---")
def main():
"""Main function to run the Reddit stock analysis tool."""
parser = argparse.ArgumentParser(description="Analyze stock ticker mentions on Reddit.", formatter_class=argparse.RawTextHelpFormatter)