Reputation: 11
Very much a noob question. I'm trying to code with copilot and some (many) things in the code need fixing. However I can't progress past this error. I've installed and imported praw, I've defined the variable following the praw documentation format, but python is still telling me I haven't defined it? I'm running the python extenstion in VScode in a conda environment (I think that's what I set up). Also yes, I did create an app in reddit so I'd get the IDs
import praw
import datetime
import pandas as pd
from collections import Counter
import os
import logging
import re
import alpaca_trade_api as tradeapi
# Configure logging
logging.basicConfig(filename='stock_report.log', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
# Initialize Reddit API credentials
reddit = praw.Reddit(
client_id="redacted",
client_secret="redacted",
password="redacted",
user_agent="redacted",
username="redacted",
)
print(reddit.read_only) #test
# Subreddits to search
subreddits = ["stocks", "wallstreetbets", "wallstreetbetsELITE", "valueinvesting", "pennystocks"]
# Timeframe for analysis (e.g., last 24 hours)
time_delta = datetime.timedelta(days=300)
end_time = datetime.datetime.now(datetime.timezone.utc)
start_time = end_time - time_delta
logging.info(f"Analyzing posts from {start_time} to {end_time}")
# Get all available stock symbols from Alpaca
try:
api = tradeapi.REST('redacted', base_url='https://paper-api.alpaca.markets')
assets = api.list_assets(status='active')
stock_symbols = [asset.symbol for asset in assets if asset.exchange == 'NASDAQ' or asset.exchange == 'NYSE']
logging.info(f"Loaded {len(stock_symbols)} stock symbols from Alpaca.")
except Exception as e:
logging.error(f"Error loading stock symbols from Alpaca: {e}")
raise
all_mentions = []
for subreddit_name in subreddits:
try:
subreddit = reddit.subreddit(subreddit_name)
logging.info(f"Processing subreddit: {subreddit_name}")
submission_count = 0
for submission in subreddit.new(limit=500):
submission_time = datetime.datetime.fromtimestamp(submission.created_utc, datetime.timezone.utc)
if start_time <= submission_time <= end_time:
submission_count += 1
text_to_search = (submission.selftext or "") + " " + submission.title
logging.info(f"Searching text: {text_to_search}")
for symbol in stock_symbols:
if re.search(r'\b' + re.escape(symbol) + r'\b', text_to_search, re.IGNORECASE): # Word boundary regex
all_mentions.append(symbol)
submission.comments.replace_more(limit=0)
for comment in submission.comments.list():
if hasattr(comment, 'body'):
if re.search(r'\b' + re.escape(symbol) + r'\b', comment.body, re.IGNORECASE): # Word boundary regex
all_mentions.append(symbol)
logging.info(f"Retrieved {submission_count} submissions from {subreddit_name} within the time range.")
except praw.exceptions.APIException as e:
logging.error(f"PRAW API Error in {subreddit_name}: {e}")
except Exception as e:
logging.error(f"Error processing subreddit {subreddit_name}: {e}")
# Count mentions
mention_counts = Counter(all_mentions)
print(all_mentions)
# Create a Pandas DataFrame for the report
report_data = {'Stock Symbol': list(mention_counts.keys()),
'Mentions': list(mention_counts.values())}
df_report = pd.DataFrame(report_data)
if not df_report.empty:
df_report = df_report.sort_values(by='Mentions', ascending=False)
print(df_report)
df_report.to_csv("stock_report.csv", index=False)
logging.info("Report saved to stock_report.csv")
print("Report saved to stock_report.csv")
else:
print("No stock mentions found in the specified time range.")
logging.info("No stock mentions found in the specified time range.")
For this specific problem, I'm just expecting to be authenticated into reddit. I'll then use this to pull certain information from other subreddits. The reddit variable should be clearly defined above, but python doesn't recognize it.
Here is the error message:
Traceback (most recent call last):
File "c:\Users\fdossantos\Code\Untitled-2.py", line 26, in <module>
print(reddit.read_only)
^^^^^^
NameError: name 'reddit' is not defined
Upvotes: 1
Views: 91
Reputation: 1
Try initializing the variable first by using:
reddit = None
it could also be an issue with the library you are using causing the variable to not be initialized correctly, so also try renaming the variable to apistuff
or something like that.
(Also, you just leaked api keys, remove that ASAP.)
Upvotes: 0