[KongchangAI]
· 5 min read· 2,697 words

Building an AI Trading Bot with Claude and Zero Code: A Full Breakdown of the ALPHA Framework

Building an AI Trading Bot with Claude and Zero Code: A Full Breakdown of the ALPHA Framework

Build a daily trading system with Claude and zero code, centered on rigorous validation and risk-control discipline.

The ALPHA framework shows how to build a daily trading system with only the Claude desktop app and zero coding experience. It stresses that a bot is just a single rule placing orders, while a real trading system inserts five layers between rules and orders: data validation, backtesting, risk control, alerts, and review. The key methodology is to first validate the backtester itself (edge implantation, pure noise, and cheating-signal tests), then split data into training and locked test windows for out-of-sample validation, and use parameter-neighbor tests to detect overfitting. Ultimately only 7 of 44 ideas passed six hurdles; combined with the QQQ-gold rotation core, the locked test produced about 29% annualized return and 13% drawdown. Going live uses Alpaca paper trading with broker-side stop-losses, daily loss circuit breakers, and Telegram alerts, while retirement conditions are hard-coded and the model can only fix bugs, not change rules.

Building an AI Trading Bot with Claude and Zero Code: A Full Breakdown of the ALPHA Framework

Trading automation has long been considered the exclusive domain of programmers, but Brendan—a creator with three years of investment banking experience and a UCLA background in mathematics and economics—published a complete three-hour course on YouTube showing how to go from zero coding experience to delivering a trading system that runs automatically every day, using only the Claude desktop app. The methodology is called the ALPHA framework, covering five stages: architecture, logic, validation, operations, and adaptation.

To be clear, the video's author repeatedly emphasizes that this is not investment advice and does not guarantee profits. The value of the course lies in providing a reproducible operational process and testing discipline, not some winning strategy.

The Essential Difference Between a Trading Bot and a Trading System

The course opens by clarifying a common misunderstanding: a bot and a trading system are two different things. A bot is simply a trading rule connected directly to an order action—for example, "buy Nvidia when it drops 5% in a week, sell when it returns to its original price." This structure has no data validation, no rule testing, and no risk-control interception; once something goes wrong, there is no buffer.

A real trading system inserts a complete middle layer between rules and orders: data input, historical backtesting, risk control, real-time alerts, and periodic review. The risk layer can directly veto a trade when an order touches its own risk threshold—this is especially critical in unattended automation scenarios. Without risk control, twenty strategies could all trigger at once and instantly wipe out all capital.

There are two other foundational decisions in the architecture. First, you must use the desktop app of Claude or ChatGPT rather than the browser version, because only the desktop version can read and write local folders, execute backtesting programs, and schedule tasks on a timetable. Second, API keys must never be pasted directly to the model; instead, they are manually written into the .env file within the project, and all subsequent prompts include a built-in rule to "never read that file."

Illustration of backtesting costs eroding profits

Why Daily Bars Are the Best Starting Point for Beginners

On the choice of timeframe, the course offers a compelling cost argument. Assuming a combined cost of about 0.05% per buy and sell, a strategy trading 250 times a year (roughly once a day) would have costs eat about 25% of profits. The higher the trading frequency, the thicker the edge each trade needs to have.

Daily strategies also have three structural advantages. First, the data is free—Yahoo Finance provides decades of daily data through the yfinance library, whereas Yahoo only retains about one month of minute-level data and about two years of hourly data, far from enough for effective backtesting. Second, the matching logic is simple: calculate signals at any time after the close, place orders to be filled at the next day's open, which is perfectly consistent with backtest assumptions, and slippage is almost negligible. Third, the operational barrier is low—the bot only needs to run once a day.

The course also introduces the intermediate concept of "market regime." Each asset is tagged on any given trading day with two types of labels: whether the price is in an uptrend or downtrend relative to the 200-day moving average, and whether that day's volatility is calm or turbulent. Strategies must read the regime tags before trading, because the same mean-reversion signal that works in an uptrend may keep losing money in a downtrend.

Validating the backtest engine by implanting a known edge

The 200-day moving average is the most commonly used long-term trend benchmark in technical analysis, representing the arithmetic average of closing prices over the past 200 trading days. It is widely viewed as the bull-bear dividing line: when price stands above the 200-day MA, it is usually interpreted as a long-term uptrend, and a break below means the trend may be weakening. In the course, the 200-day MA plays a dual role—it is both the switching signal for the QQQ and gold rotation strategy and the basis for determining whether an asset is in an uptrend or downtrend (one of the regime tags). The reason for choosing 200 days rather than a shorter period is that long-period moving average signals are more stable and switch less often, naturally curbing the cost erosion from overtrading, which aligns closely with the positioning of daily strategies.

Profit Factor is a core metric in backtest evaluation for measuring a strategy's profit efficiency, calculated as the total amount of all winning trades divided by the total amount of all losing trades. A profit factor of 1.0 means gains and losses cancel out, while 1.3 means that for every 1 yuan lost, 1.3 yuan is gained. It is more informative than win rate, because a strategy with a 90% win rate but one huge loss can still lose money overall, whereas profit factor directly reflects the net efficiency of capital. The course sets 1.3 as the minimum threshold, a conservative requirement for strategy robustness given limited sample sizes.

Asset Research: Understand the Asset First, Then Match the Strategy

The course provides an actionable asset classification method. For each candidate asset, use historical data to answer five questions: does it continue after breaking to new highs, does it rebound after a sharp drop, does it move in the same direction as the broad market, how does it perform when the market falls, and how large is its intraday volatility. Based on these measurements, assets are tagged as "trending," "mean-reverting," "defensive," and so on, and the tags then determine which strategy families suit them.

In the course example, QQQ is marked as having strong trend continuation, while SPY, IWM, and DIA show clear mean-reversion characteristics. The author also shows a correlation heatmap to illustrate the diversification logic of an asset portfolio—part of the reason for choosing the QQQ and gold rotation as the core holding is precisely their low correlation in key periods.

This "research first, match later" order is essentially about narrowing the search space. Rather than letting the model generate strategies out of thin air, it is better to first lock down an asset's behavioral characteristics and then test only matching strategy types, which significantly reduces the probability of overfitting.

Validation: Validate the Backtester First, Then the Strategy

The most methodologically valuable part of the course is the validation of the backtest itself. The author argues that if the backtest code has bugs, all subsequent conclusions are untrustworthy, and non-technical users are precisely the ones least able to spot such problems.

The solution is to use fake data with known answers for three tests. The first is implanting an edge: construct a set of prices where, whenever a specific signal appears, the next day's price rises an extra 1%, so the backtester should report a return of about 0.6% to 1.2% per trade (after costs). The second is pure noise: the same signal paired with random prices should report near-zero or negative results. The third is a cheating signal: construct a signal that uses the next day's price, and the backtester's built-in look-ahead guard should actively throw an error and abort.

Data is divided into a training window and a locked test window. The course example uses 2022 to 2024 for parameter tuning, and data after 2025 is run only once at the very end. The author emphasizes that the locked test can only be used once—if you look at the results, change parameters, and rerun, that portion of data has already been contaminated into a training set and lost its meaning as out-of-sample validation.

Strategy screening also sets multiple hurdles: must be profitable after costs, must reach a minimum sample size of trades, profit factor (total winning trades divided by total losing trades) no lower than 1.3, and parameter neighbors (such as 198-day, 201-day, and 250-day moving averages) must also be profitable. The neighbor test is the core means of identifying overfitting—a strategy that performs excellently only at one precise parameter and collapses when the parameter shifts slightly is most likely luck rather than a pattern.

Look-ahead Bias is one of the most fatal and hidden errors in backtesting, referring to a strategy using information at a point in time that was not yet available then. Typical examples include: using the same day's closing price to decide buys and sells at the same day's open, using statistics from the entire dataset (such as the full-period mean) to standardize early signals, or mistakenly introducing the next day's price into signal calculations. Such bugs make backtest results absurdly inflated, and the strategy is bound to fail in live trading. The "cheating signal" test in the course is exactly the gatekeeping mechanism for this problem—deliberately constructing a signal that uses the next day's price; if the backtester does not actively throw an error and abort, it means its look-ahead guard is useless and all subsequent backtest conclusions are untrustworthy.

Out-of-sample Testing is the standard practice for preventing overfitting: split historical data into a training set and a test set, optimize parameters only on the training set, and use the test set only once for final evaluation. The course uses 2022 to 2024 for training and post-2025 for the locked test, emphasizing that the locked window "can only be used once"—because once you go back and adjust parameters based on test results and rerun, the test set is informationally merged into the training process, and the validity of the out-of-sample test is lost. This is a discipline that is easily overlooked in quantitative research yet determines success or failure.

Results: From 44 Ideas to 7 Strategies

In the course's example run, the core strategy is automatically identified as a rotation between QQQ and gold: hold QQQ when it is above the 200-day moving average, switch to gold when it falls below. This rule switches only a few times a year, has extremely low costs, and achieved about 24.8% annualized return and 11.2% maximum drawdown in the locked test.

The screening for short-term strategies is more stringent. The 44 initial ideas went through six hurdles—suitability, training-period profitability, number of trades, profit factor, neighbor values, and locked test—and only 7 survived in the end, including sharp-drop buy and breakout strategies for QQQ, XLK, XLF, and XLY, plus a gold sharp-drop strategy. Combined with the core, these short-term strategies produced a locked-test annualized return of about 28.7% to 29% with a maximum drawdown of about 13%.

The author also notes that these numbers were obtained under specific parameters and a specific historical period and should not be taken as expectations for future returns. The goal of the course is to demonstrate the process, not to deliver a product ready to be deployed with real money.

Validating the quarterly strategy re-selection process

Going Live and Risk Control: Let the System Hit the Brakes Itself

The live trading segment uses an Alpaca paper trading account. The course specifically explains the timing: Alpaca rejects orders between 9:28 and 19:00 New York time, so the bot must place orders after 19:00, waiting for the next day's open to fill at market price, which aligns perfectly with the backtest assumptions.

The system sets up four safety mechanisms: stop-loss orders held broker-side (effective even if the local computer is shut down or the program crashes), a unique ID for each order to prevent duplicate submissions, a run lock to prevent two processes from trading simultaneously, and a halt on opening new positions when the daily loss exceeds 3%. On top of that, there are three optional limits: a manual pause file, automatic pause with push notification when the daily decline exceeds 5%, and stopping the use of margin when account drawdown exceeds the worst backtest level.

Alerts are pushed to the phone via a Telegram bot, covering failure notifications, daily run summaries, market-open check summaries, and missed-run reminders. The entire scheduling relies on the operating system's built-in task scheduler, waking the script every 30 minutes, and the script decides based on New York time whether to execute the evening run or the morning stop-loss check—which means the computer must stay powered on and connected, otherwise that night's run is skipped.

For intraday trading, the course clearly states that the barrier rises steeply: it requires paid real-time market data (Alpaca's free tier covers only a single exchange and up to 30 symbols), a server that stays on year-round, higher cost assumptions, and more safety checks for data feed interruptions. The author's judgment is that the first build should start with daily bars.

Grouped attribution for reconciling live and backtest trades

Alpaca is a US brokerage for developers and algorithmic trading, offering commission-free stock and ETF trading APIs and known for its Paper Trading accounts, which allow users to test automated strategies with real market data at zero financial risk. Its API is simple and supports Python calls, making it a common live-trading integration layer for personal quant projects. The 9:28 to 19:00 New York time order rejection mentioned in the course is part of its pre-market and intraday order acceptance rules; scheduling orders after 19:00 for next-day open market-price fills aligns exactly with the daily strategy's matching assumption of "calculate signals after the close, execute at the next open," avoiding execution discrepancies between backtest and live trading.

Broker-side stop-loss orders are a key risk-control design in automated trading. Custody here means the stop-loss order is submitted directly and stored on the broker's servers, rather than relying on a local program to monitor prices and trigger. This means that even if the computer running the bot is shut down, disconnected, or the program crashes, the stop-loss order will still be executed by the broker when the price hits the threshold. The opposite is a "local stop-loss," which requires the program to keep running to take effect; once the process is interrupted, the risk exposure is fully exposed. For unattended trading systems, broker-side custody is the last physical line of defense against catastrophic losses.

Adapting: Strategies Decay, and the System Must Be Able to Refresh Itself

The final part of the course discusses long-term operations. Any short-term strategy will fail over time, so the system needs a preset retirement and replacement mechanism. Removal of short-term strategies has only three trigger conditions, all hard-coded before running: drawdown exceeds twice the worst drawdown in the test period (the "kill line"), the strategy is not selected during quarterly re-screening, or live trading frequency deviates from the test period by more than double or less than half.

A principle repeatedly emphasized is: poor performance in a single week or month is not grounds for removal. The system needs to distinguish normal fluctuation from strategy failure, and the judgment should be based on predefined thresholds, not after-the-fact emotions. The replacement process is equally constrained—candidate strategies must have passed all test hurdles, have a correlation of no more than 0.6 with the core and other running strategies, and every change must be written into a changelog.

Claude is scheduled to perform review tasks weekly, monthly, and quarterly: weekly reports summarizing run logs and live-versus-backtest deviations, monthly reports assessing each strategy's health status, and quarterly reports rerunning the screening process and proposing allocation changes. But all actions involving rule changes require human confirmation; the model can only fix bugs, not change rules.

The author's closing advice is to spend about ten minutes a week reading reports, checking phone alerts, and watching the distance of each strategy from its kill line. Most of the time there is indeed nothing to do—which is itself a sign that the system is running normally. For accounts with smaller capital, there is also the constraint of whole-share trading: a 20% position in a $2,000 account may not be enough to buy a single share of a high-priced ETF.

The core claim of the entire course can be summed up in one sentence: writing code is the easy part; what determines a system's success is how you build it and how rigorously you test the rules you give it.

#AI trading bot#Claude desktop app#ALPHA framework#zero code trading system#backtesting validation#Alpaca paper trading#risk control#overfitting
Share:

Related articles