Monitor Stock Prices with Python to Seize Investment Opportunities

Have you ever felt frustrated for missing out on a stock surge? Or do you find yourself glued to your stock app, afraid of missing any buying or selling points? Don’t worry, we can let Python help us keep an eye on stocks, saving time and effort!

Get Real-Time Stock Data

We need a reliable data source. I chose the <span>yfinance</span> library, which can fetch real-time stock data from Yahoo Finance. Installation is super easy:

pip install yfinance

Next, let’s fetch real-time data for a stock:

import yfinance as yf

# Get Alibaba stock information
stock = yf.Ticker("BABA")
current_price = stock.info['regularMarketPrice']
print(f"Alibaba's current stock price: ${current_price}")

Running this code will show you Alibaba’s real-time stock price. Isn’t it much more convenient than manually refreshing the app?

Tip:<span>yfinance</span> uses US stock codes. If you want to check A-shares, you might need other libraries or make adjustments in the code.

Set Price Alerts

Just watching the price isn’t enough; we also need to set up a notification mechanism. For example, when the stock price reaches a target price, we should be notified immediately:

import time

target_price = 100  # Set target price
check_interval = 60  # Check every 60 seconds

while True:
    current_price = yf.Ticker("BABA").info['regularMarketPrice']
    if current_price >= target_price:
        print(f"Opportunity alert! Alibaba's stock price has reached ${current_price}")
        break
    time.sleep(check_interval)

This code checks the stock price every minute, and if it reaches or exceeds $100, it will notify you immediately. You can adjust the check interval and target price as needed.

Send Email Notifications

Staring at the computer screen all the time isn’t a solution. Let’s take it a step further and set up email alerts:

import smtplib
from email.mime.text import MIMEText

def send_email(subject, body):
    sender = "[email protected]"
    receiver = "[email protected]"
    password = "your_password"  # It's recommended to use an app-specific password

    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = receiver

    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
        server.login(sender, password)
        server.send_message(msg)

# Add to the previous loop:
if current_price >= target_price:
    send_email("Stock Alert", f"Alibaba's stock price has reached ${current_price}")
    break

With this, when the stock price reaches the target, you’ll receive an alert email. No more worries about missing investment opportunities!

Tip: Remember to replace the email and password in the code. For account security, it’s best to use an app-specific password rather than your login password.

Analyze Historical Data

Besides monitoring prices, we can also use Python to analyze historical data, which helps us make more informed investment decisions:

import pandas as pd
import matplotlib.pyplot as plt

# Get historical data for the past year
hist = stock.history(period="1y")

# Calculate 20-day and 50-day moving averages
hist['MA20'] = hist['Close'].rolling(window=20).mean()
hist['MA50'] = hist['Close'].rolling(window=50).mean()

# Plot the chart
plt.figure(figsize=(12, 6))
plt.plot(hist.index, hist['Close'], label='Close Price')
plt.plot(hist.index, hist['MA20'], label='20-Day MA')
plt.plot(hist.index, hist['MA50'], label='50-Day MA')
plt.legend()
plt.title('Alibaba Stock Price Trend')
plt.show()

This code generates a chart that includes the closing price, 20-day moving average, and 50-day moving average. Through this chart, you can visually see the stock price trend and determine if it’s a good time to buy.

As I write this, I suddenly feel like a stock market guru (laughs). But don’t forget, investing should be rational; these tools are just aids, and the final decision still relies on your judgment.

Honestly, using Python to monitor stocks is really convenient. You can continue to expand this little tool based on your needs. Maybe one day, you’ll achieve financial freedom with it? Who knows, dreams should be there, just in case they come true!

Leave a Comment