Recommended resources
The freely available resources this lesson will direct you to.
Introduction
In our previous lessons, you've successfully established the foundational pieces of your trading bot: you've decomposed the project, learned to craft detailed prompts, and built a data connector by generating and debugging API code with your AI assistant. You now have a reliable way to get the market data you need.
This lesson moves to the next logical step: building the "brain" of your bot. We will focus on generating the core trading strategy logic. Your goal is to write a focused prompt that instructs your AI assistant to create a Python function for a classic moving average crossover strategy. This is where a trading idea transforms into executable code that can make decisions. Mastering this will allow you to rapidly prototype and test any trading strategy you can imagine.
The Engineering Mindset: From Monolith to Module
It's tempting to ask your AI assistant, "Build me a complete moving average trading bot." As we've discussed, this "do-it-all" approach often leads to a tangled, unmanageable block of code where data fetching, strategy logic, and order execution are all mixed together. This is a house of cards.
Instead, we will continue to apply a core software engineering principle: Divide and Conquer. Our goal is not to generate a whole script, but to create a single, focused, and testable module for the strategy logic.
Software Engineering Fundamentals for Powerful AI Prompts
The article from Mad Devs provides an excellent rationale for breaking down complex tasks. It contrasts the "do-it-all" prompt with a step-by-step strategy.
Please read the section titled Break it down. The key insight here is that a "chain of simple prompts beats the 'one perfect prompt'." We are applying this by creating our strategy logic as an independent component, just as the article describes building a database layer before the API layer.
By isolating the strategy logic, we gain several advantages:
- Clarity: The function does one thing and does it well.
- Testability: We can easily verify if the logic is correct without needing a live data feed or a broker connection.
- Flexibility: The same logic can be reused with different data sources or execution engines.
The video below demonstrates what often happens with a less specific prompt. Notice how the AI immediately generates a complete script using the backtrader library. While useful for quick backtesting, this merges all components together, which is what we want to avoid in our modular design.
This video from QuantTrader shows a user asking ChatGPT for a trading strategy.
Watch from the initial prompt to see how the AI produces a full script that includes data fetching, strategy definition, and execution all in one. Our goal today is to prompt for only the strategy logic part.
Anatomy of a Focused Strategy Prompt
To get a clean, modular function from your AI, you need to provide a precise specification. A vague request leads to a vague result. A focused prompt acts as a clear technical requirement document.
The "Claude 4.1 for Trading" guide gives an excellent checklist of what to include when prompting for trading algorithms. We will adapt its principles for our specific goal.
Claude 4.1 for Trading: 2025 Algo-Trading Copilot Guide
This guide offers practical advice on using AI for trading tasks. The Q&A section contains a goldmine of information on crafting effective prompts.
Please read the answers to these two questions: What are safe prompts? This provides a list of key elements to specify. Which starter strategies work well? This confirms that moving-average crossovers are a great starting point.
Based on these principles, a high-quality prompt for generating strategy logic should explicitly define the following:
- Objective: What is the high-level goal? (e.g., "Create a Python function to determine trading signals based on a moving average crossover.")
- Inputs (The Data Contract): What data does the function need? Be specific about the format. (e.g., "The function must accept a pandas DataFrame containing historical price data. This DataFrame will have columns for 'open', 'high', 'low', and 'close'.")
- Core Logic (The Rules): How are decisions made? Detail the calculations and conditions. (e.g., "Calculate a 20-period simple moving average (SMA) and a 50-period SMA using the 'close' prices.")
- Outputs (The Signals): What should the function return? Define the possible outcomes clearly. (e.g., "The function should return one of three strings: 'BUY', 'SELL', or 'HOLD'. A 'BUY' signal is generated when the short-period SMA crosses above the long-period SMA. A 'SELL' signal is generated when it crosses below.")
- Constraints: What libraries or techniques should be used or avoided? (e.g., "Use only the
pandaslibrary. Do not include any code for data fetching, plotting, or backtesting. The function should be pure and self-contained.")
Your Task: Prompting for the Moving Average Crossover Logic
Now, let's put this all together. Your task is to use your AI assistant (like VS Code Copilot Chat, ChatGPT, or Claude) to generate the Python function for your trading strategy. You will construct a single, detailed prompt based on the anatomy we just discussed.
Here is a template you can adapt. This prompt is carefully constructed to give you a clean, modular, and correct function.
Prompt for your AI Assistant:
Objective: Write a standalone Python function named
get_ma_crossover_signal. This function will implement a simple moving average (SMA) crossover trading strategy.Inputs:
The function must accept a single argument: a pandas DataFrame. This DataFrame represents historical price data and is guaranteed to have a column named 'close'.Logic:
- Inside the function, calculate two SMAs from the 'close' price column:
- A short-term SMA with a 20-period window.
- A long-term SMA with a 50-period window.
- The function should then check for a crossover event using the two most recent data points (the last and second-to-last rows of the DataFrame).
Outputs (Return Value):
- Return the string 'BUY' if the short-term SMA has just crossed above the long-term SMA. (i.e., on the previous tick it was below, and on the current tick it is above).
- Return the string 'SELL' if the short-term SMA has just crossed below the long-term SMA. (i.e., on the previous tick it was above, and on the current tick it is below).
- In all other cases (no crossover), return the string 'HOLD'.
Constraints:
- Use only the
pandaslibrary for all calculations.- The function should be self-contained. Do not include any code for fetching data, printing output, or plotting charts.
Why this prompt works:
- It names the function (
get_ma_crossover_signal), creating a predictable deliverable. - It defines a clear "data contract" for the input DataFrame.
- It specifies the exact parameters for the SMAs (20 and 50 periods).
- It explicitly defines the crossover logic ("just crossed"), which prevents the AI from generating signals on every tick where the short SMA is simply above the long one.
- It enforces modularity by forbidding data fetching or plotting code.
After you run this prompt and get the code, your function should look something like this (the exact implementation may vary slightly):
import pandas as pd
def get_ma_crossover_signal(df: pd.DataFrame) -> str:
# Calculate SMAs
short_window = 20
long_window = 50
df['SMA_short'] = df['close'].rolling(window=short_window).mean()
df['SMA_long'] = df['close'].rolling(window=long_window).mean()
# Check for enough data
if len(df) < long_window + 1:
return 'HOLD'
# Get the last two data points
last_row = df.iloc[-1]
prev_row = df.iloc[-2]
# Check for crossover conditions
if prev_row['SMA_short'] <= prev_row['SMA_long'] and last_row['SMA_short'] > last_row['SMA_long']:
return 'BUY'
elif prev_row['SMA_short'] >= prev_row['SMA_long'] and last_row['SMA_short'] < last_row['SMA_long']:
return 'SELL'
else:
return 'HOLD'
If your AI's first attempt isn't quite right, remember the techniques from our earlier lessons. You can use follow-up prompts to refine it. For instance, if the AI gives you a very complex implementation, you could ask, "Can you simplify this logic to only compare the last two time steps?"
Conclusion
You have now taken a crucial step from being a consumer of data to a producer of trading decisions. By crafting a focused, detailed prompt, you have generated the core logic of your trading bot as a clean, independent module. This disciplined, engineering-led approach is what separates flimsy prototypes from robust, scalable trading systems.
Key Takeaways:
- Prompt for Modules, Not Monoliths: Always aim to generate small, self-contained components. Use the "Divide and Conquer" principle.
- A Good Prompt is a Specification: To get precise code, you must provide a precise specification detailing the objective, inputs, logic, outputs, and constraints.
- Moving Average Crossover Logic: You now have the code for a classic trading strategy that looks for a 'BUY' signal when a short-term trend overtakes a long-term trend, and a 'SELL' signal for the reverse.
In the next lesson, we'll address a critical question: the AI gave us code, but how do we know it's correct? We will explore how to prompt your AI assistant to explain its own code and generate tests to verify that the strategy logic works exactly as intended.