Python Trading System in Google Colab
How to Use This Python Trading System in Google Colab – A Complete Beginner’s Guide
If you have never used Python before, terms such as Python, Google Colab, stock data, indicators, signals, backtesting, and trading strategy may sound complicated.
Don't worry.
In this tutorial, we will learn how to use a Python trading program in Google Colab, step by step.
You do not need to install Python on your computer.
You do not need to be a programmer.
You simply need:
A Google account
An internet connection
A web browser
Basic understanding of stocks
A willingness to experiment
Google Colab allows you to write and execute Python code directly in your browser, without installing Python locally. It is widely used for Python programming, data analysis, education and machine learning.
What Will We Learn?
By the end of this tutorial, you will understand:
What Google Colab is
How to open the trading program
How to connect the Colab notebook
How to run Python code
What a Python code cell is
How libraries are installed
How stock data is downloaded
How indicators are calculated
How trading signals are generated
How to read the output
How to generate charts
How to change the stock
How to change the strategy parameters
How to troubleshoot common errors
How to use the program for research and backtesting
Important: A trading program is a research and analysis tool. A historical backtest does not guarantee future profits. Never trade real money simply because a Python program produces a BUY or SELL signal.
1. What Is Google Colab?
Imagine that you want to learn driving.
You don't necessarily need to buy a car first.
You can practice in a driving school.
Google Colab is somewhat similar for Python.
Instead of installing Python and setting up several software packages on your computer, you can open a notebook in your browser and run Python code there.
A Colab notebook contains small blocks called cells.
For example:
print("Hello Trading World!")
When you run the cell, Python produces:
Hello Trading World!
That's it!
Your first Python program is running.
Google's own Colab documentation describes Colab as an environment where you can write and execute Python code in your browser.
2. Open the Trading Notebook
Open the notebook:
Python Trading System – Google Colab
Then sign in using your Google account if required.
If the notebook opens successfully, you will see a page containing different sections of Python code.
The notebook will normally have:
Text cells
Code cells
Output
Charts
Tables
Don't try to understand everything at once.
We will take it one step at a time.
3. What Is a Code Cell?
A code cell is simply a box containing Python instructions.
For example:
x = 10
y = 20
print(x + y)
When you run it, the output is:
30
In Colab, you can execute a cell by clicking the Run ▶ button beside the cell. Keyboard shortcuts such as Shift + Enter can also be used.
4. The Most Important Rule for Beginners
Run the cells from top to bottom.
This is extremely important.
Suppose Cell 1 contains:
stock = "RELIANCE"
And Cell 2 contains:
print(stock)
You should run Cell 1 first.
Otherwise Python may produce an error such as:
NameError: name 'stock' is not defined
Why?
Because Python has not yet been told what stock means.
Think of the notebook like a recipe.
You cannot:
Bake the cake
before:
Mixing the ingredients.
5. Installing Required Libraries
Trading programs normally use Python libraries.
A library is a collection of ready-made functionality written by other programmers.
Instead of writing thousands of lines of code yourself, you can use a library.
Common libraries used in Python trading projects include:
pandas
numpy
matplotlib
yfinance
scikit-learn
For example:
Pandas
Used for working with tables and time-series data.
NumPy
Used for numerical calculations.
Matplotlib
Used for charts.
yfinance
Used in many educational projects to retrieve Yahoo Finance market data.
If the notebook contains a command such as:
!pip install yfinance
the ! tells Colab to execute a system command rather than ordinary Python code.
You normally need to run this installation cell before using that library.
6. Importing Libraries
After installing a library, the program may contain something like:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
Don't let this scare you.
It simply means:
"Bring these tools into my program so I can use them."
For example:
import pandas as pd
means that we are importing Pandas and giving it the short name:
pd
Therefore:
pd.DataFrame()
means that we are using the DataFrame functionality from Pandas.
7. What Is a DataFrame?
This is one of the most important concepts in Python trading.
A DataFrame is basically a table.
Imagine an Excel sheet:
| Date | Open | High | Low | Close | Volume |
|---|---|---|---|---|---|
| 1 Oct | 100 | 105 | 98 | 103 | 100000 |
| 2 Oct | 103 | 108 | 101 | 107 | 125000 |
| 3 Oct | 107 | 110 | 105 | 109 | 150000 |
Python's Pandas library can store this type of information in a DataFrame.
Trading data is essentially a large table of this type.
8. Understanding OHLC Data
You will frequently see these terms:
Open
The price at which the trading session opened.
High
The highest price reached during the session.
Low
The lowest price reached during the session.
Close
The closing price.
Volume
The number of shares/contracts traded.
These are commonly called:
OHLCV
O = Open
H = High
L = Low
C = Close
V = Volume
9. Downloading Market Data
A trading program needs historical price data before it can calculate indicators or test a strategy.
A typical program might use:
import yfinance as yf
data = yf.download(
"RELIANCE.NS",
period="5y",
interval="1d"
)
This tells Python to retrieve historical data for Reliance Industries.
The exact ticker and data source used by your notebook may be different.
After downloading the data, you can inspect it using:
data.head()
You may see something like:
Date Open High Low Close
2026-01-01 1400 1425 1390 1415
2026-01-02 1415 1440 1405 1435
...
10. What Does .head() Mean?
This is a very useful beginner command.
data.head()
means:
Show me the first few rows.
Similarly:
data.tail()
shows the last few rows.
You can also use:
data.shape
to find out how many rows and columns are present.
For example:
(1250, 6)
means:
1,250 rows
6 columns
11. Why Do We Need Historical Data?
Suppose our trading rule says:
Buy when the stock crosses above its 52-week high.
We cannot test this rule using only today's price.
We need historical prices.
For example:
2024 → Historical data
2025 → Historical data
2026 → Current data
Python can examine this history and determine:
"What would have happened if I had followed this rule in the past?"
This process is called backtesting.
12. What Is a Trading Strategy?
A trading strategy is simply a set of rules.
For example:
Entry
Buy when:
Price > 52-week high
Exit
Sell when:
Price falls below the chosen exit condition
Filter
Only trade when:
Volume > average volume
The computer can then apply these rules consistently.
This is one of the major advantages of algorithmic trading research.
13. What Is a Trading Signal?
A trading signal is an instruction generated by the strategy.
For example:
BUY
SELL
HOLD
In Python, this might be represented by:
data["Signal"] = 0
where:
0 = No position
1 = Buy
-1 = Sell
The exact coding convention depends on the program.
14. Understanding Technical Indicators
A trading program may calculate indicators such as:
Moving Average
RSI
MACD
Bollinger Bands
ATR
ADX
Volume averages
These indicators transform raw price data into additional information.
For example:
Moving Average
A 20-day moving average gives an average price over the previous 20 trading sessions.
A simplified calculation is:
data["SMA20"] = data["Close"].rolling(20).mean()
This means:
Calculate the average closing price using the previous 20 observations.
15. Understanding RSI
RSI stands for:
Relative Strength Index
It is commonly used as a momentum indicator.
A simplified interpretation is:
Higher RSI → stronger recent momentum
Lower RSI → weaker recent momentum
Do not interpret RSI mechanically as:
RSI above 70 = automatically sell.
Real strategies need testing and context.
16. Understanding the Trading Chart
One of the most useful parts of a Python trading system is visualization.
A program may create a chart containing:
Stock Price
|
| /\
| / \ BUY
| /\ / \ ↑
| / \/ \___/
|
+--------------------> Time
The chart allows you to visually inspect whether the signals make sense.
A chart can reveal things that numbers alone may hide.
17. What Does plt.plot() Do?
If the program contains:
plt.plot(data["Close"])
it means:
Plot the closing price.
For example:
plt.figure(figsize=(12,6))
plt.plot(data["Close"])
plt.title("Stock Price")
plt.xlabel("Date")
plt.ylabel("Price")
plt.show()
The result is a price chart.
18. What Is Backtesting?
This is perhaps the most important concept in algorithmic trading.
Suppose you have this rule:
Buy after a breakout.
Instead of immediately risking real money, you can ask Python:
How would this strategy have performed historically?
Python goes through historical data one row at a time.
Conceptually:
Day 1 → Check rule
Day 2 → Check rule
Day 3 → Check rule
...
Day 500 → Check rule
It records the trades and calculates performance.
19. Understanding Strategy Returns
Suppose you start with:
₹100,000
After a historical simulation, the strategy produces:
₹125,000
The backtest return is:
25%
But this does not mean you will definitely make 25% in the future.
Backtesting is evidence for research—not a guarantee.
20. Important Performance Metrics
A good trading system should not be judged only by total return.
Look at:
Total Return
How much the strategy gained or lost.
CAGR
Compound Annual Growth Rate.
Maximum Drawdown
The largest decline from a previous peak.
Win Rate
Percentage of profitable trades.
Number of Trades
Too few trades can make a strategy unreliable.
Sharpe Ratio
A commonly used risk-adjusted performance measure.
Profit Factor
Total winning profits divided by total losing losses.
21. Maximum Drawdown – A Beginner Example
Imagine your account grows like this:
₹1,00,000
₹1,20,000
₹1,40,000
₹1,30,000
₹1,10,000
The highest value was:
₹1,40,000
The lowest value after that peak was:
₹1,10,000
The decline was:
₹30,000
or approximately:
21.43%
That decline is part of the strategy's drawdown.
A strategy with a high return but an enormous drawdown may be unsuitable for many investors.
22. How to Run the Complete Notebook
For a beginner, follow this sequence.
Step 1
Open the Colab notebook.
Step 2
Connect the runtime.
Step 3
Start with the first code cell.
Step 4
Click the ▶ Run button.
Step 5
Wait for the output.
Step 6
Move to the next cell.
Step 7
Continue from top to bottom.
Do not randomly execute cells in the middle unless you understand the dependencies.
23. What If You See an Error?
Don't panic.
Errors are normal when programming.
Suppose you see:
NameError
It usually means Python doesn't know something that your code is trying to use.
For example:
print(stock)
without previously defining:
stock = "RELIANCE"
can produce a NameError.
24. Common Colab Errors
Error 1 – ModuleNotFoundError
Example:
ModuleNotFoundError: No module named 'xyz'
This usually means the required package isn't available in the current environment.
If appropriate, install it:
!pip install xyz
Then rerun the import cell.
Error 2 – NameError
Example:
NameError: name 'data' is not defined
Possible reason:
You did not run the cell that created data.
Solution
Run the earlier cells first.
Error 3 – KeyError
Example:
KeyError: 'Close'
This can happen when the DataFrame doesn't contain the expected column name.
The first thing to check is:
print(data.columns)
This shows the actual column names.
25. What If the Program Stops Working?
Sometimes the Colab runtime can be restarted.
If that happens, variables created earlier may no longer exist.
The solution is usually simple:
Restart/reconnect the runtime
Then:
Run the notebook again from the beginning.
This is another reason why you should keep your notebook cells logically ordered.
26. How to Change the Stock
One of the most useful things you can learn is how to change the input.
Suppose the program contains:
ticker = "RELIANCE.NS"
You could change it to another supported ticker, depending on the data source.
For example:
ticker = "TCS.NS"
or:
ticker = "INFY.NS"
Then rerun the relevant cells.
Always verify the ticker format required by your data source.
27. How to Change the Time Period
A program may contain something like:
period = "5y"
You may be able to change it to:
1y
2y
5y
10y
depending on the data provider.
More historical data can be useful, but more data is not automatically better.
Market behaviour changes over time.
28. Never Trust a Backtest Immediately
This is one of the most important lessons in algorithmic trading.
Imagine Python reports:
Return: 85%
Win Rate: 78%
It looks fantastic.
But ask:
Were transaction costs included?
Was slippage included?
Was there look-ahead bias?
Was the strategy optimized excessively?
Was the stock survivorship bias considered?
Did the strategy work during different market regimes?
Was the test performed on unseen data?
A beautiful backtest can still produce a poor live strategy.
29. What Is Look-Ahead Bias?
Look-ahead bias occurs when a strategy accidentally uses information that would not have been available at the time of the trade.
For example, suppose you calculate a signal using tomorrow's closing price.
That would make the historical result unrealistic.
A proper backtest must ensure that:
Today's decision uses only information available at that time.
This is one of the most important rules of quantitative trading.
30. Include Trading Costs
Real trading has costs.
Depending on the market and instrument, these may include:
Brokerage
Taxes
Exchange charges
Slippage
Bid-ask spread
Other transaction costs
Suppose a strategy makes 100 trades.
Even a small cost per trade can significantly affect the final result.
Therefore:
Backtest Return
↓
Subtract realistic costs
↓
More realistic strategy result
31. How a Beginner Should Use This Notebook
If you are completely new to Python, don't immediately modify the strategy.
Follow this learning path:
Stage 1 – Run
Run the notebook exactly as provided.
Stage 2 – Understand
Read what each cell does.
Stage 3 – Change
Change only simple inputs.
For example:
Stock
Time period
Indicator period
Stage 4 – Experiment
Try different parameters.
Stage 5 – Validate
Compare results.
Stage 6 – Improve
Add filters, risk management and realistic costs.
32. Your First Experiment
After successfully running the notebook, make one small change.
For example:
ticker = "TCS.NS"
Run the relevant cells again.
Then record:
Stock:
Period:
Number of trades:
Total return:
Maximum drawdown:
Win rate:
Sharpe ratio:
Now repeat the experiment with another stock.
You have just started doing quantitative research!
33. Create a Simple Strategy Comparison Table
You can maintain a table like this:
| Stock | Return | Drawdown | Win Rate | Trades |
|---|---|---|---|---|
| Stock A | 32% | -14% | 58% | 24 |
| Stock B | 25% | -9% | 61% | 18 |
| Stock C | 41% | -23% | 55% | 31 |
Don't automatically choose Stock C because it has the highest return.
You need to consider return versus risk.
34. Beginner Project
Once you understand the notebook, try building your own research project.
Project: Compare Five Stocks
Select five stocks.
For example:
RELIANCE
TCS
INFY
HDFCBANK
ICICIBANK
Run the same strategy on all five.
Record:
Total return
CAGR
Maximum drawdown
Number of trades
Win rate
Sharpe ratio
Then answer:
Which stock performed best?
Which had the lowest drawdown?
Which had the most consistent performance?
Did the strategy work on all stocks?
This is much more useful than simply asking:
"Which stock should I buy?"
35. Take Your Trading System to the Next Level
Once the basic notebook works, you can gradually add:
Technical Indicators
RSI
MACD
ADX
Bollinger Bands
ATR
Price Action
Breakouts
Support/resistance
Candlestick patterns
52-week highs
Momentum
Risk Management
Stop-loss
Position sizing
Risk per trade
Portfolio exposure
Advanced Research
Walk-forward testing
Out-of-sample testing
Monte Carlo analysis
Market regime detection
Portfolio optimization
Machine learning
36. The Golden Rule of Algorithmic Trading
Don't start with:
"How can I make money with Python?"
Start with:
"How can I test whether my trading idea actually works?"
That difference is extremely important.
Python should be used to research, test, measure and improve a trading idea.
It should not be treated as a magic money-making machine.
37. Beginner's Checklist
Before running the notebook:
☐ Google account available
☐ Colab notebook opened
☐ Runtime connected
☐ First cell executed
☐ Required libraries installed
☐ Market data downloaded
☐ Data columns checked
☐ Indicators calculated
☐ Trading signals generated
☐ Chart displayed
☐ Backtest completed
☐ Performance metrics reviewed
☐ Transaction costs considered
☐ Drawdown checked
☐ Strategy tested on unseen data
38. Final Takeaway
You don't need to be an expert programmer to start learning algorithmic trading.
Start with three simple steps:
Python
↓
Market Data
↓
Trading Rules
↓
Backtesting
↓
Risk Analysis
↓
Strategy Improvement
Google Colab makes this learning process easier because you can work with Python directly in your browser without setting up a local Python environment.
The most important skill is not writing hundreds of lines of code.
It is learning to ask the right questions:
Does the strategy work?
Does it work consistently?
What happens during a losing period?
How large is the drawdown?
Does it survive transaction costs?
Does it work on data that was not used to build the strategy?
Once you start asking these questions, you move from simply running Python code to actually thinking like a quantitative trader.
🚀 Your Next Challenge
Run the notebook successfully first.
Then change only one parameter.
Run it again.
Compare the results.
Then change a second parameter.
This simple process—change → run → compare → analyse—is the foundation of systematic trading research.
Python Trading System:
Research → Test → Evaluate → Improve → Automate
Disclaimer: This tutorial is for educational and research purposes only. Historical backtest results do not guarantee future performance. Always perform independent validation and understand the risks before using any strategy with real money.
Comments
Post a Comment