Read the first example one line at a time. A line that prints shows what appears on screen; the rest set things up quietly.
prices = [100, 105, 110, 108, 115, 120, 118, 125]
sets nothing on screen
cash = 1000.0
sets nothing on screen
holding = 0.0
sets nothing on screen
trades = 0
sets nothing on screen
for i in range(1, len(prices)):
sets nothing on screen
prev = prices[i - 1]
sets nothing on screen
cur = prices[i]
sets nothing on screen
if cur > prev and holding == 0:
sets nothing on screen
holding = cash / cur
sets nothing on screen
cash = 0.0
sets nothing on screen
trades += 1
sets nothing on screen
elif cur < prev and holding > 0:
sets nothing on screen
cash = holding * cur
sets nothing on screen
holding = 0.0
sets nothing on screen
trades += 1
sets nothing on screen
final_value = cash + holding * prices[-1]
sets nothing on screen
print("Backtesting strategy over history")
Backtesting strategy over history
print("Initial capital: $1000.00")
Initial capital: $1000.00
print("Final value: $%.2f" % final_value)
Final value: $1055.40
print("Return: %.1f%%" % ((final_value / 1000.0 - 1.0) * 100.0))
Return: 5.5%
print("Trades executed: %d" % trades)
Trades executed: 5