AIFBA_P5-M
AIFBA_P5-M
SCIENCE
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
# 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']
# 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]
# Plot results
plt.figure(figsize=(16, 10))
# 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)
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