Trading Technology·12 min read

How to Build a Simple Trading Algorithm: A Beginner’s Guide to Algo Trading

AM
Andreas Müller
How to Build a Simple Trading Algorithm: A Beginner’s Guide to Algo Trading

How to Build a Simple Trading Algorithm: A Beginner’s Guide to Algo Trading

Algorithmic trading allows you to automate buying and selling in financial markets using predefined rules. This guide walks you through creating a basic trading algorithm using Python, focusing on a moving average crossover strategy. Here's what you'll learn:

  • Set Up Your Environment: Install Python 3.12+, Jupyter Notebook, and libraries like Pandas, NumPy, yfinance, and Backtrader.
  • Gather Market Data: Use yfinance to fetch historical stock prices and clean them with Pandas.
  • Build a Strategy: Code a 50/200-day moving average crossover strategy to generate buy/sell signals.
  • Backtest Your Algorithm: Test performance using Backtrader with historical data and analyze metrics like returns and Sharpe Ratio.
  • Go Live: Deploy your algorithm on QuantVPS for reliable, uninterrupted trading.

This step-by-step approach ensures you can automate trades effectively while minimizing risks. Start small, test rigorously, and refine your strategy for better results.

Setting Up Your Development Environment

Before diving into coding your trading algorithm, you need to set up the right tools. Python is the backbone of most algorithmic trading setups. It's easy to learn, highly readable, and packed with libraries tailored for financial analysis. To avoid compatibility issues with the latest libraries, make sure you're using Python 3.12 or later.

For an interactive coding experience, Jupyter Notebook is a fantastic choice. It lets you write and run code in chunks, making it easier to test strategies and visualize results. If you're working in a virtual environment, don't forget to install ipykernel and link it to your environment with this command:

ipython kernel install --user --name=env_name

This ensures Jupyter Notebook can access your environment's libraries. Once you've got Python and Jupyter Notebook ready, you're all set to install the libraries needed for building your algorithm.

Installing Python, Jupyter Notebook, and Required Libraries

Python

After setting up Python, you'll need a few essential libraries to get started:

  • Pandas: For handling data manipulation and time-series analysis.
  • NumPy: For performing mathematical operations.
  • yfinance: To fetch historical market data directly from Yahoo Finance.
  • Matplotlib: For creating visualizations and charts.

Install them all at once using pip:

pip install pandas numpy yfinance matplotlib

To handle time zones and Daylight Savings Time in your trading data, add pytz to your setup. If you're planning to explore advanced technical indicators like RSI or MACD later, you might also want to install TA-Lib, which provides access to over 150 indicators.

As you develop your algorithm, keep your project organized by separating it into modules for tasks like data acquisition, strategy implementation, backtesting, and performance evaluation. This will help you keep your code clean and easy to manage.

Getting Started with Backtrader

Backtrader

When it's time to test your strategies, Backtrader is an excellent tool. This free, open-source Python framework is specifically designed for backtesting trading strategies. It simplifies tasks like simulating trades, managing positions, and calculating performance metrics. You can install it with:

pip install backtrader

Backtrader integrates smoothly with Pandas DataFrames, making it easier to work with your data. While Jupyter Notebook is great for prototyping and development, keep in mind that it's not ideal for strategy optimization. The multiprocessing requirements of optimization can cause conflicts in interactive environments like Jupyter.

Getting and Preparing Market Data

Once your development environment is set up, the next step is gathering market data. The yfinance library is a popular choice for accessing historical price data from Yahoo Finance. It gained traction after Yahoo Finance discontinued its official API on May 15, 2017.

Downloading Historical Data with yfinance

yfinance

To fetch historical data for a single stock, you can use the yf.download() function with the stock's ticker symbol. For instance, if you want to retrieve Apple's daily price data for 2023, you would use:

import yfinance as yf

df = yf.download("AAPL", start="2023-01-01", end="2023-12-31")

The result is a Pandas DataFrame containing standard OHLCV columns: Open, High, Low, Close, and Volume. If you're working with multiple stocks, you can pass their ticker symbols as a space-separated string:

df = yf.download("AAPL MSFT GOOG", start="2023-01-01", end="2023-12-31")

The interval parameter lets you choose the data frequency. Daily data (interval='1d') spans decades, but intraday intervals, like 1-minute data, are limited to the past 7 days, while other intraday timeframes typically cover the last 60 days. For most strategies, daily data provides sufficient historical depth.

An important feature is the auto_adjust=True setting, which adjusts prices for stock splits and dividends. This ensures that technical indicators, such as moving averages, remain accurate over long periods.

NEVER MISS A TRADE
Your algos run 24/7
even while you sleep.

99.999% uptime • Chicago, New York & London data centers • From $59.99/mo

Once you've downloaded the data, use Pandas to clean and format it, making it compatible with backtesting tools.

Cleaning and Formatting Data with Pandas

Pandas

Market data often needs some cleanup before you can use it for backtesting. One common issue is the timezone information attached to the date index. Many backtesting engines expect timezone-naive data, so you can strip the timezone with:

df.index = df.index.tz_localize(None)

If you're working with multiple tickers, yfinance may return a MultiIndex DataFrame, where symbols and price columns are organized in separate levels. To simplify things for single-strategy backtesting, you can flatten the structure using df.columns.droplevel(), or just select the ticker you're analyzing.

Handling missing data is also crucial. Use df.dropna() to remove rows with missing values or df.fillna(method='bfill') to backfill gaps without introducing look-ahead bias. For strategies like moving averages, focus on the Adjusted Close column to ensure your indicators are accurate.

It's worth noting that yfinance operates as an unofficial scraper, making it ideal for learning and prototyping but less reliable for production-level systems.

Creating a Simple Moving Average Crossover Strategy

Once your market data is cleaned and ready, you can dive into building your first trading strategy. The moving average crossover strategy is often seen as the "Hello World" of quantitative trading because it’s straightforward to grasp and execute.

How the Moving Average Crossover Strategy Works

This strategy hinges on two moving averages: a short-term (or "fast") average and a long-term (or "slow") average. When the short-term average crosses above the long-term average, it’s called a Golden Cross, signaling upward momentum and a potential buy opportunity. On the flip side, a Death Cross occurs when the short-term average crosses below the long-term average, indicating downward momentum and suggesting a sell.

Common lookback periods include:

  • 20/50 days for short-term trends
  • 50/200 days or 100/400 days for long-term trends

Since moving averages rely on historical prices, they act as lagging indicators. This means they confirm trends rather than predict them. While the strategy shines in trending markets, it tends to struggle in choppy or sideways conditions.

"The Moving Average Crossover technique is an extremely well-known simplistic momentum strategy. It is often considered the 'Hello World' example for quantitative trading."
QuantStart

"The Moving Average Crossover technique is an extremely well-known simplistic momentum strategy. It is often considered the 'Hello World' example for quantitative trading."
QuantStart

For example, in October 2022, Intrinio CEO Rachel Carpenter backtested this strategy on Apple (AAPL) from September 16, 1982, to 2022. The results showed 26 positions with a total return of 429.39%. While this underperformed the buy-and-hold return of 685.88% for the same period, the strategy demonstrated its effectiveness during downtrends. When applied to Palantir (PLTR) from September 30, 2020, to October 2022, it returned -15.29%, significantly reducing the buy-and-hold loss of -66.87%.

With this understanding, let’s break down how to implement this strategy step by step.

Coding the Strategy in Python

You can calculate moving averages in Python using Pandas’ rolling mean function. Below is an example of how to implement a 50/200-day moving average crossover strategy:

import numpy as np

# Calculate moving averages
df['SMA_50'] = df['Close'].rolling(window=50).mean()
df['SMA_200'] = df['Close'].rolling(window=200).mean()

# Generate signals: 1 for a long position, 0 for cash
df['Signal'] = np.where(df['SMA_50'] > df['SMA_200'], 1, 0)

# Identify crossover points
df['Position'] = df['Signal'].diff()

The first 200 rows will have NaN values due to the long-term moving average calculation. You can remove these rows using df.dropna(). The Position column helps identify key crossover points: a value of 1 marks a Golden Cross (buy signal), while -1 marks a Death Cross (sell signal).

To calculate returns for the strategy, multiply the daily log returns by the signal, shifted by one day to avoid look-ahead bias:

df['Returns'] = np.log(df['Close'] / df['Close'].shift(1))
df['Strategy_Returns'] = df['Returns'] * df['Signal'].shift(1)

Finally, compare the cumulative returns of this strategy with a simple buy-and-hold benchmark. This basic algorithm provides a functional starting point for backtesting and refining your trading approach in the next steps.

Testing Your Strategy with Backtrader

You've coded your moving average crossover strategy, and now it's time to find out how it holds up. Testing is a crucial step before even thinking about live deployment. Backtrader provides a solid framework for running your algorithm on historical data and analyzing its performance through key metrics.

Setting Up Backtrader for Testing

To get started, you’ll need to set up Backtrader's engine, called Cerebro. Begin by adding your historical data feed with cerebro.adddata(data) and linking your strategy using cerebro.addstrategy(YourStrategy). Backtrader makes data access straightforward, using [0] for the current bar and [-1] for the previous one. Once everything is in place, initiate the backtest with cerebro.run(). This will process each bar of data and execute your strategy. After completing the test, you’ll have a framework ready for evaluating how your strategy performs.

Reviewing Performance Metrics

When the backtest wraps up, dive into the performance metrics to see how well your strategy worked. Start with Total Return, which gives you the percentage of profit or loss over the testing period. Another key metric is the Profit Factor, which compares gross profits to gross losses - a value above 1.0 signals profitability.

STOP LOSING TO LATENCY
Execute faster than
your competition.

Sub-millisecond execution • Direct exchange connectivity • From $59.99/mo

The Sharpe Ratio is another critical indicator, as it measures returns adjusted for risk. A ratio above 1.0 is generally good, above 2.0 is great, and anything over 3.0 might indicate a bug or look-ahead bias in your code. Thankfully, Backtrader’s event-driven design helps minimize the risk of look-ahead bias.

For a deeper analysis, look at metrics like annualized volatility and Conditional Value at Risk (CVaR). These help you understand the risks tied to your strategy. Together, these metrics will give you a thorough assessment of whether your moving average crossover strategy is ready to go live or needs more tweaking.

Running Your Algorithm on QuantVPS

QuantVPS Pricing Plans Comparison for Algorithmic Trading

QuantVPS Pricing Plans Comparison for Algorithmic Trading

QuantVPS Pricing Plans Comparison for Algorithmic Trading

After testing your strategy with Backtrader, the next step is to go live on QuantVPS. Relying on a standard desktop for trading has its risks - power outages, internet hiccups, or unexpected restarts can disrupt trades or fail to execute stop-loss orders.

QuantVPS eliminates these issues. Hosted in Tier-IV data centers, it boasts N+1 redundancy and an impressive 99.999% uptime. It offers ultra-low latency (as fast as 0.52ms) on AMD EPYC processors, NVMe storage, and unmetered 1Gbps+ bandwidth. Plus, a 24/7 Network Operations Center uses AI-driven monitoring to detect and address potential problems before they escalate. With this level of reliability and speed, QuantVPS ensures your trading strategies run smoothly. The next step? Picking the plan that suits your needs.

Selecting Your QuantVPS Plan

The plan you choose depends on the number of trading charts and the resources your strategies require. Here’s a breakdown:

  • VPS Lite: Ideal for a single moving average crossover strategy, this plan includes 4 cores, 8GB RAM, and 70GB NVMe storage. It costs $59.99/month (or $41.99/month if billed annually) and supports 1–2 charts.
  • VPS Pro: Designed for multiple strategies across 3–5 charts, this plan offers 6 cores and 16GB RAM at $99.99/month (or $69.99/month annually).
  • VPS Ultra: Perfect for 5–7 charts, this plan features 24 cores and 64GB RAM at $189.99/month (or $132.99/month annually).
  • Dedicated Server: Built for institutional trading with 7+ strategies, it provides 16+ cores, 128GB RAM, and 2TB+ NVMe storage at $299.99/month (or $209.99/month annually).

Opting for annual billing can save you roughly 30% compared to monthly payments. You can always start small and upgrade as your trading demands grow.

Deploying Your Algorithm on QuantVPS

After selecting your plan, it’s time to set up your algorithm for continuous operation. Once you’ve signed up, you’ll receive RDP credentials via the QuantVPS dashboard. Here’s how to deploy:

  1. Connect to Your VPS: Use Remote Desktop Connection on Windows or Microsoft Remote Desktop on Mac to access your VPS.
  2. Install Python: Open a browser on the VPS, download Python from python.org, and install it on the C: drive.
  3. Install Required Libraries: Open Command Prompt on the VPS and run:
    pip install backtrader yfinance pandas
    
  4. Upload Your Strategy: Use RDP clipboard sharing or a cloud storage service to transfer your strategy file to the VPS.
  5. Run Your Algorithm: Open Command Prompt, navigate to the folder containing your script using the cd command, and execute:
    python your_strategy.py
    
pip install backtrader yfinance pandas
python your_strategy.py

Once running, your algorithm will operate continuously - even if you disconnect from the VPS or turn off your local machine. QuantVPS ensures your trading stays uninterrupted, no matter what.

Conclusion and Next Steps

You've made it through the entire journey - from setting up your development environment to deploying your algorithm live. As Quantified Strategies puts it:

"Algorithmic trading is a tool - not a guaranteed profit machine. Success requires discipline, patience, and willingness to learn from both wins and losses".

"Algorithmic trading is a tool - not a guaranteed profit machine. Success requires discipline, patience, and willingness to learn from both wins and losses".

Before putting real money on the line, test your algorithm in a simulated environment for 1–3 months. This helps you gauge its performance with live market data and account for execution delays. Once you're ready to trade live, start cautiously - risk no more than 0.5% per trade and keep a close eye on performance. To safeguard against major setbacks, implement protective measures like kill-switches and daily loss limits to shield yourself from unexpected errors or volatile market swings.

Refinement is key. Use Monte Carlo simulations to evaluate how your strategy holds up under different market conditions. To ensure your strategy isn’t overly dependent on ideal historical scenarios, exclude the top 5–15% of your best-performing trades and recheck its effectiveness. Simpler algorithms with fewer parameters often perform better in live trading because they’re less reliant on historical perfection.

As you gain more experience, experiment with advanced strategies, but always backtest rigorously using 10–20 years of data. Pay attention to your Sharpe Ratio - it’s a solid measure of risk-adjusted returns. A ratio of 1.0 is good, while 1.5 or higher is ideal. Organize your work with Git version control to keep your code clean, track changes, and ensure reproducibility.

Algorithmic trading now drives 70–80% of equity market volume in developed economies. With discipline, continuous learning, and the right tools like QuantVPS, you can develop strategies that are both reliable and profitable. These principles are the foundation of success in algorithmic trading.

FAQs

How do I avoid look-ahead bias in my backtest?

To avoid look-ahead bias, ensure your algorithm relies solely on data available at the moment of the trade decision. This means basing trades on information up to the close of the current period, without incorporating any future data. When simulating trades, execute orders at the next available opportunity, such as the opening price of the following period. Keeping signal generation and execution data separate is key to producing realistic and unbiased backtesting outcomes.

Should I use adjusted close or close prices for moving averages?

When working on trading algorithms, it's typically best to use adjusted close prices for calculating moving averages. These prices factor in corporate actions such as dividends and stock splits, giving a clearer picture of a stock’s value over time. This added precision is essential for dependable backtesting and analyzing trading strategies.

What’s the safest way to start trading this strategy live?

To start trading live without unnecessary risks, begin by backtesting your algorithm using historical data. This step helps you gauge its performance and identify any weaknesses. Once you're confident, move on to a demo or paper trading account. These tools let you simulate live trading scenarios without putting real money on the line.

When transitioning to live trading, start small. Use modest position sizes to minimize exposure while you get comfortable. Only increase your trades gradually after achieving consistent positive results. And always prioritize risk management - set up stop-loss orders to cap potential losses and protect your capital.

AM

Andreas Müller

March 18, 2026

Share this article:

About the Author

AM

Andreas Müller

European Markets Specialist

Andreas covers trading from a global perspective, with expertise in multi-timezone trading setups and cross-market arbitrage strategies.

Areas of Expertise
Multi-Timezone TradingEuropean MarketsForex TradingGlobal Infrastructure
Published:

Disclaimer: QuantVPS does not represent, guarantee, support, or endorse any third-party brands, products, or services mentioned in this article. All brand references are for informational purposes only. Read our full Brand Non-Endorsement Disclaimer.

Risk Disclosure: QuantVPS does not provide financial, investment, or trading advice. Trading involves substantial risk of loss and is not suitable for every investor. Past performance is not indicative of future results. You should consult a qualified financial advisor before making any trading decisions. Read our full Trading Disclaimer.

More articles

All posts
Best VPS optimized for futures trading - QuantVPS Logo
Best VPS optimized for futures trading - QuantVPS Logo

ONLINE WHILE YOU SLEEP
Run your trading setup
24/7 - always online.

Manage trades seamlessly with low latency VPS optimized for futures trading
CME GroupCME Group
Latency circle
Ultra-fast low latency servers for your trading platform
Best VPS optimized for futures trading in Chicago - QuantVPS LogoQuantVPS
Best VPS optimized for futures trading - QuantVPS Logo
Best VPS optimized for futures trading - QuantVPS Logo

Billions in futures
VOLUME TRADED DAILY
ON OUR LOW LATENCY
SERVERS

Chart in box

24-Hour Volume (updated Mar 18, 2026)

$11.71 Billion
2.91%
Best VPS optimized for futures trading - QuantVPS Logo
Best VPS optimized for futures trading - QuantVPS Logo

99.999% Uptime
– Built for 24/7
Trading Reliability.

Core Network Infrastructure (Chicago, USA)
100%
180 days ago
Today
DDoS Protection | Backups & Cyber Security
Operational
Best VPS optimized for futures trading - QuantVPS Logo
Best VPS optimized for futures trading - QuantVPS Logo

ELIMINATE SLIPPAGE
Speed up order execution
Trade smarter, faster
Achieve more consistency on every trade

ES 03-26
CME
BidPriceAsk
5766.00
67
5765.75
45
5765.50
128
5765.25
89
5765.00
234
312
5764.75
156
5764.50
78
5764.25
203
5764.00
Spread0.25

Market Buy Order

50 Contracts

Target: 5765.00