On this page
Course at a glance
- Project
- Momentum trading web application
- Language
- Python
- Framework
- Django
- Market data
- Massive
- Brokerage connectivity and trading API
- SnapTrade
- Brokerage used for the tutorial
- Alpaca Paper
- Trading in the course
- Paper trading, not real-money trading
- SnapTrade plan needed
- Commercial Build - $0 for development and testing
- Recommended experience
- Comfortable with basic Python, Git, APIs, and web development. You do not need prior Django or algorithmic trading experience to understand the architecture.
Use SnapTrade Commercial Build for this course
You can follow the SnapTrade portion of this course on Build, SnapTrade’s free Commercial plan for development and testing.
As of September 24, 2026, Build is $0 and includes up to 5 brokerage connections, real-time data, trading included where supported, and Discord community support. You do not need to pay for Launch just to complete this tutorial.
Build is intended for development and testing before production. If you turn the tutorial into a real product, review the current Launch or Custom requirements before going live.
Important: choose Commercial, not Personal
This project uses the Commercial SnapTrade model because the application creates and manages brokerage connections for an end user. In the code, that means registering a SnapTrade user and working with a userId and userSecret.
The course was assembled from recordings made at different times. If you see a later clip briefly create a Personal SnapTrade account while setting up credentials, use Commercial instead for this project. The Commercial model matches the architecture and code taught in the course.
Know the four SnapTrade credentials and identifiers
clientId- identifies your SnapTrade API key.
consumerKey- secret used by your server to authenticate API requests. Keep it on a secure backend.
userId- a stable, immutable identifier your application chooses for a Commercial SnapTrade user. Avoid using an email address because emails can change.
userSecret- secret returned when that SnapTrade user is registered. Store it securely and never expose it in browser-side code.
If the opening account setup video says 'consumer ID' at one point, the credential is called consumerKey.
What you’ll build
The finished project is a Django application that turns market data into a simple momentum ranking, connects a paper brokerage account, and lets you submit a paper order from the app.
1. Retrieve market data
The application uses Massive to retrieve historical U.S. stock prices. You’ll build logic for historical price requests, bulk market data, caching, API limits, retries, and dates when the market was closed.
2. Calculate momentum
The app calculates a 12-minus-1 momentum score for a stock universe, ranks the stocks, and stores the results so they can be displayed in the dashboard and used to generate example trading signals.
3. Connect a brokerage account
SnapTrade connects the Django application to an Alpaca Paper account. Once connected, the application can work with brokerage accounts, cash balances, positions, and orders through one brokerage API layer.
4. Generate trading signals
The strategy layer uses the momentum rankings to generate example signals. The course implementation focuses on buy signals for the highest-ranked stocks and uses a simple equal-dollar allocation so the emphasis stays on the software architecture.
5. Submit and verify a paper trade
The application submits an order through SnapTrade to the connected Alpaca Paper account. You’ll then open Alpaca and verify that the paper order was received.
What each service does
Django
Django is the application framework. It handles the database models, migrations, admin interface, URLs, views, management commands, and HTML templates.
Massive
Massive is the market data provider. It supplies the historical stock prices used by the momentum calculations. It is not the brokerage connection in this project.
SnapTrade
SnapTrade is the brokerage connectivity and trading API layer. The application uses it to connect a brokerage account, retrieve brokerage data, and submit orders where trading is supported.
Alpaca Paper
Alpaca Paper is the simulated brokerage environment used in the tutorial. It gives you a paper account so you can test the full brokerage workflow without funding an account or trading with real money.
Before you start
Create a SnapTrade Commercial Build account
- Go to the SnapTrade Dashboard.
- Choose Commercial.
- Create your account and verify your email.
- Enable two-factor authentication.
- Open API Keys and generate a test API key.
- Save your
clientIdandconsumerKeysecurely. - Keep the
consumerKeyon your backend. Do not commit it to GitHub or expose it in client-side code.
Create a Massive account
Create a Massive account and generate an API key. You’ll use this later when you build the market-data client.
Create an Alpaca Paper account
Create an Alpaca account and use the Paper Trading environment for the tutorial. The paper account simulates trading and is separate from live trading.
Use accurate information when creating your account and follow Alpaca’s current eligibility rules for your location. If an account type is not available where you live, do not enter false residency information just to follow the tutorial.
Set up your local development tools
- Python
- Git
- GitHub
- A code editor
- An authenticator app for two-factor authentication
uvfor the Python virtual environment and dependency workflow used in the course
How the application fits together
Massive supplies the market data. Your Python code turns that market data into momentum scores. Django stores the data and exposes it through a web interface. SnapTrade connects the app to the brokerage account. Alpaca Paper receives the simulated brokerage orders.
Architecture
- Massive market data
- Django data models
- Momentum calculator
- Strategy engine
- Trading signals
- SnapTrade
- Alpaca Paper
That separation is important. SnapTrade does not decide which stocks to buy. Massive does not connect the brokerage account. Your strategy code sits in the middle and makes the application-specific decisions.
How the momentum calculation works
The project uses a 12-minus-1 momentum calculation. In simple terms, it measures how much a stock moved over a longer historical period while excluding roughly the most recent month.
A simplified expression is:
Momentum = (price about 1 month ago / price about 12 months ago) - 1Example: if a stock was $100 about 12 months ago and $125 about 1 month ago, its simplified 12-minus-1 momentum would be 25%.
The application calculates this across its stock universe, ranks the stocks, and stores the results. The tutorial uses momentum because it creates a realistic reason to combine historical market data, calculations, rankings, portfolio data, trading signals, and brokerage APIs.
The strategy is an educational example. It is not a recommendation to buy, sell, short, or hold any security, and historical momentum does not guarantee future performance.
Build the Django project
The course starts from an empty repository. You’ll build the project in small pieces and see the mistakes, debugging, and fixes that happen during normal development.
Create the environment and install Django
You’ll create an isolated Python environment, install the project requirements, bootstrap Django, run the local development server, and apply the initial database migrations.
Useful commands from this stage include:
uv venv
uv pip install -r requirements.txt
python manage.py migrate
python manage.py runserverCheckpoint
- The virtual environment exists.
- Django is installed.
- The development server runs.
- The default Django page loads locally.
- Initial migrations have been applied.
Split the project into trading and portfolio apps
The Django project is divided into two main apps so market/strategy logic and brokerage portfolio data do not become one large codebase.
Trading app
- Stocks
- Historical price data
- Momentum scores
- Trading signals
- Rebalance events
- Market data integrations
- Momentum calculations
- Strategy logic
Portfolio app
- Portfolios
- Positions
- Trades
- Portfolio values
- Performance data
- SnapTrade user and account identifiers
You’ll register both apps in INSTALLED_APPS so Django knows to load them.
Design the trading database
Stock
Stores the ticker and descriptive information for a security, along with fields such as sector, market capitalization, active status, and created/updated dates.
Price data
Stores historical price observations such as date, open, high, low, close, adjusted close, and volume.
Momentum score
Stores the calculated momentum value, calculation date, rank, grouping information, and the date range used for the calculation.
Trading signal
Represents a strategy output such as buy, sell, or hold and can track whether the signal has been executed.
Rebalance event
Records a strategy run, including information such as the number of stocks analyzed, signals generated, portfolio value, execution status, and errors.
Design the portfolio database
Portfolio
Represents a portfolio connected to the application. It stores local portfolio information plus the SnapTrade identifiers needed to work with the connected brokerage user and account.
Position
Represents a security held in the connected portfolio. It can store quantity, average cost, current price, current value, and unrealized gain or loss.
Trade
Stores orders submitted by the app, including the portfolio, security, direction, quantity or value, order status, brokerage order ID, and relevant timestamps.
Performance metric
Creates a place to store portfolio-level values and performance information over time. The course creates the model as a foundation for later analytics.
Apply Django migrations
Whenever the models change, Django migrations translate the Python model definitions into database schema changes.
The normal workflow is:
- Change a model.
- Run
python manage.py makemigrations. - Review the generated migration.
- Run
python manage.py migrate. - Check that the application still runs and the database matches the intended schema.
During a tutorial it can be tempting to delete local migrations and recreate a database when you make a large mistake. Do not use that shortcut casually in a production application with real data.
Configure the Django admin
Django’s built-in admin gives you a fast way to inspect the database while you build.
You’ll create a superuser, register the project models, and configure useful list columns, search, filters, ordering, and read-only fields.
Create a local superuser with:
python manage.py createsuperuserWhy this matters: when the front end says there are no positions or signals, the admin is a quick way to determine whether the problem is the UI or whether the records were never written to the database.
Keep API credentials out of your code
The project uses environment variables so secret credentials are not hard-coded into Python files.
Your local environment will eventually contain values similar to:
MASSIVE_API_KEY=
SNAPTRADE_CLIENT_ID=
SNAPTRADE_CONSUMER_KEY=Keep the real values in a local .env file. Use .env.example to document the required variable names without exposing real credentials. Add .env to .gitignore before pushing the repository.
For a production application, use an appropriate secret-management system rather than treating a local .env file as production secret storage.
Build the Massive market data client
The first major external integration is the market data service. Instead of scattering API calls throughout the project, you’ll create a dedicated Massive client.
The service is responsible for:
- Requesting historical prices
- Converting responses into application-friendly data
- Caching repeated requests
- Respecting plan-level request limits
- Retrying recoverable failures
- Handling missing market dates
- Retrieving data for many stocks efficiently
Cache repeated requests
If the application has already requested the same ticker and historical period, it can reuse that result instead of immediately making another external API request. This reduces unnecessary work and helps stay within API limits.
Handle request limits
The course adds logic to keep track of outgoing requests and wait when needed instead of repeatedly sending requests until the provider rejects them.
Use bulk market data
Requesting one stock at a time becomes inefficient when the strategy needs a broad stock universe. Massive’s grouped daily market endpoint can return daily OHLC and volume data for U.S. stocks in one request, which is useful for wide-scale analysis.
Handle weekends and holidays
A historical date does not always correspond to a trading day. The market-data service includes fallback logic so the application can look around a requested date instead of failing whenever the exact date is a weekend or market holiday.
Calculate and rank momentum
Once historical prices are available, the momentum service calculates scores for the stock universe.
The service can:
- Retrieve the relevant historical prices
- Calculate the 12-minus-1 momentum value
- Calculate many scores in one run
- Rank the stocks
- Group them
- Identify high- and low-ranked stocks
- Save the results to the database
- Return summary statistics for the dashboard
The calculation periods are configurable, so the project can later be adapted to experiment with other definitions of momentum.
Build the SnapTrade brokerage integration
This is where the project moves from market analysis into brokerage connectivity.
The application uses a Commercial SnapTrade API key. For each end user, the app registers a SnapTrade user, securely stores that user’s credentials, generates a Connection Portal URL, and then uses the connected account in later API requests.
Register a SnapTrade user
A Commercial integration creates one SnapTrade user for each end user in the application. Use a stable, immutable userId from your own system and securely store the returned userSecret.
Generate the Connection Portal
The app generates a SnapTrade Connection Portal URL and sends the user through the brokerage connection flow. Current Connection Portal URLs expire after a short period, so generate them when the user is ready to connect.
If the account will place trades, use the trading-enabled connection flow where supported rather than creating a read-only connection.
Connect Alpaca Paper
For this course, the user chooses Alpaca and authorizes the paper account. Once the connection finishes, SnapTrade makes the connected brokerage accounts available to the application.
Retrieve positions
The application reads positions from the connected brokerage account and maps them into the local Position model.
Retrieve balances
The application also retrieves the connected account’s cash balances so portfolio information can be stored and displayed locally.
Submit an equity order
When a user chooses to execute a paper trade, the application sends the order through SnapTrade to the brokerage. The project stores its own trade record and the brokerage order identifier so it can track what happened.
Track order status
Submitting the request is not the end of the order lifecycle. Brokerage orders can be pending, accepted, partially filled, executed, canceled, rejected, or in another brokerage-specific state. The application includes logic for updating its local trade record as the brokerage order changes.
Build the strategy engine
The strategy engine connects the momentum calculations to a portfolio.
It handles concepts such as:
- Whether a rebalance is needed
- Generating trading signals
- Executing selected signals
- Retrieving strategy-related performance information
The course intentionally leaves room for you to add proper backtesting. That is one of the best extensions to build after the tutorial.
Build the Django interface
The course uses Django templates for the front end so the entire application can stay in one Python/Django project.
You’ll connect:
- URL routes
- Django views
- HTML templates
- Database queries
- Form and button actions
A Django view receives a browser request, prepares the data required by the page, and renders the response into a template.
Populate the stock universe
An empty database cannot produce useful momentum scores, so you’ll create a Django management command that seeds the application with an example stock universe and historical price information.
This part is primarily development setup. In a production system, you would design the data-loading process around your actual market universe, provider limits, data licensing, and refresh requirements.
Recalculate momentum and populate the dashboard
Once enough historical data is available, you can calculate momentum for the full example universe.
The dashboard then begins showing:
- Highest-ranked momentum stocks
- Lowest-ranked momentum stocks
- Average momentum
- Median momentum
- Connected portfolios
- Rebalance information
The securities and returns shown in the course are historical examples from the time the recording was made. Your results will differ if you run the project with newer market data.
Create and connect your first portfolio
Next, create a portfolio inside the Django application and connect it to Alpaca Paper.
The flow is:
- Create a portfolio in the app.
- Launch the SnapTrade Connection Portal.
- Choose Alpaca.
- Authenticate with your Alpaca Paper account.
- Authorize the connection.
- Return to the Django application.
- Sync the connected account data.
If the connection worked, the application should be able to retrieve the paper account’s brokerage data through SnapTrade.
Generate trading signals
With momentum scores and a connected portfolio available, the strategy can generate example trading signals.
The course keeps portfolio construction deliberately simple. It creates buy signals for the highest-ranked names and uses an equal dollar amount per selected stock.
A production investment system would need a much more deliberate approach to portfolio construction, risk, trade validation, and user confirmation.
Submit a paper trade
The final workflow connects everything you built.
- Massive data
- Momentum calculation
- Stock ranking
- Trading signal
- SnapTrade
- Alpaca Paper
- Brokerage order
You select a signal in the Django app, submit the paper order, then open Alpaca Paper and verify that the order was received.
Because the tutorial uses a paper account, the course does not require you to risk real money.
Current SnapTrade references for this project
The course code may age as SDKs and APIs evolve. If a method name or initialization pattern in the recording does not match the version you install, use the current SnapTrade documentation as the source of truth.
Checkpoints while you build
After Django setup
- The development server runs.
- The app loads in the browser.
- The initial migrations are applied.
After data modeling
- The database has models for stocks, prices, momentum scores, signals, portfolios, positions, trades, and related records.
- The Django admin lets you inspect those models.
After the Massive integration
- A test request returns stock market data.
- The app can retrieve the historical periods needed for momentum.
- Bulk market data works for the stock universe.
After the SnapTrade integration
- Your app can register a Commercial SnapTrade user.
- You can generate a Connection Portal URL.
- You can connect the Alpaca Paper account.
- The app can retrieve brokerage account data.
After the UI is wired up
- The dashboard loads.
- Momentum scores appear.
- The portfolios page works.
- Trading signals can be generated.
At the end of the course
- You can calculate momentum.
- You can connect a paper brokerage account.
- You can generate a trade signal.
- You can submit a paper order through SnapTrade.
- You can verify the order in Alpaca Paper.
Troubleshooting
uv says there is no virtual environment
Create the virtual environment first with uv venv, then rerun the dependency installation.
Django says there are unapplied migrations
Run python manage.py migrate. If you just changed models, run python manage.py makemigrations first.
Django cannot find the trading or portfolio app
Check that the app has been added to INSTALLED_APPS in the Django settings.
Changes to a model are not appearing in the database
Generate and apply migrations. Also confirm you are inspecting the same local database your Django process is using.
The application cannot find the Massive API key
Check that the value exists in .env, the variable name matches your settings code, python-decouple is installed, and the application process has been restarted if necessary.
Massive returns no price for a date
Check whether the date was a weekend or market holiday and whether the requested date is available on your plan. The tutorial adds nearby-date fallback logic for this reason.
Market-data requests are slow
A broad universe can require substantial data. Confirm that bulk requests are being used where appropriate, avoid duplicate requests, and make sure your caching logic is working.
SnapTrade authentication fails
Confirm that you created a Commercial API key for this project, the clientId and consumerKey are correct, your secrets are loaded on the backend, and the SnapTrade user has a valid userId and userSecret.
I created a Personal SnapTrade key by following a later screen in the recording
Create or switch to Commercial for this project. The application code registers end users and uses userId plus userSecret, which is the Commercial model.
The Connection Portal link stopped working
Generate a fresh Connection Portal URL. These session URLs are intentionally short-lived.
The brokerage connects but the app cannot trade
Confirm that trading is supported for the brokerage and account, your SnapTrade API key has trading enabled, and the brokerage connection was created with the appropriate trading connection type rather than read-only access.
The app says there is no active portfolio
Create and connect a portfolio first. The strategy needs a connected portfolio before it can create portfolio-specific signals.
The account connects but no positions appear
A fresh Alpaca Paper account may have no positions. Confirm that the connection completed successfully and inspect the paper account directly in Alpaca.
I submitted an order but it has not filled
Order behavior can depend on market hours, order type, security availability, brokerage processing, and the paper environment. Check the order status in both your application and Alpaca Paper.
Security checklist
- Keep SnapTrade consumerKey on the server.
- Keep each Commercial userSecret on the server.
- Do not commit .env files.
- Use a stable internal identifier for userId rather than an email address.
- Do not log secrets.
- Use environment-specific credentials.
- Treat paper and production environments separately.
- Validate order details in your application before submission.
- Require clear user confirmation before any production trade.
- Plan for secret rotation and disabled/reconnected brokerage connections.
- Use proper authentication and authorization before exposing portfolio or trading functions to real users.
Before turning the tutorial into a production trading app
The course is designed to teach application architecture and API integration. A tutorial project is not automatically production-ready trading software.
A real application should also address:
- Application authentication
- User authorization
- Secure secret storage
- Trade confirmation
- Risk controls
- Order idempotency
- Monitoring and alerting
- Retries and failure recovery
- Webhook handling where appropriate
- Brokerage-specific edge cases
- Connection health and reconnection flows
- Data freshness
- Production database design
- Audit logging
- Testing across market conditions
- Applicable legal, compliance, and brokerage requirements
When you are ready to move beyond development and testing, review SnapTrade’s launch guidance and current pricing before creating a production key.
What to build next
Build the backtester
The strategy engine leaves room for proper backtesting. Build a system that runs the strategy over historical periods, records portfolio states, accounts for realistic assumptions, and produces reproducible results.
Add a better portfolio construction model
Replace the equal-dollar example with a portfolio-sizing approach and explicit risk constraints.
Add risk controls
- Maximum position size
- Portfolio exposure limits
- Cash checks
- Trade confirmation
- Daily loss or trade limits where appropriate
- Additional order validation
Expand the stock universe
The course intentionally uses a limited universe to make development manageable. Expand it and see what needs to change in your market-data workflow, database, calculation performance, and UI.
Add portfolio analytics
- Historical portfolio value
- Returns
- Asset allocation
- Drawdown
- Position performance
- Cash history
- Contributions and withdrawals
Improve order monitoring
- Order history
- Automatic status updates
- Rejected-order handling
- Partial fills
- Cancel and replace flows
- Better brokerage error messages
Improve the front end
The course intentionally keeps the Django UI simple. You could redesign the application with a more polished Django interface or use a separate front end such as React or Next.js.
Connect another brokerage
The architecture can be extended beyond Alpaca. SnapTrade supports multiple brokerage integrations, but data and trading capabilities vary by brokerage.
Course resources
freeCodeCamp course
Project source
SnapTrade
Django
Frequently asked questions
What do I build in this course?
You build a Python and Django momentum trading application that retrieves stock market data from Massive, calculates momentum rankings, connects an Alpaca Paper account through SnapTrade, generates trading signals, and submits paper orders.
Is SnapTrade free for this tutorial?
Yes. Use SnapTrade’s Commercial Build plan. As of September 24, 2026, Build is $0 for development and testing and includes up to 5 brokerage connections, real-time data, trading included where supported, and Discord community support. You do not need a paid Launch plan to complete the course.
Should I choose SnapTrade Personal or Commercial?
Choose Commercial for this project. The Django application creates and manages a SnapTrade user and passes that user’s userId and userSecret on user-scoped requests. Personal API keys use a different model and do not register separate SnapTrade users.
What does SnapTrade do in the project?
SnapTrade handles the brokerage connectivity layer. The app uses it to connect the Alpaca Paper account, retrieve brokerage account data, and submit paper orders.
What does Massive do in the project?
Massive supplies the historical stock market data used by the momentum calculations. It does not connect the brokerage account.
Why use Alpaca Paper?
Alpaca Paper provides a simulated brokerage environment so you can test the complete connection and order workflow without funding an account or using real money.
Does this course place real trades?
No. The tutorial is built around Alpaca Paper. If you later adapt the application for live trading, treat that as a separate production project with additional security, risk, testing, user confirmation, and compliance requirements.
What is 12-minus-1 momentum?
It is a momentum calculation that looks at a longer historical period while excluding roughly the most recent month. The course uses it as an educational example for turning market data into rankings and trading signals.
Is the momentum strategy investment advice?
No. It is an educational example used to demonstrate application architecture, market-data processing, brokerage connectivity, and trading APIs.
Do I need to know Django already?
No, but basic Python and web-development familiarity will make the course easier. The tutorial builds the Django structure, models, admin, services, views, and templates as part of the project.
Can I use a different brokerage?
The tutorial uses Alpaca Paper because it provides a convenient simulated environment. SnapTrade supports additional brokerages, but availability, data, authentication, and trading capabilities vary by institution.
Does SnapTrade support trading?
Yes, where trading is enabled for the SnapTrade API key, brokerage, connection, and account. Trading availability varies by brokerage and connection type.
What is the difference between consumerKey and userSecret?
The consumerKey is the secret associated with your SnapTrade API key. A userSecret belongs to an individual Commercial SnapTrade user created by your application. Both are sensitive and should be stored securely on the backend.
Why does the course use both market data and brokerage data?
They solve different problems. Massive provides market prices used by the strategy. SnapTrade provides access to the user’s brokerage account. Keeping those concerns separate makes the architecture easier to reason about and replace or extend later.
Can I use this project as production trading software?
Treat it as a learning project and starting architecture, not a production-ready trading system. Production software needs substantially more work around authentication, authorization, secret storage, risk controls, order validation, monitoring, recovery, brokerage edge cases, and compliance.
Glossary
- Algorithmic trading
- Using software and predefined logic to help generate, manage, or execute trading decisions.
- Brokerage API
- An interface that allows an application to work programmatically with brokerage accounts and brokerage functions.
- Connection Portal
- SnapTrade’s user-facing flow for connecting a brokerage account and authorizing the connection.
- Connected account
- A brokerage account made available to an application through a completed brokerage connection.
- Market data
- Price, volume, reference, and other market information used for research, analytics, or trading logic.
- Momentum
- A measure of how a security’s price has changed over a period of time.
- Paper trading
- Simulated trading that lets you test an application or strategy without using real money.
- Position
- A security or asset currently held in a brokerage account.
- Rebalance
- Changing a portfolio so it better matches the target produced by a strategy or allocation model.
- Trading signal
- An output from a strategy indicating a potential action such as buying, selling, or holding.
- userId
- In a Commercial SnapTrade integration, a stable identifier chosen by your application for one end user.
- userSecret
- A secret associated with a Commercial SnapTrade user. It is returned when the user is registered and must be stored securely.