Use Python 3.10 or later and a text editor. Start with Python basics for traders if you are new to functions and tests. The earlier Python trading indicators course explains aligned series and warm-up periods. Read Arth Script for the separate product overview. Here you will write one short example against a stated contract and review the Python port, not ask a tool to rewrite a large rule without a check.
Work in three stages: lesson, exercise and answer check. Quanty exercise review (beta) can help interpret one mismatched row if you share only the contract and synthetic fixture. The comparison does not need a connected account, passwords, access tokens or any actual trade data. Code and source examples are for learning, not a launch decision.
Lesson 1: Translate the rule before translating the syntax
Begin with a short description: “For each completed synthetic close, calculate a simple mean of the latest two valid contiguous closes and a simple mean of the latest three. Report whether the first becomes strictly greater than the second after being at or below it on the preceding bar.” That sentence frames the example as a data transformation. The period choices are invented for short hand calculations and not recommended settings.
List the named intermediate values and outputs: fast mean, slow mean and a crossing flag. They must all be aligned by bar. If either mean has not warmed up, the crossing comparison should not claim the threshold was crossed. If a missing value resets the window, the program needs enough consecutive inputs to build the mean again. A port that carries the last average through a missing bar has a different rule even if its resulting chart looks smooth.
Write one row of the expected receipt for each bar before using any conversion tool. Include the input close, both means, prior relation and current relation. Treat the relation as undefined if either value is missing. That gives you a clear reason for a false crossing flag. There are several ordinary ways to display missing values; the port must preserve the underlying condition regardless of how the display presents a dash or leaves a cell empty.
For the exercise, give the rule to a friend without showing code. Ask them whether a move from equality to above is included and whether a move from below to equality is enough. The first is included because the preceding relation permits equality and the current one is strictly greater. The second is not because the current relation fails the strict comparison. Those cases catch minor-looking wording changes that can alter an entire result series.
Answer check. Ask Quanty to list the assumptions missing from the sentence “mark when two averages cross.” A useful response should mention the two periods, the sample or indexing, whether missing values reset state, which crossing direction counts and how equality is treated. Do not accept a new trading rule as the answer. You are trying to make your own rule precise.
Lesson 2: Read a short Arth Script example in terms of that contract
This lesson uses the v2 grammar and technical-analysis names. The following is a classroom indicator, not an order or alert. The variables refer to the chart's close field and the three plots provide visible series. The crossing plot converts a Boolean to a zero or one solely to display it numerically. That conversion does not give the number a trade meaning.
//@arth 2
indicator("Classroom parity", overlay = false)
fast = ta.sma(close, 2)
slow = ta.sma(close, 3)
crossed = ta.crossover(fast, slow)
plot(fast, "Fast mean")
plot(slow, "Slow mean")
plot(crossed ? 1 : 0, "Cross marker")Compare the vocabulary with the QuantPower Arth Script overview. This example is checked against the separate v2 compiler and simulator used for this exercise. Keep the language version and intended execution environment in your note. A short formula may use a different surface syntax from a versioned script. Similar words such as “SMA” across environments do not prove the same parser or state behaviour. Here the names and examples refer to the v2 source documented alongside the engine.
Each mean is evaluated once per row in this example. A stateful call maintains its own running state; calling it under a different condition or on a different sequence could be a different program. Rather than moving the calculations around while translating, leave the source version unchanged and compare the output it is meant to produce. In a longer script you would inventory where each indicator is evaluated and preserve the order of observations it sees.
For the exercise, explain what each line contributes without naming a buy or sell action. Then identify a change that affects presentation only, such as renaming a plot, and a change that affects values, such as changing a period. If you turn off a plot but keep its calculation, that also has a different effect from removing the calculation altogether. Record the distinction before you judge a port by its visual appearance.
Answer check. Ask which part of the Python result should align with the numeric plot. The expected answer distinguishes the raw Boolean field from the plot's zero-or-one presentation. You can compare Boolean fields directly, or convert to the same numeric convention at the final display step, but do not put a new decision in that conversion.
Lesson 3: Preserve missing values and recovery rows
The first complete fast mean arrives after two consecutive closes. The first complete slow mean arrives after three. The crossing comparison additionally needs a preceding row with both defined means. When the slow mean first appears, the prior slow value is missing, so there is no supported comparison with it. The result may be false even when the current fast mean is greater. That is not necessarily a defect; it follows from the rule's dependence on the previous relation.
The v2 indicator implementation checked for this course restarts its average state when it sees a nonfinite input and returns no valid crossing if either side or either preceding value is unavailable. The Python port uses None for missing input and output, and refuses other nonfinite values. This is an explicit mapping: the exercise uses None to represent a deliberate missing observation, not an invalid text value silently converted to one.
Use these closes: 8, 8, 8, 12, 4, missing, 8, 8, 12, 18. At bar two the means agree at 8 and the preceding slow value is missing, so the crossing flag is false. At bar three the fast mean rises to 10, the slow mean to a little over 9 and the flag is true because the preceding means were equal. At bar four both means are again 8 and the flag is false. The missing bar clears both states. After recovery, the first time both means are defined again can still produce a false crossing because the previous slow value is not yet defined.
Make a table with one line per close, including the missing bar. Do not remove that line to make the input shorter. Removing a row entirely would alter adjacency and could join values across a gap; keeping an explicit missing bar demonstrates the intended restart. The source data course separately checks for gaps and invalid history before using it. This lesson intentionally passes one declared missing marker to demonstrate how the arithmetic behaves.
For the exercise, extend the written table with a second gap after a single recovered input. Predict which periods would restart and which outputs could be defined between the two gaps. Run the same check with the gap at the very beginning. These are separate boundary conditions even if the final valid values happen to match.
Answer check. Show the reviewer two records: the first after recovery with a fast value and no slow value, and the first with both values. Ask which condition is still missing before a crossing can be considered. Require the answer to identify a bar and field, not merely say “warm-up.”
Lesson 4: Give the Python program one job per function
The classroom port uses a rolling window with a running sum so the operations happen in the same order as the pinned simple-average example. Floating-point arithmetic is not decimal arithmetic; the program uses ordinary Python float on a small finite fixture to align with the numeric representation used by the source. It does not assert bit-for-bit equivalence for every runtime or possible input. Validate outputs by timestamp and by a written comparison rule.
Save this as arth_parity.py:
from dataclasses import dataclass
import math
@dataclass(frozen=True)
class Row:
index: int
fast: float | None
slow: float | None
crossed: bool
def sma_restart(values: list[float | None], length: int) -> list[float | None]:
if type(length) is not int or length <= 0:
raise ValueError("length must be a positive integer")
ring = [0.0] * length
position = 0
count = 0
total = 0.0
output = []
for value in values:
previous = ring[position]
ring[position] = 0.0 if value is None else value
position = (position + 1) % length
if value is None:
count = 0
total = 0.0
output.append(None)
continue
if not math.isfinite(value):
raise ValueError("input must be finite or an explicit missing marker")
count += 1
total += value
if count < length:
output.append(None)
continue
if count > length:
total -= previous
output.append(total / length)
return output
def crossed_over(
fast: float | None, slow: float | None,
prior_fast: float | None, prior_slow: float | None,
) -> bool:
if fast is None or slow is None or prior_fast is None or prior_slow is None:
return False
return fast > slow and prior_fast <= prior_slow
def evaluate(values: list[float | None]) -> list[Row]:
fast = sma_restart(values, 2)
slow = sma_restart(values, 3)
output = []
before_fast = before_slow = None
for index, (f, s) in enumerate(zip(fast, slow)):
output.append(Row(index, f, s, crossed_over(f, s, before_fast, before_slow)))
before_fast, before_slow = f, s
return output
if __name__ == "__main__":
data = [8.0, 8.0, 8.0, 12.0, 4.0, None, 8.0, 8.0, 12.0, 18.0]
for row in evaluate(data):
print(row.index, row.fast, row.slow, int(row.crossed), sep=" | ")Following one rolling buffer row by row is useful. While the window is filling, the code builds a total without subtracting a value. When the window is already full, it adds the incoming close and subtracts the outgoing close. After a gap it does not need to trust a number left in an old slot: there are at least length newly visited slots before the next complete result, and subtraction resumes only on the following observation. Check this reasoning on a two-slot ring of your own before trusting a larger one.
The conditional uses strict comparison for the current values and inclusive comparison for the previous values. Do not apply a display rounding operation before using them in the Boolean comparison. Doing so could turn two different close averages into equal displayed numbers and manufacture or suppress a flag. The aim is to port the stated condition, not make plotted labels agree at a glance.
For the exercise, adjust just the fixture so there is an interval where the fast value is equal to the slow value following a lower one. Predict why that interval is not a crossing. Then add a later interval with a strictly greater result and compare again. Do not change the condition if the existing example does not happen to produce the case you wanted; use a small direct unit test to isolate the relation.
Answer check. Ask which line enforces the prior relation and which line prevents a missing observation from being counted as zero. A reviewer should identify two different concerns. If a response suggests replacing every missing number with zero, rerun the explicit gap fixture to see why the proposed port no longer matches the contract.
Lesson 5: Verify numeric outputs and Boolean outputs differently
A provisional parity receipt can compare numeric outputs with a small explicit tolerance when different runtimes use slightly different representations. Agree on that tolerance before seeing the results. Keep undefined positions and exact Boolean outputs separate. A numeric tolerance should never convert an undefined value into zero or turn a false flag into true. Those are semantic changes, not differences in display precision.
The included tests use exact small values when possible and an approximate comparison for a repeating fractional result. Save the second example as test_arth_parity.py and run python -m unittest -v:
import unittest
from arth_parity import crossed_over, evaluate, sma_restart
class ParityTests(unittest.TestCase):
def test_warm_up_and_equality_to_above(self):
rows = evaluate([8.0, 8.0, 8.0, 12.0, 4.0])
self.assertIsNone(rows[0].fast)
self.assertIsNone(rows[1].slow)
self.assertEqual((rows[2].fast, rows[2].slow, rows[2].crossed), (8.0, 8.0, False))
self.assertEqual(rows[3].fast, 10.0)
self.assertAlmostEqual(rows[3].slow, 28 / 3, places=12)
self.assertTrue(rows[3].crossed)
self.assertFalse(rows[4].crossed)
def test_gap_restarts_both_windows_and_comparison(self):
rows = evaluate([8.0, 8.0, 8.0, None, 8.0, 8.0, 12.0, 18.0])
self.assertIsNone(rows[3].fast)
self.assertIsNone(rows[4].fast)
self.assertIsNone(rows[5].slow)
self.assertEqual(rows[6].fast, 10.0)
self.assertAlmostEqual(rows[6].slow, 28 / 3, places=12)
self.assertFalse(rows[6].crossed)
self.assertFalse(rows[7].crossed)
def test_cross_boundary_is_strict_now(self):
self.assertTrue(crossed_over(3.0, 2.0, 1.0, 1.0))
self.assertFalse(crossed_over(2.0, 2.0, 0.5, 1.0))
self.assertFalse(crossed_over(3.0, 2.0, None, 1.0))
def test_prefix_has_no_later_influence(self):
p = [8.0, 8.0, 8.0, 12.0]
self.assertEqual(evaluate(p), evaluate(p + [4.0, None])[:len(p)])
def test_one_slot_window_recovers_after_gap(self):
self.assertEqual(sma_restart([2.0, None, 3.0], 1), [2.0, None, 3.0])
def test_nonfinite_is_not_a_silent_gap(self):
with self.assertRaisesRegex(ValueError, "explicit missing marker"):
sma_restart([float("nan")], 2)Now compare a future observation's effect on an earlier row. The prefix check does not prove the two environments use the same source data, yet it verifies that this implementation did not use the added observations to calculate prior rows. The definition checks independently recognise the correct mean and relation. Having both prevents one test from being asked to answer two unrelated questions.
Answer check. Give Quanty exact expected outcomes for both missing and defined rows. If the model suggests a broader tolerance, ask what specific representation difference it is intended to absorb. Do not widen the tolerance just to turn a surprising comparison green.
Lesson 6: Prepare your comparison in the same runtime context
A pasted indicator name is not enough to reproduce a result. Record the language version, input period, time frame, timezone and whether the comparison used completed bars. Make both sides use the same synthetic fixture where possible. For separately sourced histories, document which bars are actually equal rather than assuming identical labels mean equal values. A mismatch in the input closes is not evidence that the Python algorithm is wrong.
Test exactly one row at which a mismatch appears and the preceding row. If the current numeric values match but the flag differs, the earlier relation can explain it. If the previous relation matches but the numeric means differ, compare the windows and warm-up assumptions. A report with only a final Boolean column cannot show which of these categories failed. Include the intermediate values you chose when you translated the rule.
When using a real application workspace later, run only the documented chart indicator in a permitted context. The exercise does not propose importing account records, querying a production API or activating an algo. The Python files are a local implementation of a teaching rule, not a bridge between services. Only compare recorded values you are authorised to use and keep them out of external debugging conversations if they contain account information.
Parity drill: Separate chart rendering from the actual numeric series
Place two copies of your table side by side. In one, print the fast mean to two places. In the other, use enough precision to expose the original result. When a row looks identical at two display places but the values differ, write both raw values in the note and calculate the difference. A comparison of screenshots cannot settle that mismatch because the chart may not display enough digits. Export or inspect plain values from a permitted workspace rather than estimating points from a line.
Next compare missing positions independently. A series title or a chart marker may be visible even where the corresponding numeric series is absent. An indicator that draws zero for a Boolean flag can still have undefined numeric inputs at that row. Your receipt should record three individual columns, each with its own interpretation. Do not make the empty fast or slow cell into a zero simply because the Boolean plot chose zero for false. That would confuse a missing calculation with a valid comparison result.
Sketch the same fixture with the crossing marker hidden. The two numeric means should remain unchanged. If hiding the plot is implemented by hiding an entire script or changing evaluation conditions, check that the resulting program still runs the stateful calls when needed. The isolated example intentionally evaluates each call on every bar. If you later compare a conditional version, that is a different schedule and needs its own trace. Use a short before-and-after sample to show which parts of the schedule changed.
Write a report for one side that uses round labels and another that uses raw outputs. Include the intended common input, time/index convention, first supported index and raw Boolean value. Record the display precision separately. This keeps the evidence useful to someone who cannot see either chart. If you cannot obtain the raw values from a supported interface, say that the comparison is limited to display behaviour instead of implying numerical parity.
Answer check. Ask the review feature to produce separate acceptance criteria for a display check and an arithmetic check. A display check can consider the chart label or legend. An arithmetic check must reproduce definedness, value and timestamp or index. Add a third criterion for the expression result if the rule has a Boolean flag. These independent observations let you localise a discrepancy.
Parity drill: Compare suite design before changing indicator periods
Use three categories of fixtures. First, choose a hand-checkable set with a near equality and one exact equality. This challenges the strict-current and inclusive-previous comparison at different points. Second, choose a gap case long enough to require a new warm-up. This challenges the state reset. Third, choose a stable nondisruptive series, such as a constant repeated value, and verify that every defined mean equals that value and no crossing appears.
The constant fixture is not sufficient on its own because it cannot easily distinguish a wrong window from a correct one. Its purpose is an invariant a broader implementation should preserve. In contrast, a varied fixture makes the changing contribution of each close visible. Keep both tests. Replacing a varied test with several constant tests may increase the count without increasing the evidence.
Now write a hypothetical requirement to expose the two periods as inputs. Do not change the fixed classroom example yet. First decide whether the values must be integers, what bounds apply in the particular scripting environment, and what it means if the two values are equal. A comparison between two moving averages with the same period is normally a comparison of two equal series under matching implementation, so there is no strict crossing in this setup. If you are using another tool or seed convention, confirm the premise directly rather than treating this as a universal statement.
When you adapt the examples later, change only one period in the source and the port. Record the first defined position for each series before running. Then identify the first position at which both current and previous values are defined for the flag. The exact input list might not generate a true flag after the change, so create a fixture with visible movement that tests the desired boundary. Do not keep changing the levels until you happen to get a preferred chart. Your job is to confirm the documented evaluation on chosen cases, not to extract an indication from arbitrary settings.
A second input test can expose a mismatch between numeric and configuration rules. Passing a noninteger period may be refused by an input component on one side and refused by a function guard on the other. These can be corresponding results even if the visible error wording differs. If one environment silently rounds while the other rejects the value, determine which behaviour your contract requires before adopting a conversion. Do not change just one side and call the difference an improvement without documenting the new specification.
Answer check. Ask for a fixture that proves a period change was propagated to both means rather than just relabelled in a header. The test should compare the first supported position or a hand-checked sequence. Keep the old-period fixture too so the prior example remains reproducible.
Parity drill: Identify which part of a long script is safe to translate first
A substantial chart script can combine source inputs, configuration, indicator computations, colour formatting and action labels. A single request to translate it is likely to mix these concerns. Start with a section that has a small explicit input and output. Name the helper it depends on, and write a local sample that shows leading undefined values and one nontrivial decision. Do not ask the conversion tool to infer a rule from a plot alone.
List the boundaries that separate a paper reproduction from use in a real system. A port might calculate the same number and still run at a different frequency. It might preserve a condition but display it before the bar is actually completed. It might reproduce an indicator but omit an action guard that belongs elsewhere. For this course the contract excludes all actions and compares values at completed synthetic rows. Do not label the output as converted order logic or a complete trading system.
The matching Python implementation rejects numeric infinity and NaN passed directly, while the fixture represents a deliberate missing observation with None. The source engine uses a nonfinite marker internally to initialise or reset. This is not an invitation to take any invalid number from a file and call it a clean gap. At the data boundary, decide whether a field is defective, missing under documented rules or an impossible value. Only the deliberate gap is passed to this exercise as missing. If the two implementations are fed different interpretations of the same raw field, a downstream comparison cannot resolve that upstream decision.
Make a versioned note naming the source fragment, its language version and the exact small fixture. Record how missing input is mapped, what numeric tolerance you use, and whether the helper is expected to receive one value per complete row. Run the source and destination from the same frozen input. If the first mismatch appears only after adding a gap, reduce the fixture until you can identify the first row whose state differed. This provides much more useful evidence than a wide screenshot of an entire history.
Finally, compare the intended meaning with what the application actually offers. This lesson uses a pinned v2 compiler and simulator independently of the deployed chart interface. It does not assert that every installed chart, formula editor or account has that v2 runtime enabled. The separate product overview describes the public Arth Script experience; verify the actual runtime where you intend to work. Keep the report honest by labelling environment coverage rather than inferring deployed availability from a repository test.
Parity drill: Decide what evidence a reviewer can safely receive
Create a one-page diagnostic sample with made-up closes and a precise comparison. The minimum useful example contains the rule version, two previous and current pairs, the Boolean decisions and the first row where output definitions disagree. Do not include application tokens, private chart links or data that an account holder has not approved for sharing. The same mathematics can be discussed using a fictional sequence. Reducing the example protects data and usually makes the technical review sharper.
Suppose one reviewer asks whether a point should be false or absent. Give them three separate outputs rather than a single “looks wrong” comment. The class contract can say that a missing average is absent in a numeric column, while the crossing flag is false because an unavailable comparison cannot be supported. That is a clearer requirement than merging both ideas into an empty cell. Preserve the distinction in your export or your comparison code.
Write acceptance in two sentences. First: “The local port matches the pinned source simulator for these fixtures, including the warm-up and gap case.” Second: “No hosted chart, real account or execution behaviour is covered.” This form separates a verified observation from the next thing a reviewer might want to test. If you later verify an on-device chart, identify the actual build and data contract before changing that second sentence. A single offline comparison cannot become that evidence on its own.
Capstone: Write a useful discrepancy report
Include one synthetic source sequence, the visible calculations on both sides, the first mismatch and a hypothesis about where it comes from. Add a miniature reproduction with the preceding row. State whether the difference involves a missing value, time alignment, number formatting, numerical computation, or the Boolean definition. Then run the relevant test instead of rewriting the rules all at once.
Quanty exercise review (beta) can help phrase the diagnostic. Ask for the smallest test that distinguishes your two most plausible causes. State that thresholds, periods and rule direction must not be changed without your decision. A suggested edit earns acceptance only after you rerun the hand-checkable examples and explain the consequence. If the code change makes the outputs coincide by dropping an unsupported bar, it has not necessarily preserved the definition.
Return to learn to code for trading to revisit any prerequisite. The backtesting in Python course turns timed decisions into a separate offline model ledger. A matching indicator is not the same as a matching execution policy, and neither tells you what to trade.
FAQ about this course
Does matching the last row prove that the port is right?
No. Earlier warm-up, gaps or crossings can differ even if the final row agrees. Compare defined and undefined positions throughout the fixture and keep the earliest disagreement.
Why does missing input appear as None in Python?
It represents an explicit absence under the exercise schema. It is neither a zero price nor evidence that a numeric value was invalid. The source average resets when its input is unavailable; the local port uses a visible marker for that event.
Does this create an algo or execute anything?
No. It creates a practice parity table and local tests. The reference script draws lines and a numeric marker, not an order or recommendation.
Related
- Learn to code for trading: the course sequence.
- Python trading indicators: compare numeric transformations offline.
- Arth Script: separate QuantPower product overview.