text_plain_output_2.png text_plain_output_1.png
from datetime import datetime

import datetime

import yfinance as yf

ticker = 'SPY'
start_time = datetime(2020, 5, 1)
end_time = datetime(2023, 5, 1)
spy = yf.download(ticker, start=start_time, end=end_time)

spy = yf.download(ticker, start=start_time, end=end_time)
start_time = datetime(2020, 5, 1)
end_time = datetime(2023, 5, 1)
spy['5_day_MA'] = spy['Close'].rolling(window=5).mean()
spy['30_day_MA'] = spy['Close'].rolling(window=30).mean()
initial_capital = 100000
capital = initial_capital
position = 0
stop_loss = None
for i in range(30, len(spy) - 1):
    pct_change = spy['Close'][i] / spy['Close'][i - 1] - 1
    if spy['5_day_MA'][i] > spy['30_day_MA'][i] and position <= 0:
        position = capital * 0.3
        capital -= position
        stop_loss = spy['Close'][i] * 0.9
    elif spy['5_day_MA'][i] < spy['30_day_MA'][i] and position >= 0:
        position = -capital * 0.2
        capital -= position
        stop_loss = spy['Close'][i] * 1.1
    if position > 0:
        if pct_change >= 0.1:
            additional_position = capital * 0.3
            position += additional_position
            capital -= additional_position
            stop_loss = spy['Close'][i] * 0.9
        elif pct_change >= 0.2:
            additional_position = capital * 0.4
            position += additional_position
            capital -= additional_position
            stop_loss = spy['Close'][i] * 0.9
        elif pct_change <= -0.1:
            capital += position
            position = 0
            stop_loss = None
    elif position < 0:
        if pct_change <= -0.1:
            additional_position = capital * 0.3
            position -= additional_position
            capital += additional_position
            stop_loss = spy['Close'][i] * 1.1
        elif pct_change <= -0.2:
            additional_position = capital * 0.4
            position -= additional_position
            capital += additional_position
            stop_loss = spy['Close'][i] * 1.1
        elif pct_change >= 0.1:
            capital -= position
            position = 0
            stop_loss = None
portfolio_value = capital + position
print(f'Initial capital: {initial_capital}')
print(f'Final portfolio value: {portfolio_value}')