PySheets / pysheets

Source for PySheets
Other
41 stars 5 forks source link

Tutorial: Building a Simple Algorithmic Trading Strategy #86

Open kimo opened 2 days ago

kimo commented 2 days ago

Hi @laffra,

Is this a good use-case to showcase the basic usability of pysheets ?

Example: Building a Simple Algorithmic Trading Strategy

Let’s walk through an example of a simple trading strategy using Python and its popular libraries.

  1. Libraries Used

    • Pandas: For data manipulation and analysis. • NumPy: For mathematical operations. • yfinance: For retrieving stock market data. • TA-Lib: For technical analysis indicators (optional).

  2. Moving Average Crossover Strategy

One of the most basic strategies in algorithmic trading is the moving average crossover strategy. It uses two moving averages (SMA—simple moving average):

•   Short-term average (e.g., 50 days): Indicates short-term price trends.
•   Long-term average (e.g., 200 days): Indicates long-term price trends.

The strategy:

•   Buy signal: When the short-term average crosses above the long-term average.
•   Sell signal: When the short-term average crosses below the long-term average.
  1. Example Code

Here’s how you could implement this in Python using pandas and yfinance:

import yfinance as yf import pandas as pd import numpy as np

Fetch historical stock data (e.g., Apple) from Yahoo Finance

stock_data = yf.download('AAPL', start='2020-01-01', end='2023-01-01')

Calculate short-term (50 days) and long-term (200 days) simple moving averages

stock_data['SMA_50'] = stock_data['Close'].rolling(window=50).mean() stock_data['SMA_200'] = stock_data['Close'].rolling(window=200).mean()

Define the trading signals (buy/sell)

stock_data['Signal'] = 0 # 0 means hold stock_data['Signal'][50:] = np.where(stock_data['SMA_50'][50:] > stock_data['SMA_200'][50:], 1, -1)

Generate positions based on the signal

stock_data['Position'] = stock_data['Signal'].diff()

Output the DataFrame with the signals

print(stock_data[['Close', 'SMA_50', 'SMA_200', 'Signal', 'Position']].tail())

To visualize:

import matplotlib.pyplot as plt

plt.figure(figsize=(10, 5)) plt.plot(stock_data['Close'], label='AAPL Price', color='blue') plt.plot(stock_data['SMA_50'], label='50-Day SMA', color='red') plt.plot(stock_data['SMA_200'], label='200-Day SMA', color='green') plt.title('Apple Price with SMA Crossover Strategy') plt.legend() plt.show()

Explanation:

•   Download stock data: We fetch Apple’s historical stock data using yfinance.
•   Calculate moving averages: We calculate the 50-day and 200-day moving averages.
•   Generate buy/sell signals: A “1” signal is generated when the short-term moving average is above the long-term moving average (buy signal), and a “-1” signal when it’s below (sell signal).
•   Visualize: We plot the stock’s closing price along with the moving averages to see where the crossovers happen.
laffra commented 21 hours ago

This is a great example. I am busy with an all-day workshop on Monday. I will definitely look into this later this week.