P
PipsGrowth

Python Environment Setup

Set up a complete Python development environment for algorithmic trading in under 30 minutes. From installation to your first strategy.

Difficulty: Beginner
Duration: 35 min
Step 1 of Learning Path

What You'll Learn

Install Python & tools
Create virtual environments
Install trading libraries
Set up Jupyter Notebook
Organize trading projects
Build your first strategy

Prerequisites

System Requirements

  • Windows 10+, macOS 10.14+, or Ubuntu 18.04+
  • 4GB RAM minimum (8GB recommended)
  • 5GB free disk space

Required Tools

  • Python 3.10+
  • Code editor (VS Code recommended)
  • Command line / Terminal

Prior Knowledge

  • Basic Python (variables, functions, loops)
  • Basic understanding of financial markets
  • Basic command line knowledge

Step-by-Step Guide

1

Install Python

Download and install Python 3.10+ on your system

Python
# Check if Python is installed
python --version
# Expected output: Python 3.10.x or higher
# On Windows: Download from https://www.python.org/downloads/
# On macOS:
brew install python3
# On Ubuntu/Debian:
sudo apt update && sudo apt install python3 python3-pip python3-venv
# Verify installation
python3 --version
pip3 --version
2

Create a Virtual Environment

Isolate your project from system packages using venv

Python
# Create a new project directory
mkdir my-trading-bot
cd my-trading-bot
# Create virtual environment
python -m venv venv
# ACTIVATE the virtual environment
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activate
# You'll see (venv) in your terminal prompt
# (venv) $ pip install ...
# Deactivate when done
deactivate
3

Install Core Trading Libraries

Install all required libraries for algorithmic trading

Python
# Core data science stack
pip install pandas numpy matplotlib
# Market data
pip install yfinance
# Technical analysis
pip install ta-lib pandas-ta
# Backtesting
pip install backtrader vectorbt
# Broker integration
pip install MetaTrader5 # Windows only
# Machine learning (optional)
pip install scikit-learn tensorflow xgboost
# Save all dependencies
pip freeze > requirements.txt
# Later, recreate the environment:
pip install -r requirements.txt
4

Set Up Jupyter Notebook

Interactive environment for developing and testing strategies

Python
# Install Jupyter
pip install jupyter jupyterlab
# Launch Jupyter Lab (recommended)
jupyter lab
# Or classic Jupyter Notebook
jupyter notebook
# Install useful extensions
pip install jupyter-contrib-nbextensions
jupyter contrib nbextension install --user
# Create your first notebook and test:
# In a new cell, type:
import pandas as pd
import numpy as np
import yfinance as yf
import matplotlib.pyplot as plt
# Download test data
df = yf.download("EURUSD=X", period="6mo")
df['Close'].plot(figsize=(12, 6), title="EUR/USD")
plt.show()
print("Setup complete! Ready to trade.")
5

Recommended Project Structure

Organize your trading project professionally

Python
# Recommended project structure:
#
# my-trading-bot/
# ├── venv/ # Virtual environment (don't commit)
# ├── data/ # Cached market data
# │ ├── raw/ # Raw downloaded data
# │ └── processed/ # Cleaned data
# ├── strategies/ # Trading strategies
# │ ├── __init__.py
# │ ├── sma_crossover.py
# │ └── rsi_reversal.py
# ├── indicators/ # Custom indicators
# │ ├── __init__.py
# │ └── custom_rsi.py
# ├── backtests/ # Backtest scripts & results
# │ ├── run_backtest.py
# │ └── results/
# ├── live/ # Live trading scripts
# │ ├── mt5_trader.py
# │ └── risk_manager.py
# ├── notebooks/ # Jupyter notebooks for research
# │ ├── exploration.ipynb
# │ └── strategy_dev.ipynb
# ├── config.py # Configuration & API keys
# ├── requirements.txt # Dependencies
# ├── .env # Environment variables (don't commit)
# └── .gitignore # Git ignore rules
# Create this structure:
import os
dirs = [
"data/raw", "data/processed",
"strategies", "indicators",
"backtests/results", "live",
"notebooks"
]
for d in dirs:
os.makedirs(d, exist_ok=True)
init_file = os.path.join(d.split("/")[0], "__init__.py")
if not os.path.exists(init_file):
open(init_file, "w").close()
print("Project structure created!")
6

Build Your First Strategy

Simple Moving Average crossover strategy to verify your setup

Python
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 1. Download data
print("📥 Downloading data...")
df = yf.download("EURUSD=X", period="1y", interval="1d")
print(f"Downloaded {len(df)} bars")
# 2. Calculate indicators
df['SMA_20'] = df['Close'].rolling(20).mean()
df['SMA_50'] = df['Close'].rolling(50).mean()
# 3. Generate signals
df['Signal'] = 0
df.loc[df['SMA_20'] > df['SMA_50'], 'Signal'] = 1 # Buy
df.loc[df['SMA_20'] < df['SMA_50'], 'Signal'] = -1 # Sell
# 4. Calculate returns
df['Returns'] = df['Close'].pct_change()
df['Strategy'] = df['Signal'].shift(1) * df['Returns']
# 5. Performance metrics
total_return = (1 + df['Strategy'].dropna()).prod() - 1
sharpe = df['Strategy'].mean() / df['Strategy'].std() * np.sqrt(252)
win_rate = (df['Strategy'] > 0).sum() / (df['Strategy'] != 0).sum() * 100
print(f"\n📊 Results:")
print(f"Total Return: {total_return*100:.2f}%")
print(f"Sharpe Ratio: {sharpe:.2f}")
print(f"Win Rate: {win_rate:.1f}%")
print(f"Total Trades: {df['Signal'].diff().abs().sum() / 2:.0f}")
# 6. Plot
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(14, 8), sharex=True)
ax1.plot(df.index, df['Close'], label='EUR/USD', alpha=0.7)
ax1.plot(df.index, df['SMA_20'], label='SMA 20', linewidth=1)
ax1.plot(df.index, df['SMA_50'], label='SMA 50', linewidth=1)
ax1.set_title('EUR/USD with Moving Averages')
ax1.legend()
ax2.plot(df.index, (1 + df['Strategy']).cumprod(), label='Strategy', color='green')
ax2.plot(df.index, (1 + df['Returns']).cumprod(), label='Buy & Hold', color='gray', alpha=0.5)
ax2.set_title('Cumulative Returns')
ax2.legend()
plt.tight_layout()
plt.savefig('first_strategy.png', dpi=150)
plt.show()
print("\n✅ Setup verified! Your environment is ready.")

Common Troubleshooting

!

pip: command not found

Use `python -m pip` instead of `pip` directly, or reinstall Python with PATH option checked

!

TA-Lib installation error

On Windows: download .whl from unofficial binaries. On macOS: run `brew install ta-lib` first. On Linux: `sudo apt install libta-lib-dev`

!

MetaTrader5 not working on macOS/Linux

MetaTrader5 Python API only works on Windows. Use Wine or a Windows VPS for other platforms

!

Jupyter can't find installed packages

Make sure Jupyter is installed inside the same virtual environment: `pip install jupyter` after activating venv

VS Code Setup for Trading

Python Extension

IntelliSense, linting, and debugging

Jupyter Extension

Run notebooks directly in VS Code

Pylance

Type checking and performance analysis

GitLens

Track changes and collaborate on strategies

PipsGrowth - Expert Broker Reviews, Trading Strategies & Tools