0% found this document useful (0 votes)
17 views

AIFBA_P5-M

The document outlines an experiment focused on developing and backtesting a simple trading algorithm using the Moving Average Crossover Strategy. It explains key concepts such as moving averages, buy/sell signals, and the backtesting process, along with steps for implementing the algorithm using historical market data. The experiment includes code for data collection, signal generation, and performance evaluation, comparing the trading strategy against a buy-and-hold approach.

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)
17 views

AIFBA_P5-M

The document outlines an experiment focused on developing and backtesting a simple trading algorithm using the Moving Average Crossover Strategy. It explains key concepts such as moving averages, buy/sell signals, and the backtesting process, along with steps for implementing the algorithm using historical market data. The experiment includes code for data collection, signal generation, and performance evaluation, comparing the trading strategy against a buy-and-hold approach.

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. 05

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.
o 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.
o 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:
o 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.
o 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:
o Cumulative Returns: This is the total return on the investment over a specific
period.
o 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.
o 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]
# Import required libraries
!pip install yfinance
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# Download historical data


ticker = "AAPL" # Example ticker (Apple Inc.)
start_date = "2010-01-01"
end_date = "2023-12-31"
data = yf.download(ticker, start=start_date, end=end_date)

# Calculate moving averages


data['SMA50'] = data['Close'].rolling(window=50).mean()
data['SMA200'] = data['Close'].rolling(window=200).mean()

# Generate signals
data['Signal'] = 0
data['Signal'][50:] = np.where(data['SMA50'][50:] > data['SMA200'][50:], 1, 0)
data['Position'] = data['Signal'].diff()

# Backtest parameters
initial_balance = 10000
portfolio = pd.DataFrame(index=data.index)
portfolio['Price'] = data['Close']
portfolio['SMA50'] = data['SMA50']
portfolio['SMA200'] = data['SMA200']
portfolio['Position'] = data['Position']

# Initialize portfolio values


portfolio['Shares'] = 0
portfolio['Cash'] = initial_balance
portfolio['Total'] = initial_balance

# Simulate trading
for i in range(1, len(portfolio)):
if portfolio['Position'][i] == 1: # Buy signal
shares_to_buy = portfolio['Cash'][i-1] // portfolio['Price'][i]
portfolio.loc[portfolio.index[i], 'Shares'] = portfolio['Shares'][i-1] +
shares_to_buy
portfolio.loc[portfolio.index[i], 'Cash'] = portfolio['Cash'][i-1] -
(shares_to_buy * portfolio['Price'][i])
elif portfolio['Position'][i] == -1: # Sell signal
portfolio.loc[portfolio.index[i], 'Cash'] = portfolio['Cash'][i-1] +
(portfolio['Shares'][i-1] * portfolio['Price'][i])
portfolio.loc[portfolio.index[i], 'Shares'] = 0
else: # Hold position
portfolio['Shares'][i] = portfolio['Shares'][i-1]
portfolio['Cash'][i] = portfolio['Cash'][i-1]

portfolio['Total'][i] = portfolio['Cash'][i] + (portfolio['Shares'][i] *


portfolio['Price'][i])

# Buy and hold comparison


portfolio['Buy_Hold'] = (initial_balance // portfolio['Price'][0]) *
portfolio['Price']

# Plot results
plt.figure(figsize=(16, 10))

# Price and moving averages plot


plt.subplot(2, 1, 1)
plt.plot(portfolio['Price'], label='Price')
plt.plot(portfolio['SMA50'], label='50-day SMA')
plt.plot(portfolio['SMA200'], label='200-day SMA')
plt.title(f'{ticker} Price and Moving Averages')
plt.ylabel('Price ($)')
plt.legend()

# Buy/Sell signals
buy_signals = portfolio[portfolio['Position'] == 1]
sell_signals = portfolio[portfolio['Position'] == -1]
plt.scatter(buy_signals.index, buy_signals['Price'], marker='^', color='g',
label='Buy', zorder=5)
plt.scatter(sell_signals.index, sell_signals['Price'], marker='v', color='r',
label='Sell', zorder=5)

# Equity curve plot


plt.subplot(2, 1, 2)
plt.plot(portfolio['Total'], label='Strategy Value')
plt.plot(portfolio['Buy_Hold'], label='Buy & Hold Value')
plt.title('Portfolio Value Comparison')
plt.ylabel('Value ($)')
plt.legend()

plt.tight_layout()
plt.show()

# Performance metrics
strategy_return = (portfolio['Total'][-1] / initial_balance - 1) * 100
buy_hold_return = (portfolio['Buy_Hold'][-1] / initial_balance - 1) * 100
print(f"\nStrategy Return: {strategy_return:.2f}%")
print(f"Buy & Hold Return: {buy_hold_return:.2f}%")

Output :

R1 R2 R3
DOP DOS Conduction File Record Viva - Total Signatu
Voce re
5 Marks 5 Marks 5 Marks 15
Marks

You might also like