Build a Python Stock Monitoring Bot: Real-Time Prices, Email Alerts & Auto-Run
This article guides you through creating a Python script that fetches real‑time stock quotes, evaluates price changes, and automatically sends email notifications, while covering required libraries, scheduling, packaging as an executable, and future enhancements for quantitative trading.
Introduction
Python's high development efficiency makes it a powerful tool for data analysis in the big‑data era. The article argues that in quantitative investment the core decision logic still relies on human intelligence, so 80% of effort should focus on model construction and 20% on coding.
Idea
By writing a Python program that monitors real‑time stock prices and sends email or SMS notifications when a predefined price‑change threshold is reached, investors can avoid constantly watching the market.
Readers will learn how to obtain real‑time quotes, send emails, schedule the script, and package it as an executable.
Workflow Diagram and Screenshots
Overall program flow is illustrated below.
Example of price‑monitoring result for stock 600905 (三峡能源).
Code Implementation
Required third‑party libraries
Tushare : free Python financial data interface for real‑time quotes.
pandas : data manipulation of the DataFrame returned by Tushare.
schedule : schedule the script during trading hours.
smtplib : send email notifications.
sys : exit the program after market close.
pyinstaller : package the script into an .exe file.
Install them via pip install tushare pandas schedule pyinstaller.
Key functions
def get_now_jiage(code):
df = ts.get_realtime_quotes(code)[['name','price','pre_close','date','time']]
return df def pd_ztjytime():
# Determine whether the current time is within the lunch break (11:30‑13:00)
now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
now_datetime = datetime.datetime.strptime(now_time, '%Y-%m-%d %H:%M:%S')
d1 = datetime.datetime.strptime(datetime.datetime.now().strftime('%Y-%m-%d') + ' 11:30:01', '%Y-%m-%d %H:%M:%S')
d2 = datetime.datetime.strptime(datetime.datetime.now().strftime('%Y-%m-%d') + ' 13:00:00', '%Y-%m-%d %H:%M:%S')
delta1 = (now_datetime - d1).total_seconds()
delta2 = (d2 - now_datetime).total_seconds()
if delta1 > 0 and delta2 > 0:
return True # within pause period
else:
return False def do_programe(code):
if pd_ztjytime() == False:
info = get_now_jiage(code)
now_price = float(info['price'][0])
name = info['name'][0]
pre_close = float(info['pre_close'][0])
date = info['date'][0]
time_ = info['time'][0]
now_change = round((now_price - pre_close) / pre_close * 100, 2)
# ... calculate total change, market value, profit/loss ...
if (abs(now_change) >= 3 and abs(now_change) < 3.1) or \
(abs(now_change) >= 6 and abs(now_change) < 6.1) or \
(abs(now_change) >= 9 and abs(now_change) < 9.1):
# build HTML email content and send
email_comment = []
email_comment.append('<html>')
email_comment.append(f'<p>Stock {name} ({code}) price change detected.</p>')
# ... table construction omitted for brevity ...
email_comment.append('</html>')
send_msg = '
'.join(email_comment)
send_Email(email_add[0], send_msg) def send_Email(Email_address, email_text):
from_addr = '*****'
password = '*****'
title = 'Stock Price Alert - ' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
msg = MIMEText(email_text, 'html', 'utf-8')
msg['From'] = from_addr
msg['To'] = Email_address
msg['Subject'] = title
try:
server = smtplib.SMTP_SSL('smtp.qq.com', 465)
server.login(from_addr, password)
server.send_message(msg)
server.quit()
except Exception as e:
passHow to obtain email authorization code (QQ example)
1. Log in to QQ Mail and open the Settings → Account page.
2. Scroll to the “POP3/SMTP Service” section and click “Enable”.
3. Follow the verification steps; the authorization code will be displayed and can be copied.
Running the script
def run():
while True:
do_programe('600905')
now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
market_close = datetime.datetime.strptime(datetime.datetime.now().strftime('%Y-%m-%d') + ' 15:00:00', '%Y-%m-%d %H:%M:%S')
if (datetime.datetime.strptime(now_time, '%Y-%m-%d %H:%M:%S') - market_close).total_seconds() <= 0:
sys.exit()
time.sleep(1) if __name__ == '__main__':
schedule.every().day.at("09:30").do(run)
while True:
schedule.run_pending()
time.sleep(1)Packaging and auto‑run
Use pyinstaller -w -F script.py to generate a background executable. Copy the .exe file to the Windows Startup folder for automatic launch after system boot. The process can be verified in Task Manager under the name you assigned.
Outlook
The current example monitors a single stock; future improvements include monitoring a stock pool with technical indicators (e.g., MACD, K‑line, KDJ), integrating a database for flexible stock management, adding SMS alerts via services like Twilio, switching to Tushare Pro or other data providers, and deploying the bot on a cloud server for continuous operation.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
