top of page

Part 1: Building My First Simulated Stock Trading Bot with Alpaca & Python 🚀

  • zacharymenzies
  • May 22
  • 2 min read

As someone passionate about finance and tech, and to help me get to grips with some of the CFA® Level 2 concepts, I decided to build a simulated trading bot — a system that uses live market data to make and log trade decisions automatically.

My goal was to use tools that are scalable, secure, and beginner-friendly. Keep in mind that I am not. coding-expert, so this really was a big task.



Here’s what I did, step by step



🧠 Set Objectives


Build a stock trading bot that:

  • Uses Alpaca’s paper trading API (simulated trading)

    • Note that the plan is to integrate real trading later down the line

  • Fetches live historical data

  • Applies a simple moving average crossover strategy

  • Logs simulated trades (buy/sell/hold)

  • Runs entirely in Python

  • Uses VS Code as the development environment



🧰 Tools I Used


I used the following:

  • Python (installed via Anaconda)

  • Alpaca Markets (for stock data + trading simulation)

  • VS Code (code editor & runner)

  • Pandas (data handling)

  • alpaca-trade-api (official API client)



🛠️ Setup & Build Process


Step 1: Set Up Environment

  • Installed Python with Anaconda Navigator

  • Created a new environment called Algotrading_Test

  • Opened the project folder in VS Code

  • Installed required library (pandas)


Step 2: Connected to Alpaca’s Paper API

  • I signed up at alpaca.markets and used my paper trading API keys (free demo account with fake money).

  • I stored the credentials in a file called config.py to keep them separate from the logic.


Step 3: Fetched Historical Data

I wrote a function to pull recent stock data (like AAPL) using Alpaca’s API and the correct TimeFrame.Day enum.


Step 4: Strategy Logic (SMA Crossover)

A simple script checked when the short-term SMA crossed above or below the long-term SMA — a common momentum-based strategy.

if short_SMA > long_SMA: 
	action = "buy" 
elif short_SMA < long_SMA: 
	action = "sell" 
else: 
	action = "hold"

Step 5: Simulated Trade Execution

Instead of placing real trades, I created a simulated executor class that just prints and logs the decision:

SIMULATED BUY: 10 of AAPL at $189.23

Step 6: Ran It!

With everything in place, I ran the script in VS Code and watched my first simulated trading decision come to life — powered by real data.



📈 What’s Next

From here, I plan to:

  • Add logging to CSV or cloud storage (like AWS S3)

  • Schedule the bot to run daily

  • Build a real-time dashboard using Streamlit

  • Eventually connect to a UK-friendly live trading broker like Interactive Brokers

Comments


bottom of page