Register

Quanty · Agentic AI

Generate Python Trading Scripts From Your Rules

An indicator script should do exactly what its inputs and rules say. A starting template helps you get there faster, but its defaults are not a decision about what you should trade. This guide shows how to ask for a reviewable Python file, test it with fictional data, and check where it belongs in your workflow. Quanty Code is in testing (beta). QuantPower is software, not an adviser.

1. Begin with a small, observable output

Start with a result you can open and inspect without access to a live account. Ask for a table of values, an annotated CSV file, a short terminal report, or a chart built from a file on your machine. Pick one output for the first version. Asking for a broker connection, market scanning, a strategy and a dashboard in one sentence introduces four places where an error can hide. Beginning with one calculation makes those errors easier to locate.

Write down an example of the output before requesting code. A moving average report could contain a timestamp, the closing price, and the computed average, with a blank where the indicator is not ready. A summary based on entry and exit conditions could contain a timestamp and a plain label such as “condition met.” It does not need an order object, a broker identifier or fields for quantity. Keeping those extra fields out helps you see that the calculation is a separate task.

Here is a starting request: “Write a local Python script that reads a CSV with timestamp and close, calculates a five-bar simple moving average of the close, and writes one row per input row. Leave the average blank until five valid rows are available. Reject missing or repeated timestamps. Do not call a broker or send an order. Include a small fictional CSV and instructions.” The five bars are only a checkable example. Replace that value with the period you actually want the code to use.

To make the request easier to review, specify the format and not just the name of the file. “Print the results” could mean a seconds-long terminal log or a structured record you later import into another tool. Ask for column names, units and a destination that is easy to find. If the result belongs in a report, ask for a reproducible file rather than a screenshot. If you need a screen, build it after you can reproduce the rows it should show.

2. Describe the input file precisely

A candle file mixes data conventions that are easy to take for granted. A timestamp can refer to the opening or closing edge of a candle. A trading symbol can refer to a cash instrument, an index or a specific derivative contract. A price may be quoted in rupees or stored as integer paise. A column called “volume” could be trade volume or the cumulative value from a source that expects you to take differences. Paste a few fictional rows in the request and spell out the convention rather than expecting it to be guessed.

For a close-only calculation, do not require open, high, low and volume if they are not read. Every extra input becomes another possible source of error. By contrast, a range calculation cannot recover a candle's true high and low from only its closing price. A file can have rows for different symbols, but the request then needs rules for grouping. A ten-bar average across mixed instruments usually does not mean what someone wants. Ask for each symbol to have its own history, or reject mixed input if that is simpler.

The Python CSV documentation covers delimiters, quoting and dictionary rows. Reading a CSV row as a dictionary does not make contents valid numbers. The script still has to check empty values, leading spaces, non-finite prices and unexpected headers. Decide whether unexpected columns should be ignored or rejected. Ignoring a harmless extra column may be convenient; accepting the wrong required column silently is not.

Put the expected columns in the script's instructions and in the sample. Use fictional timestamps and prices in the examples. In a review handoff, share only the fields needed to reproduce the calculation. Do not paste broker credentials, client identifiers or full account exports into a prompt. If an example needs a real date to communicate a session boundary, a manually constructed miniature file is often enough. Its values can still be entirely made up.

3. Separate price interval, lookback and decision time

A fifteen-minute candle and a fifteen-period average are different ideas. The interval describes the amount of time represented by each row. The lookback describes how many rows a calculation uses. A twenty-period average on fifteen-minute candles is based on twenty of those candles; it is not a twenty-minute average. If the script imports an existing fifteen-minute file, say whether you want it to verify the timestamp spacing or simply trust the file interval after validation.

A rule may wait for each candle to close, or it may react while a candle is still changing. Those choices can give different results even with the same formula. A historical file only has the values it stores; it cannot recreate the sequence of unseen updates inside a bar. If the source is historical and decisions should use completed candles, say that clearly. Avoid a test that uses a completed high, low or close to pretend the decision had that information earlier.

Also decide what time the result is available. If your code detects a condition using the current bar's close, label it as known only at or after that close. A test that uses the same bar's earlier open as a fill is a different assumption and may use information that would not have been available. This guide's local examples log calculated values and rule conditions. They do not model executable prices or place orders.

Write these conventions in ordinary words beside the function. For example, “Timestamp is the start of a completed candle, so the calculated output is available at start time plus the interval, provided the file was actually produced after completion.” A source that already labels the end of a candle needs a different statement. The timezone and source convention belong in the instructions and in at least one test case.

4. Specify timestamps, order and gaps before calculating

When intervals matter, use timestamps that include a UTC offset or state how a timezone is assigned. A bare time such as 09:15 contains no date or zone and may produce an incorrect grouping when files from different computers are combined. Python's datetime documentation explains the distinction between timestamps with and without timezone information. Pick one internal representation and format results explicitly. Your file format documentation should make it possible to reproduce the same result on another machine.

Duplicate timestamps deserve an explicit rule. In a one-symbol file where one row represents one candle, two rows with the same timestamp might mean repeated download data, conflicting sources or a source correction. Silently counting both rows alters the lookback. If you choose to accept corrections, define how the replacement is identified and record what was removed. If the file is ordered by multiple symbols, checking duplicates within each symbol may be more useful than a blanket global rule.

Out-of-order timestamps are a separate check. Rejecting them makes problems visible and preserves the order in which the source gave you data. Sorting them before calculation can be useful for research fixtures, provided the script reports that it did so and separately checks duplicates. Neither choice tells you whether data that arrived late would have been available for a live decision. Avoid carrying a retrospective correction into a simulation without labeling that assumption.

A missing time slot is not the same as a row with a blank price. Decide whether the output should use available rows, stop and report the problem, or restart the rolling calculation after a gap. Carrying the last close forward creates an invented value. That may be an explicit research choice, but it is not a neutral repair. Include one fixture with a missing slot and another with a repeated slot so the chosen rule is visible in the test results.

5. Ask for a calculation you can check by hand

A simple moving average makes a useful first example because the arithmetic is visible. Suppose four completed fictional candles close at 100, 102, 104 and 106, and the example lookback is three bars. The first two rows have no three-bar value. On the third row the average is 102, from (100 + 102 + 104) divided by 3. On the fourth row the average is 104, from (102 + 104 + 106) divided by 3. These are made-up numbers, not historical results.

Ask the generated script to keep blank indicator values blank, rather than replacing them with zero. Zero may look like a real reading in a chart or summary. If you export a CSV, decide whether a blank field or an explicit string such as “not ready” will be easier for the next program to read. Whatever you choose should be documented. A missing close should follow its own input policy; it is different from an indicator that is not ready because the window is too short.

An exponential moving average needs another decision: how the first value is seeded. Two implementations can use the same period and multiplier and still differ near the start because one starts from the first observed price and another starts from a simple average of an initial window. Ask for the convention you want, or ask the script to state the one it uses. Compare more than one output row if you intend to match a chart.

Also say when to round values. Rounding every intermediate result can change later indicators, while rounding only the final display preserves the original arithmetic for comparisons. Keep numeric values as numbers until display or export, and record the unit. If another tester copies displayed values back into a calculation, they may not get the same precision. This is a data-handling decision, not a reason to increase the number of decimal places shown to a reader.

6. Keep the rule in a separate, named function

A generated file is easier to review if data loading, calculation and display are separate. A loader turns file records into validated rows; the calculation function takes those rows and returns results; the command-line entry point handles filenames, settings and printing. Separation lets you test the logic without a real file or a network request. It also lets you detect whether an unexpected result began in parsing, in the calculation or in formatting.

The name of the calculation should describe what it does. Names such as “simple_average” or “crossed_above” tell a reviewer where to look. A general name such as “trade” tells you little and may hide unrelated behaviour. Ask for no network calls in a calculation function. Results should depend on the data supplied and chosen settings, not on whatever happened to be returned from a remote service when the test ran.

If you need a crossing condition, define both the previous state and the current state. For example, decide whether a previous value equal to the threshold counts as at or below it. Decide what should happen on the first ready bar, when there may be no valid previous reading. A request that says “above” is not necessarily a request to signal every bar above the level. A rule that is true for ten consecutive bars and a rule that triggers once on crossing are different.

The output can simply record the condition met and the values that triggered it. There is no need to add a line that decides what quantity to trade. If you later use that output in another workflow, keep the calculation and the action separate. A computed condition remains a calculation even when it appears in a dashboard or a backtest report. It does not, by itself, verify order handling, capital limits or applicable constraints.

7. Match a template before adapting it

Quanty Code organizes starting files around specific tasks. A supported request may match a template and fill a field such as a period. Check that the generated file contains the exact number you requested in the executable setting. It is not enough that the response repeats the number in a heading. If it appears only in a comment or if it is read from a variable that gets overwritten later, ask why before relying on the result.

Make a one-variable comparison with the default. Save the default output, then change just the period and run the same data. Unless no row reaches the relevant lookback, the result should change in the direction the new settings imply. If the script returns exactly the same result, check whether the setting was passed to the function and whether the input file was actually read. If many unrelated lines are different, a reviewer should not treat it as a simple parameter change.

Not every change belongs to a prewritten template. Changing the price column might expose a field if the template was designed to choose a source. Switching from a closing price calculation to an intrabar process is a different kind of change. Requests that need new logic deserve separate tests. Do not describe an adapted file as the same tested template merely because some of its lines look identical.

Before reusing a template, save its instructions. Note whether it expects a plain CSV or needs an optional package. Note which version of Python you used, then run the test from the folder that holds the example. If the sample path is relative, running the command from a different directory can break a working script. The handoff needs a runnable command, not just a line in a chat that says “run Python.”

8. Pick tests that catch mistakes, not just examples that pass

The normal case checks whether a clean file returns the expected sequence. Add the smallest case that actually produces an indicator value. Also add a file with too little data, an empty file and a file with a malformed number. When the script is meant to reject a bad file, make the test check for a clear error rather than accepting any failure as success. Ideally it tells the reader which row or field needs attention without exposing the entire file in the error message.

Try a case with more than one group if the file contains multiple symbols. A test with visibly different prices for each group quickly reveals whether the calculation accidentally mixes them. Add a timestamp exactly at a boundary, such as a new session or a new hour, if grouping is part of the request. One clearly chosen bar is more useful than a large fixture that has no known expected output near the boundary.

Check that testing does not require external services. A test can use a local CSV fixture, a fabricated response or a file written in a temporary directory. If a test fails when your internet connection is turned off, find out what it tried to reach. A local parser and calculation should not need an API key. The unittest documentation explains test discovery, individual test cases and assertions.

A passing test is useful evidence of a specific behaviour under its inputs. It does not guarantee the script will handle every market condition or provider response, and it does not evaluate whether anyone should trade. Include the failing scenario when you report a bug. “The output looks wrong” is hard to investigate; “on the fourth fictional candle, a period of three produced 106 instead of 104” gives a reviewer something to reproduce.

9. Review the command and results as if you were a second user

Choose a clear command such as a Python file followed by an input filename and a period. Ask for a help line listing required columns and accepted units. The command should fail clearly if the file is missing, if the period is not valid or if the output would overwrite an input file. Avoid a script that accepts an invalid setting and changes it to a default without telling you. The result may be syntactically valid but answer a different question from the one you asked.

A useful output file includes the time and value fields you agreed on. Decide if each input row should produce one output row even when the indicator is blank. Comparing row counts can reveal skipped lines. Also compare the first and last timestamps with the original file. A script should not quietly remove the most recent row because its price is invalid while still reporting a successful calculation. You need enough information to decide whether the file is incomplete.

Walk through the review on a clean folder where no old output files exist. Run the command on the supplied sample. Open the result and identify one number you can recompute. Then run with another input, or deliberately change the period. Copy the command into your notes so another person can reproduce the same run. If a command assumes a working directory or environment variable, write down that prerequisite too.

When reporting results, distinguish “works in my sample” from “checked against the source we plan to use.” A printout is not evidence that the row times were correct unless you checked them. A figure showing an expected pattern is not evidence a timestamp boundary was respected unless you can find the underlying values. If you changed the script after running tests, repeat the meaningful checks on the file you actually intend to keep.

10. Introduce a broker data adapter only after local checks

A local candle script can be written without a broker connection. The data part can be replaced later with a read-only adapter that produces the same rows. Keep the adapter in a separate file or function so it is easy to tell which lines request data and which lines perform the calculation. Follow your own broker's documentation for supported instruments, candle intervals, account permissions and error responses. Ask for a local fixture that has the same shape so your tests still do not need credentials.

Do not paste a broker key into prompts, commit it into a template, or include it in a screenshot. Keep credentials in an appropriate private environment and give them only the permissions needed for the task. Inspect any example that writes account responses to disk or prints them to logs. A historical-candle script does not need to record a user's account profile. Treat automatic error reporting as a possible place where personal information could be copied unexpectedly.

A broker response may contain a rate-limit message, a partial page, an invalid timestamp or no data for the requested interval. The adapter should distinguish those cases before passing rows to the calculation. An empty result can be a valid response in one situation and a signal that the wrong instrument was requested in another. Log a useful reason without printing a credential or private account data. Do not substitute fake candles for a failed request and then label the output real.

Read-only is a meaningful boundary. The example should not place, modify or cancel an order. If you see paths or methods unrelated to retrieving data, ask why they are there. Keep any later deployment or trading decision out of this code review. A good local script can explain a calculation and return a reproducible file without making a claim about market outcomes or handling a real order.

11. Avoid drawing conclusions the sample cannot support

A small example demonstrates the interface and the arithmetic. It cannot tell you how a rule behaves across market regimes, how a broker would fill an order or what an investor should do. Do not attach a made-up performance figure to a template. If you later use a longer history, write down the source, the period, what the calculation sees at each point, and which assumptions differ from a live setup. The same results should be recoverable from those choices.

A backtest is a different task from calculating an indicator. If you later simulate a trade, state what price is available, when the signal becomes known, and how fees, delays and missing data are treated. A clean indicator output does not validate those assumptions. Conversely, an unexplained backtest result is harder to investigate if the underlying condition was not tested separately. Keep result files and tests tied to the exact version of the logic under review.

A change in results may be legitimate if an input changed. Check whether two runs used different price sources, candle definitions, timezones, missing-data rules, seeds or rounding. Compare one instrument and a short date range before escalating to a whole history. If one row differs, identify the first point of disagreement and work forward. A repeatable explanation is more useful than a large summary whose inputs no one can inspect.

Software should not choose a trade for you. The relevant decision here is whether a file does the calculation you specified, behaves clearly when inputs are invalid and is safe to inspect. A count of successes in a toy sample is not a win rate. A small series selected to force a crossing is not a market forecast. Use tests to understand the code, not to turn fictional data into a claim about returns.

12. Hand off the exact version and next checks

Give a reviewer the prompt, the script, its settings and a small fictional input with expected output. Include the command and the Python version you used. Add a note saying whether the code was reused from an existing template, parameterized, adapted or written for a new case. A simple change log can distinguish a file that sets a period from one that also changes how the price series is filtered.

Before distributing the files, verify the copy that will actually be sent. Open the archive or downloaded folder, check its filenames, and rerun the supplied command on those files. Sharing a test that passed on a working directory is not the same as testing the download. Keep the original sample and a separately labeled copy of any modified input. A missing README, a path pointing at your own machine, or a renamed CSV can turn an otherwise valid example into a confusing handoff.

If you give a colleague an issue to investigate, include the first expected result, the first result that differs, and the smallest input that shows the problem. Ask them to check that case before expanding into a larger data set. If they correct a rule, preserve a test for it so it cannot disappear in a later edit. When you change both data and logic, use staged comparisons so the cause of a result change can be identified.

Begin with one local calculation, one sample file and one deliberate failure case. Make the settings visible. Keep data fetching separate, and leave orders out of a read-only script. Once another person can reproduce the calculation, decide whether you need a chart, a longer test, a read-only adapter or only the simple file already in hand. QuantPower is software, not an adviser. Use example code to understand and test your own rules, not as a trading recommendation.

A practical release note

A short release note can stop two near-identical files from being confused. Record the input headers, whether timestamps identify the start or end of completed bars, the chosen lookback, and what happens when the file is empty. State what changed since the previous copy. Attach the example that reproduces the first ready value. If the code stops on duplicates, neither the note nor the test should suggest that duplicate correction is automatic.

For a shared spreadsheet or dashboard, note the shape of the output independently of the script. Someone may expect one row per candle, even when the average is blank. Another reader may treat the latest row as an instruction. Use column names that make the result's meaning explicit, such as “condition met” or “calculated value,” rather than a label that suggests an order. Put sample files in a separate folder and name them as examples. In the next review, change only one setting and save both commands so the difference is easy to reproduce.

Explore Quanty Code