Sign inGet started
← Back to all guides

Introduction to stock trading in Python

By Filip Žitný

Updated on March 6, 2024

Stock trading involves buying and selling shares of companies in the stock market. With the advent of technology, programming languages like Python have become powerful tools for financial analysis and trading. This guide will introduce you to stock trading using Python in Deepnote, a collaborative, AI-powered data platform.

Fetching stock data

We'll use the yfinance library to fetch stock data.

import yfinance as yf

# Define the stock symbol and the date range
stock_symbol = 'AAPL'  # Apple Inc.
start_date = '2022-01-01'
end_date = '2023-01-01'

# Fetch the stock data
stock_data = yf.download(stock_symbol, start=start_date, end=end_date)

# Display the first few rows of the data
stock_data.head()

Analyzing stock data

Basic data exploration:
You can explore the fetched data to understand its structure and basic statistics.

# Display the basic statistics of the data
stock_data.describe()

# Check for missing values
stock_data.isnull().sum()

Data visualization:
Visualize the stock's closing price over time to get an overview of its performance.

import matplotlib.pyplot as plt

# Plot the closing price
plt.figure(figsize=(10, 5))
plt.plot(stock_data['Close'], label='Close Price')
plt.title(f'{stock_symbol} Closing Price')
plt.xlabel('Date')
plt.ylabel('Price (USD)')
plt.legend()
plt.grid()
plt.show()

Moving averages:
Calculate and plot moving averages to analyze trends.

# Calculate moving averages
stock_data['MA20'] = stock_data['Close'].rolling(window=20).mean()
stock_data['MA50'] = stock_data['Close'].rolling(window=50).mean()

# Plot closing price and moving averages
plt.figure(figsize=(10, 5))
plt.plot(stock_data['Close'], label='Close Price')
plt.plot(stock_data['MA20'], label='20-Day MA')
plt.plot(stock_data['MA50'], label='50-Day MA')
plt.title(f'{stock_symbol} Closing Price and Moving Averages')
plt.xlabel('Date')
plt.ylabel('Price (USD)')
plt.legend()
plt.grid()
plt.show()

Simple trading strategy

A simple trading strategy can be implemented based on moving averages. For example, a "Golden Cross" occurs when the short-term moving average crosses above the long-term moving average, indicating a buy signal. Conversely, a "Death Cross" indicates a sell signal.

# Define the strategy
def trading_strategy(data):
    data['Signal'] = 0
    data['Signal'][20:] = np.where(data['MA20'][20:] > data['MA50'][20:], 1, 0)
    data['Position'] = data['Signal'].diff()

trading_strategy(stock_data)

# Plot the buy and sell signals
plt.figure(figsize=(10, 5))
plt.plot(stock_data['Close'], label='Close Price', alpha=0.5)
plt.plot(stock_data['MA20'], label='20-Day MA', alpha=0.75)
plt.plot(stock_data['MA50'], label='50-Day MA', alpha=0.75)
plt.plot(stock_data[stock_data['Position'] == 1].index,
         stock_data['MA20'][stock_data['Position'] == 1],
         '^', markersize=10, color='g', label='Buy Signal')
plt.plot(stock_data[stock_data['Position'] == -1].index,
         stock_data['MA20'][stock_data['Position'] == -1],
         'v', markersize=10, color='r', label='Sell Signal')
plt.title(f'{stock_symbol} Trading Strategy')
plt.xlabel('Date')
plt.ylabel('Price (USD)')
plt.legend()
plt.grid()
plt.show()

Conclusion

In this guide, we've introduced basic stock trading analysis using Python in Deepnote. We fetched stock data, performed basic data exploration, visualized trends, and implemented a simple trading strategy based on moving averages.

Next steps

  1. Backtesting: Implement and backtest more sophisticated trading strategies.
  2. Real-time data: Use real-time data for live trading simulations.
  3. Risk management: Incorporate risk management techniques to minimize losses.

This guide provides a starting point for exploring stock trading analysis in Python. Deepnote's collaborative features make it an excellent platform for teams to work together on financial data projects. Happy trading!

Filip Žitný

Data Scientist

Follow Filip on Twitter, LinkedIn and GitHub

That’s it, time to try Deepnote

Get started – it’s free
Book a demo

Footer

Solutions

  • Notebook
  • Data apps
  • Machine learning
  • Data teams

Product

Company

Comparisons

Resources

  • Privacy
  • Terms

© Deepnote