Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Interpreting AI Logic: Explanations & Code Comments

Introduction

In the last lesson, you successfully prompted your AI assistant to generate the core logic for a moving average crossover strategy. You now have a standalone Python function, get_ma_crossover_signal, that represents the "brain" of your trading bot. While the code might look correct and even run, a critical question remains: can you trust it? In algorithmic trading, where real capital is at stake, blindly deploying AI-generated code is a significant risk.

This lesson focuses on the crucial step of verification. You will learn how to use your AI assistant not just as a code writer, but as a code reviewer and a Socratic partner. We will explore a series of prompting techniques to make the AI explain its own logic, add clarifying comments, and even critique its work to uncover potential bugs and edge cases. By the end of this lesson, you will have the skills to move from simply accepting AI-generated code to deeply understanding and validating it.

The Developer's Mindset: Understand What You Commit

A powerful principle in AI-assisted development is to never ship code you don't fully understand. An AI assistant can generate code with incredible speed, but it lacks the full context of your project and your risk tolerance. It's your responsibility as the developer to review, test, and ultimately own every line of code that goes into your trading bot.

The article "Agentic AI Prompting" captures this idea perfectly. It's a reminder that AI is a tool to amplify your abilities, not replace your critical thinking.

Agentic AI Prompting: Best Practices for Smarter Vibe Coding

This article offers excellent advice for working with AI agents. We'll focus on the core philosophy behind responsible AI-assisted coding.

Please read the section titled Understand What You Commit. The key takeaway is that you must always review, refactor, and test what the AI produces.

With that mindset, let's explore the practical prompting techniques you can use to achieve this understanding.

Level 1: Prompting for Explanations and Comments

The first step in verifying any piece of code is to ensure you understand what it's supposed to do and how it does it. You can ask your AI assistant to act as a guide, providing both high-level summaries and detailed, line-by-line walkthroughs.

The video "AI Coding 101" provides a great overview of these fundamental explanation prompts.

AI Coding 101: Ultimate Prompt Guide (37 tips)

This video from Volo Builds demonstrates several practical prompts for understanding code.

Watch these two short segments: First, see how to get a high-level summary by asking the AI what the current code does. Next, see how to get a more granular view by asking it to explain code line by line or add comments.

Now, apply these techniques to the get_ma_crossover_signal function you generated in the last lesson.

Your Task: Generate Explanations

Paste your get_ma_crossover_signal function into your AI assistant and use the following prompts.

Prompt 1: High-Level Explanation

"Explain the logic of this Python function in plain English. What is its purpose, what inputs does it expect, and what are the possible outputs?"

This prompt forces the AI to summarize its intent, which you can check against your original requirements.

Prompt 2: Add Code Comments

"Add detailed, line-by-line comments to this Python function. The comments should explain each step of the calculation, from calculating the SMAs to checking the crossover condition."

Your code should now be much more readable, looking something like this:

import pandas as pd

def get_ma_crossover_signal(df: pd.DataFrame) -> str:



    # Define the window periods for the short and long simple moving averages (SMAs).
    short_window = 20
    long_window = 50
    



    # Calculate the short-term SMA using the 'close' prices.
    df['SMA_short'] = df['close'].rolling(window=short_window).mean()



    # Calculate the long-term SMA using the 'close' prices.
    df['SMA_long'] = df['close'].rolling(window=long_window).mean()




    # Ensure there's enough data to have valid SMA values for the last two points.
    if len(df) < long_window + 1:
        return 'HOLD' # Not enough data to make a decision.




    # Get the most recent (last) row of data.
    last_row = df.iloc[-1]



    # Get the second-to-last row of data to compare against.
    prev_row = df.iloc[-2]




    # Check for a bullish crossover: short SMA was below or equal to long SMA, and now it's above.
    if prev_row['SMA_short'] <= prev_row['SMA_long'] and last_row['SMA_short'] > last_row['SMA_long']:
        return 'BUY'



    # Check for a bearish crossover: short SMA was above or equal to long SMA, and now it's below.
    elif prev_row['SMA_short'] >= prev_row['SMA_long'] and last_row['SMA_short'] < last_row['SMA_long']:
        return 'SELL'
    else:



        # If neither crossover condition is met, there is no trade signal.
        return 'HOLD'

Level 2: The AI as a Code Review Partner

Now that you understand the code's intent, it's time to actively look for flaws. You can instruct your AI assistant to adopt the persona of a senior developer and perform a critical code review. This can help you spot subtle bugs, performance issues, and edge cases that aren't immediately obvious.

The article "7 AI Prompts for Code Review" provides a powerful template for this.

7 AI Prompts for Code Review and Security Audits | Data Science Collective

This resource from the Data Science Collective offers structured prompts for using AI in a review capacity.

Read the section The Code Review Partner. Pay close attention to the structure of the prompt, which asks the AI to check for specific categories of issues and to "Be harsh."

Your Task: Perform an AI-Powered Code Review

Combine this idea with a "role prompt" to make the review even more effective. A role prompt, as shown in the "Essential AI prompts for developers" video, tells the AI what kind of expert it should be, which dramatically improves the quality of its response.

Use the following prompt with your get_ma_crossover_signal function.

Prompt 3: The Senior Developer Review

"Act as a senior Python developer specializing in financial algorithms. I want you to perform a harsh code review on the following function.

# [Paste your commented function here]

Specifically, check for:

  1. Logic Bugs: Are there any errors in the crossover detection logic?
  2. Edge Cases: What happens if the SMA values are exactly equal for a period? What if there are NaN values in the input data?
  3. Performance: Is this the most efficient way to do this in pandas? Could it be faster?
  4. Maintainability: Is the code clear? Could the variable names be better?

For each issue you find, please state its severity (Low, Medium, High), explain the problem, and suggest a specific code fix."

This prompt might reveal interesting insights. For example, the AI could point out that calculating the SMAs for the entire DataFrame on every function call is inefficient if you're running this on streaming data. It might suggest a way to update the SMAs incrementally. This is exactly the kind of expert feedback that helps you build a more robust system.

Level 3: Exploring Alternative Implementations

A final way to verify your understanding is to ask the AI for alternative approaches. Seeing how the same problem can be solved in different ways can reveal the trade-offs of your current implementation and deepen your understanding of the underlying libraries (like pandas).

The "pros and cons" prompt is perfect for this.

Essential AI prompts for developers

This video from the Visual Studio Code channel demonstrates how to ask the AI for different implementation options.

Watch the segment on the pros and cons prompt. The key is to ask for different ways to achieve a goal and the trade-offs of each.

Your Task: Ask for Alternatives

Let's apply this to our crossover logic.

Prompt 4: Pros and Cons of Alternatives

"The current function detects a crossover by comparing SMA_short and SMA_long at iloc[-1] and iloc[-2].

Can you show me one alternative method for detecting the crossover using pandas? For example, could we use the diff() and sign() functions?

Please provide the code for the alternative method and explain the pros and cons of it compared to the current row-by-row comparison."

This might lead the AI to generate a more "vectorized" solution, which can be more idiomatic and performant in pandas. By comparing the two, you're not just verifying the code; you're learning more advanced techniques.

Conclusion

In this lesson, you've transitioned from a passive user of AI-generated code to an active validator. You now have a repeatable process for ensuring the code you use is correct, robust, and well-understood.

Key Takeaways:

  • Trust, but Verify: Always treat AI-generated code as a draft that requires your expert review.
  • Prompt for Explanation: Use prompts like "Explain this code" and "Add comments" to ensure you understand the logic.
  • Embrace the AI Reviewer: Assign a role like "senior developer" and use a structured review prompt to find bugs, edge cases, and performance issues.
  • Explore Alternatives: Use "pros and cons" prompts to understand different implementation strategies and their trade-offs.

With a verified and well-understood strategy module in hand, you are now ready to integrate it into the larger application. In the next lesson, we will connect this strategy function with the data connector you built in Module 2, enabling your bot to generate trading signals based on real market data.

Can't find a good explanation? Sign up and we'll make it for you

Sign up