AIFBA Prac7
AIFBA Prac7
Experiment No. 07
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.
Code:
# Install required packages
!pip install backtrader yfinance
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()
Output:
R1 R2 R3
DOP DOS Conduction File Record Viva -Voce Total Signature
5 Marks 5 Marks 5 Marks 15 Marks