0% found this document useful (0 votes)
36 views23 pages

Minor project

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)
36 views23 pages

Minor project

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/ 23

Report of

Minor Project (ARP 455)

ON

Stock AI Trader

Under the Supervision of: Submitted By:


Dr. Amit Choudhary Aryan
Tyagi
10119011621

1
TABLE OF CONTENT

S.No. TITLE Page No.

1 Abstract 3

2 Introduction 4-5

3 Hardware Requirement 6

4 Software Requirement 7-8

5 Problem Statement 9

6 Literature Survey

Chapter - 1 What is Algorithmic Trading? 11

Chapter – 2 Strategies for algorithmic 12


trading

Chapter – 3 Designing a back testing 13


engine

7 Major Modules of Project 15 - 16

8 Snapshot 17 - 20

9 References 21

2
ABSTRACT

The rapid advancements in financial technology have led to the rise of


algorithmic trading, a method where trading decisions are made by computer
algorithms rather than manual interventions. The key advantage of this approach
lies in its ability to analyze large volumes of historical and real-time market data
to identify profitable trading opportunities. In this project, we developed a Stock
Backtesting Engine using Streamlit, designed to evaluate and validate different
trading strategies on historical stock data from global markets, including India, the
USA, and Japan.
The main goal of this project is to provide a robust platform for users to test
various trading strategies, such as Bollinger Bands, Moving Averages (SMA),
MACD, RSI, and VWAP, on selected stocks. By simulating trades based on these
strategies, the application helps users understand the potential profitability and
risk associated with each approach. The interactive interface allows users to
configure initial capital, select specific investment styles (Aggressive, Moderate,
Passive), and analyze the performance of the strategy compared to a simple Buy
& Hold (HODL) approach.
This backtesting engine is particularly valuable for both novice traders and
experienced investors who want to experiment with different strategies before
applying them in real markets. By offering features like visualizations of stock
data, performance metrics, and a detailed trade log, the application provides
comprehensive insights into the effectiveness of each strategy. Through this tool,
users can refine their trading techniques, mitigate risks, and make more informed
investment decisions based on quantitative analysis.

3
INTRODUCTION

Algorithmic trading, often known as "algo trading," is a modern approach to


financial markets where traders use computer algorithms to automate the buying
and selling of assets. Unlike traditional trading, which relies heavily on manual
analysis and decision-making, algorithmic trading leverages advanced
mathematical models, data analysis, and automated execution to capitalize on
market opportunities swiftly and efficiently. By programming specific rules and
conditions into these algorithms, traders can make decisions based on real-time
market data, eliminating human errors and emotional biases that typically affect
manual trading.
The growing popularity of algorithmic trading is driven by its ability to process
vast amounts of market data in milliseconds, making it possible to identify trends,
patterns, and anomalies that would be difficult for human traders to detect. The
use of algorithms has also democratized access to sophisticated trading strategies,
enabling both institutional investors and individual traders to harness the power of
automated systems. With features like backtesting—where strategies are tested
against historical data—traders can refine their approaches, minimize risks, and
maximize potential returns before deploying them in live markets.

4
Hardware Requirement

1. High-Speed Internet Connection:


A reliable and fast internet connection is essential for making seamless
API calls and accessing external services such as Google Gemini, SerpApi,
and Sephora API.

2. Server or Cloud Infrastructure:


CPU: Multi-core processor (preferably Intel i7 or AMD Ryzen 7 or above)
for handling multiple API requests and computations.
RAM: Minimum of 16GB, ideally 32GB or higher, to handle large datasets
and run AI models efficiently.

3. Storage:
At least 500GB of SSD storage to store application data, user inputs, and
system logs, with additional storage if managing larger product databases.

4. Local Development Machine (for developers):


A personal computer or laptop with at least 8GB RAM, Intel i5 or Ryzen 5
processor, and 256GB SSD for developing, testing, and deploying code.
An internet connection for accessing APIs and testing interactions with
online resources.

5. Operating System:
Windows 10 /11 would be compatible for this

5
Software Requirement

1. Operating System
 Windows 10 or later, macOS, or Linux distributions (Ubuntu recommended)
2. Programming Language
 Python 3.8 or later: The core programming language used for developing the
backtesting engine and implementing the strategies.
3. Python Libraries
The project relies on various Python libraries for data handling, analysis, and
visualization. These include:
 Streamlit: For building the interactive web application interface.
 Pandas: For data manipulation and analysis of stock data.
 NumPy: For numerical operations and calculations.
 Matplotlib: For visualizing stock data and performance metrics.
 Plotly: For interactive and dynamic data visualizations within the Streamlit
app.
 yfinance: For fetching historical stock data from Yahoo Finance.
 TA-Lib (Technical Analysis Library): For implementing technical indicators
like RSI, MACD, and Bollinger Bands.
4. Development Environment
 Jupyter Notebook (optional): For prototyping and experimenting with data
analysis and strategy implementation.
 Visual Studio Code (VS Code) or PyCharm: For coding and debugging with
features like IntelliSense, linting, and git integration.
5. Data Source and API
 Yahoo Finance API via yfinance library: For real-time and historical stock
data retrieval.
 CSV File Upload: The application also supports custom data uploads in
CSV format for backtesting.
6. Web Framework and User Interface
 Streamlit: A Python-based framework for creating interactive web
applications with minimal effort, used here for building the front end of the
backtesting engine.
7. Version Control System

6
 Git: For version control, collaboration, and tracking changes in the project
codebase.
 GitHub/GitLab/Bitbucket: For code hosting and repository management.
8. Virtual Environment (Recommended)
 venv or conda: For creating isolated Python environments to manage
dependencies without conflicts.
9. Visualization Tools
 Plotly Dash : For enhanced interactive data visualization if additional
features are required in future versions.

7
Problem Statement

In the world of financial markets, investors and traders constantly seek


ways to optimize their trading strategies to maximize returns and
minimize risks. Traditional methods of stock trading often rely on human
intuition and manual analysis, which can be time-consuming, prone to
errors, and inefficient in rapidly changing markets. With the rise of data
availability and computational power, there is a growing need for
systematic approaches that can analyze historical data, backtest various
strategies, and provide data-driven insights.
Need for Customizable and Versatile Analysis:
Existing platforms may not offer the flexibility to tailor the backtesting
according to different investment styles (e.g., aggressive, moderate,
passive) or allow traders to experiment with a variety of technical
indicators like Bollinger Bands, MACD, RSI, etc., on different global
markets.

8
Literature Survey

The retail and e-commerce industries are transforming with the help of
Artificial Intelligence (AI) and Machine Learning (ML), allowing
businesses to better understand customer behavior and adapt to shifting
trends. These technologies make it possible to predict demand, provide
personalized product recommendations, and optimize inventory
management in real-time. AI and ML dive deep into consumer data,
uncovering patterns that traditional methods miss, which helps enhance
the shopping experience and boost sales. However, businesses still face
hurdles such as data quality and integrating these systems effectively. As
these technologies continue to evolve, they are reshaping how companies
forecast trends, manage stock, and engage with customers.

9
Chapter 1: Algorithmic Trading
WHAT IS ALGORITHMIC TRADING?

Introduction

Algorithmic trading is the common term for automated or algo-trading. This is the
process of using a computer programme that executes trades in consonance with
sets of instructions or algorithms. Such an instruction could be built around
multiple parameters like time, price, volume, or even more complex mathematical
models. The basic objective, however, is to generate trades at a speed and
frequency that is well beyond human capability.

Algorithmic trading has revolutionized the landscape of finance since its


inception, making it faster, systematic, and not too emotional. Algorithmic trading
is today a very important activity in both institutional and individual trade,
improving liquidity as well as cutting down on the costs of transactions.

This article, discusses the benefits and drawbacks of algorithmic trading, along
with the technical aspects of trading in detail, along with real-world examples that
explain how algorithmic trading can be applied in a variety of ways.

What is algorithmic trading?

Algorithmic trading, in simple terms, is a process based on the pre-programmed


instructions for conducting trades through a computer. They are programmed to
monitor constantly the markets and execute orders automatically when certain
market conditions are met.

10
For example, a simple algorithm can be set to instruct a system to buy a stock if
the stock's 50-day moving average crosses above its 200-day moving average and
sell when the reverse happens.
Since computers can process market information faster than humans, algorithmic
trading considerably accelerates the speedy and effective execution of trades. This
is especially observed in high-frequency trading, where algorithms carry out a
high volume of trades in less than a second.

Key Advantages

 Speed: Algorithms execute trades in real time and are able to grab
opportunities quicker than a human trader.
Efficiency: Automation prohibits the emotional bias and human mistakes
that are inherent in traditional manual trading.
Backtesting: Algorithms are tested by means of historical data; thus, the
trader is able to test how they would have performed under given previous
market conditions.

Most benefits of algorithmic trading bring with them risks that may or may not be
detrimental to the execution of any trade at hand, such as technical failures or
other market disruptions.

Pros & Cons of Algorithmic Trading

Advantages

 Optimal Execution: Algorithms trade at the best possible prices from which
maximum profit can be achieved.
11
 Instant and Precise Trade Placement: As trade is placed promptly, it does
have less impact on changing prices.
 Low Transaction Costs: The error in human trade placement decreases and it
becomes more effective to trade through algorithms on various markets.

Disadvantages

 Dependence on Technology: Algorithmic trading systems rely much on the


technology and therefore software malfunctions or internet problems might
lead to a missed opportunity or losses.
 Market Impact: High-level automated trades occasionally impact the market,
causing it to be volatile sometimes.
 Regulation: Algorithmic trading is strictly regulated, and thus, any violation
will have penalties to suit.

Chapter 2: Trading Strategies

Common Algorithmic Trading Strategies

Simple Moving Average (SMA)

A Simple Moving Average (SMA) is probably one of the most popular technical
indicators used in trading because it smoothes the price data by calculating an
average price over a certain number of periods. It helps the trader identify trends
and smooth out short-term fluctuations in price.

The formula for computing a Simple Moving Average is:


A 1+ A 2 + A 3 +…+ A n
SMA=
n

Where:
A1, A2 ,…, An are the prices at different intervals and n is the total number of
12
intervals over which the average is calculated.

For example, the 50-day SMA calculates the average price of an asset over the last
50 days. The moving average "smoothes" the fluctuations of the price and allows
the traders to determine whether the asset is in the uptrend or in the downtrend.

Trading SMA Strategy:

Buy: It would be the time when the current price is less than the SMA, that is, that
it is selling below its value, which the algorithm would imply to buy through a
buy order.

Sell: It would give a selling signal at any point in time when the price exceeds the
SMA.

Bollinger Bands Strategy

 Description: Bollinger Bands are a volatility-based indicator consisting of a


moving average and two standard deviation lines plotted above and below it.
 Logic:
o Buy Signal: When the price moves below the lower band, indicating
potential undervaluation.
o Sell Signal: When the price moves above the upper band, indicating
potential overvaluation.
 Purpose: Used to identify periods of high or low volatility and potential
price reversals.
13
Moving Average Convergence Divergence (MACD) Strategy

 Description: MACD is a momentum indicator that shows the relationship


between two moving averages (typically 12-day EMA and 26-day EMA)
and their convergence/divergence.
 Logic:
o Buy Signal: When the MACD line crosses above the signal line.
o Sell Signal: When the MACD line crosses below the signal line.
 Purpose: Used to identify trend changes and momentum strength in the
market.

Relative Strength Index (RSI) Strategy

 Description: RSI is a momentum oscillator that measures the speed and


change of price movements on a scale of 0 to 100.
 Logic:
o Buy Signal: When the RSI value is below 30, indicating an oversold
condition.
o Sell Signal: When the RSI value is above 70, indicating an overbought
condition.
 Purpose: Used to identify overbought and oversold conditions, signaling
potential reversals.

Simple Moving Average (SMA) Crossover Strategy

 Description: SMA is an average of closing prices over a specific period.


The strategy uses the crossover of two SMAs (short-term and long-term) to
generate signals.
 Logic:
o Buy Signal: When the short-term SMA crosses above the long-term
SMA (golden cross).
o Sell Signal: When the short-term SMA crosses below the long-term
SMA (death cross).
 Purpose: Used to identify trend reversals and the beginning of new trends.

. Volume Weighted Average Price (VWAP) Strategy

 Description: VWAP is a trading benchmark that averages the price of a


security weighted by total trading volume.
 Logic:
14
o Buy Signal: When the price moves above the VWAP, indicating
bullish momentum.
o Sell Signal: When the price moves below the VWAP, indicating
bearish momentum.
 Purpose: Used by institutional traders to evaluate trade efficiency and
identify price trends relative to volume.

Chapter 3: Design of the Backtesting Engine


The backtesting engine is modular and consists of the following components:
1. Data Handling Module
 Purpose: Load and preprocess historical stock data.
 Design Features:
o Reads data from CSV files or APIs.
o Ensures data integrity (e.g., handling missing values).
o Formats data with columns like Date, Open, High, Low, Close, and
Volume.
o Aligns data with the selected date range for backtesting.
2. Strategy Module
 Purpose: Encapsulate the logic for implementing different trading
strategies.
 Design Features:
o Each strategy is implemented as a class (e.g., BollingerBandStrategy,

15
RSIStrategy).
o Contains methods for generating buy/sell signals based on price
indicators.
o Modular structure allows adding new strategies without modifying the
core engine.
3. Execution Module
 Purpose: Simulate trades based on the signals generated by the strategy
module.
 Design Features:
o Tracks portfolio state, including cash, holdings, and transaction
history.
o Simulates order execution at historical prices (e.g., close price).
o Handles transaction costs, such as commissions or slippage.
4. Performance Analysis Module
 Purpose: Evaluate the results of the backtest.
 Design Features:
o Calculates key metrics like final portfolio value, profit/loss, return
on investment (ROI), and sharpe ratio.
o Compares strategy performance with a benchmark (e.g., buy-and-
hold).
o Generates visualizations, including equity curves and buy/sell signal
overlays.
5. User Interface Module
 Purpose: Facilitate user interaction for strategy selection and results
interpretation.
 Design Features:
16
o Implemented using Streamlit for a web-based interface.
o Allows users to upload data, configure strategies, and view results
interactively.
Working of the Backtesting Engine
The backtesting engine operates in a sequence of steps, as described below:
Step 1: Load Data
 Load historical stock data using the Data Handling Module.
 Ensure data is aligned with the specified date range.
 Provide users with options to upload custom data or select predefined stock
symbols.
Step 2: Configure Parameters
 User specifies initial capital, date range, and investment style (e.g.,
aggressive, moderate, passive).
 Select a trading strategy from the available options.
Step 3: Generate Signals
 The selected strategy processes the loaded data to generate buy/sell signals.
 Signals are based on the logic defined in the corresponding strategy class.
Step 4: Simulate Trades
 The engine simulates trades by executing orders whenever a signal is
generated.
 Updates portfolio value by accounting for:
o The price at which trades occur.
o Transaction costs.
o Changes in holdings and available cash.
Step 5: Analyze Performance
 Evaluate the performance of the strategy by calculating:
17
o Final Portfolio Value: Value of cash and holdings at the end of the
test.
o Holdings Value: Comparison with the buy-and-hold strategy.
o Trade History: List of trades with date, price, action, and profit/loss
per trade.
 Generate visualizations to help users interpret results.
Step 6: Visualize Results
 Display equity curves, cumulative profit/loss, and buy/sell signals on price
charts.
 Present trade history and metrics in a tabular format

18
Major Modules
1. Data Collection
This module is responsible for fetching stock market data for analysis. It utilizes:
 yfinance: A Python library used to extract stock market data for indices like
Dow Jones, Nifty50, and more.
 Custom Module: src/data/data_loader.py handles the loading and
preprocessing of the stock data.
2. Backtesting Engine
The core of the project, it runs backtests to evaluate strategies:
 Custom Module: src/backtest/backtester.py implements the backtesting
logic for strategies.
 It supports comparing strategies like Bollinger Bands, MACD, and others
against HODL (buy-and-hold) metrics.
3. Strategies
The project includes implementations of various trading strategies, located in
src/strategies:
 bollinger_band.py: Bollinger Bands strategy.
 macd.py: Moving Average Convergence Divergence strategy.
 moving_average.py: General moving average strategy.
 simple_moving_average.py: Basic SMA implementation.
 rsi.py: Relative Strength Index strategy.
 vwap.py: Volume Weighted Average Price strategy.
 base_strategy.py: A base class/interface for standardizing strategy
implementations.
4. Visualization
Visualization modules handle creating charts and performance metrics:
 Visualization File: src/visualizations.py generates graphical insights into
trading strategies.
 Visualization Libraries: Likely includes matplotlib or plotly for plotting
data.
5. Streamlit Web Interface
The Streamlit module builds the project's interactive user interface:
 Primary Files: Located in streamlit_app/, including:
o main.py: Main entry point for the Streamlit app.
o layout.py and sidebar.py: Manage the app's layout and user inputs.
o display.py: Displays the backtest results and insights.
6. Utility Modules
19
Utility functions support metrics calculation and visualization:
 src/utils/metrics.py: Calculates performance metrics like Sharpe Ratio and
Max Drawdown.
 src/utils/visualizations.py: Contains helper functions for data plotting.
7. Testing
The project includes a robust testing framework using:
 Test Files: Located in tests/, such as test_backtester.py for backtesting,
test_data_loader.py for data loading, and test_strategies.py for trading
strategies.
 Testing Libraries: Likely includes unittest or pytest.
8. Project Setup and Dependencies
The project structure supports easy setup and maintenance:
 setup.py: Used for packaging the project.
 requirements.txt: Lists external dependencies (e.g., streamlit, yfinance,
pandas).

20
Snapshots
MAIN PAGE:

VISUALIZATION

21
BACKTEST RESULTS:

22
REFERENCES
Research Papers
1. Cartea, Á., Jaimungal, S., & Penalva, J. (2015). Algorithmic and High-
Frequency Trading. Cambridge University Press.
o Discusses algorithmic trading and includes sections on strategy

backtesting.
2. Bailey, D. H., Borwein, J., Lopez de Prado, M., & Zhu, Q. J. (2014). The
Probability of Backtest Overfitting.
o Addresses statistical issues in backtesting and how to avoid

overfitting.
Link: SSRN paper
3. López de Prado, M. (2018). Advances in Financial Machine Learning.
Wiley.
o Explores machine learning applications in finance, including

backtesting frameworks.
Web Resources
1. Investopedia: Backtesting
o A beginner-friendly explanation of backtesting, its importance,

and limitations.
2. QuantInsti Blog: A Guide to Backtesting Trading Strategies
o Practical insights into implementing backtesting frameworks.

3. Medium: Building a Stock Backtesting Engine with Python


o Provides a step-by-step guide to creating a backtesting engine

using Python.

23

You might also like