0% found this document useful (0 votes)
30 views5 pages

AIFBA Prac7

The document outlines an experiment focused on developing and backtesting a simple trading algorithm using a Moving Average Crossover Strategy. It explains key concepts such as moving averages, buy/sell signals, and backtesting, along with step-by-step instructions for implementing the algorithm using Python libraries. The experiment aims to evaluate the algorithm's performance against a buy-and-hold strategy using historical market data.

Uploaded by

mgade3012
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views5 pages

AIFBA Prac7

The document outlines an experiment focused on developing and backtesting a simple trading algorithm using a Moving Average Crossover Strategy. It explains key concepts such as moving averages, buy/sell signals, and backtesting, along with step-by-step instructions for implementing the algorithm using Python libraries. The experiment aims to evaluate the algorithm's performance against a buy-and-hold strategy using historical market data.

Uploaded by

mgade3012
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

DEPARTMENT OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE

Subject: AI for Financial & Banking Course Code: CSDL 8011


application
Semester: 8 Course: AI&DS
Laboratory no.:101 Name of subject teacher: Dr. Seema Ladhe
Name of student:Meghana Gade Roll no: VU2S2223002

Experiment No. 07

Title: Developing and Backtesting a Simple trading Algorithm.

Objectives: Study and develop Backtesting a Simple trading Algorithm.

Theory:
A trading algorithm is a programmatic set of rules designed to make trading decisions
automatically. These algorithms use market data and specific criteria to enter and exit trades
without human intervention. Trading algorithms can be quite simple or highly complex,
depending on the strategy and the type of analysis used.
One common and simple trading strategy is the Moving Average Crossover Strategy. This
strategy involves two types of moving averages:
● Short-Term Moving Average (SMA): Typically calculated over a short period, such
as 50 days, it reacts more quickly to price changes.
● Long-Term Moving Average (SMA): This is calculated over a longer period, such as
200 days, and responds more slowly to price changes.

The idea behind the moving average crossover strategy is that when the short-term moving
average crosses above the long-term moving average, it signals a potential buy opportunity,
and when it crosses below, it signals a potential sell opportunity.
This simple approach is widely used by traders because it captures the general market trends.
It works on the assumption that when a short-term price trend shifts above a long-term price
trend, it may indicate a new upward trend (bullish), and vice versa for a downward trend
(bearish).

Key Concepts:
1. Moving Averages: A moving average is the average of a specific set of data points
over a period of time. It helps smooth out price data to create a trend-following
indicator. There are several types of moving averages, but the simple moving average
(SMA) is the most commonly used in trading. It is calculated by adding the closing
prices of the stock over a period and dividing by the number of periods.
○ Short-Term Moving Average (SMA50): A moving average calculated over a
shorter time frame (e.g., 50 days). It is more sensitive to recent price
movements and helps identify short-term trends.
○ Long-Term Moving Average (SMA200): A moving average calculated over a
longer time frame (e.g., 200 days). It reacts more slowly to price movements
and provides insights into long-term trends.
2. Buy and Sell Signals:
○ Buy Signal: When the short-term moving average (e.g., SMA50) crosses
above the long-term moving average (e.g., SMA200), it generates a bullish
signal, indicating a potential buy.
○ Sell Signal: When the short-term moving average (SMA50) crosses below the
long-term moving average (SMA200), it generates a bearish signal, indicating
a potential sell.
3. Backtesting: Backtesting refers to the process of testing a trading strategy using
historical market data. It simulates how the algorithm would have performed in the
past, using actual historical prices to check if the strategy would have been profitable.
Backtesting helps identify the effectiveness of a strategy and its risk-adjusted returns.

In our case, we are simulating buying and selling based on the crossover of the moving
averages. We track the portfolio value over time by updating the balance as trades are
executed.
4. Performance Metrics:
○ Cumulative Returns: This is the total return on the investment over a specific
period.
○ Portfolio Value: This is the value of the portfolio at any point in time, which
includes both the cash balance and the value of the shares owned.
○ Buy and Hold Strategy Comparison: To evaluate the effectiveness of the
strategy, it is compared to a simple buy-and-hold approach, where we buy the
stock at the start and hold it until the end of the testing period.

Steps in the Trading Algorithm:


1. Data Collection: The first step is to gather historical market data. In our case, we fetch
data from Yahoo Finance using the yfinance library, which provides historical stock
prices including Open, High, Low, Close, Adj Close, and Volume.
2. Calculating Moving Averages: Next, we compute the short-term (50 days) and long-
term (200 days) simple moving averages using the rolling method in pandas. These
averages represent the market trends over short and long periods.
3. Generating Buy and Sell Signals: The buy and sell signals are generated based on the
crossover of the two moving averages. A buy signal is triggered when the short-term
SMA crosses above the long-term SMA, and a sell signal is triggered when the short-
term SMA crosses below the long-term SMA.
4. Backtesting the Strategy: After generating buy and sell signals, we simulate the
trading process. Starting with an initial balance (e.g., $10,000), we track how many
shares we can buy and sell at each signal. The portfolio value is updated after each
buy or sell order.
5. Evaluating the Strategy: Finally, we evaluate the strategy by comparing the
performance of our moving average crossover strategy with a simple buy-and-hold
strategy. The equity curve (a plot of the portfolio value over time) is used to visualize
the performance.

Code:
# Install required packages
!pip install backtrader yfinance

# Enable inline plotting for Matplotlib


%matplotlib inline

# Import necessary libraries


import backtrader as bt
import yfinance as yf
import pandas as pd
import datetime
import matplotlib.pyplot as plt
from IPython.display import display

# Define the trading strategy


class MovingAverageCrossover(bt.Strategy):
params = (("short_period", 50), ("long_period", 200))

def __init__(self):
self.sma_short = bt.indicators.SimpleMovingAverage(period=self.params.short_period)
self.sma_long = bt.indicators.SimpleMovingAverage(period=self.params.long_period)

def next(self):
if self.sma_short[0] > self.sma_long[0] and not self.position:
self.buy()
elif self.sma_short[0] < self.sma_long[0] and self.position:
self.sell()

# Initialize Backtrader engine


cerebro = bt.Cerebro()
cerebro.addstrategy(MovingAverageCrossover)

# Define symbol and date range


symbol = "AAPL"
start_date = datetime.datetime(2020, 1, 1)
end_date = datetime.datetime(2024, 1, 1)

# Download raw (unadjusted) data from Yahoo Finance


data = yf.download(symbol, start=start_date, end=end_date, auto_adjust=False)

# Flatten MultiIndex if necessary


if isinstance(data.columns, pd.MultiIndex):
data.columns = data.columns.get_level_values(0)

# Select required columns and ensure datetime index


data = data[["Open", "High", "Low", "Close", "Volume"]]
data.index = pd.to_datetime(data.index)

# Convert DataFrame to Backtrader-compatible feed


bt_data = bt.feeds.PandasData(dataname=data)
cerebro.adddata(bt_data)

# Run the backtest


cerebro.run()

# Plot the results and explicitly display them


figs = cerebro.plot(style='candlestick')
for fig_group in figs:
for fig in fig_group:
display(fig)
plt.show()

Output:
R1 R2 R3
DOP DOS Conduction File Record Viva -Voce Total Signature
5 Marks 5 Marks 5 Marks 15 Marks

You might also like