Last active
June 21, 2022 01:35
-
-
Save rcholic/87d590d68ccc8316745e26f48b578dc2 to your computer and use it in GitHub Desktop.
simulation of options trading with Iron Condor strategy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import List | |
import numpy as np | |
import random | |
import math | |
def perform_iron_condor( | |
trade_days: int, | |
initial_capital: float, | |
spread: float = 50.0, | |
profit_rate_daily: float = 0.02, | |
stop_loss_dollar_amount: float = 4.0) -> List[float]: | |
shares_per_contract = 100 | |
stop_loss_count = 0 # number of times for stopping loss | |
profit = 0 | |
capital = initial_capital | |
funds_per_contract = shares_per_contract * spread | |
for i in range(trade_days): | |
contracts = int(capital / funds_per_contract) | |
profit += profit_rate_daily * funds_per_contract * contracts | |
sample = random.randrange(1, 100, 1) | |
if sample <= 5: | |
stop_loss_count += 1 | |
profit -= stop_loss_dollar_amount * shares_per_contract * contracts | |
if profit < 0: | |
capital += profit | |
profit = 0 | |
continue | |
additional_contracts = int(profit / funds_per_contract) | |
realized_profit = additional_contracts * funds_per_contract | |
capital += realized_profit | |
# print('realized_profit = {}, capital = {}'.format(realized_profit, capital)) | |
profit -= realized_profit | |
capital = capital + profit | |
roi = np.round((capital - initial_capital) * 100.0 / initial_capital, 2) | |
return [float(stop_loss_count), capital, roi] | |
# simulate options IC trading for different number of days | |
trade_days = [10, 20, 100, 200, 400] | |
fail_rate = 0.05 # 5% chance for stop loss | |
initial_capital = 15000 | |
profit_rate_daily = 0.02 # 2% | |
spread_amount = 50.0 | |
stop_loss_threshold = 4 # 3 dollars | |
for period in trade_days: | |
expected_stop_loss_times = math.ceil(period * fail_rate) | |
print('daily return rate: {}%, spread = {}, stop loss threshold = ${}'.format(100 * profit_rate_daily, spread_amount, stop_loss_threshold)) | |
while True: | |
result = perform_iron_condor(period, initial_capital=initial_capital) | |
stop_times = math.ceil(result[0]) | |
final_capital = result[1] | |
roi = result[2] | |
if stop_times == expected_stop_loss_times: | |
print('Initial capital = {}\nAfter {} days of trade, final capital = {}\nROI = {}%\nStop loss times: {}'.format(initial_capital, period, final_capital, roi, stop_times)) | |
print('----------------') | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment