“””
Executes trades based mostly on the momentum technique and tracks key metrics.
Course of:
– Compute the SMA and examine it with the closing costs.
– Mark when to enter or exit a commerce utilizing alerts (1 for purchase, -1 for promote).
– Preserve information for present place worth, shares held, transaction prices, money, and general portfolio worth.
“””
# Add the transferring common to the dataset
self.price_data[“SMA”] = self.calculate_moving_average()
# Outline alerts: 1 for purchase, -1 for promote, and 0 for no motion
self.price_data[“Signal”] = (self.price_data[“Close”] > self.price_data[“SMA”]).astype(int).diff().fillna(0)
# Initialize columns for portfolio monitoring
self.price_data[“PositionValue”] = 0.0 # Worth of held shares
self.price_data[“SharesHeld”] = 0 # Variety of shares presently held
self.price_data[“TransactionCosts”] = 0.0 # Complete transaction prices incurred
self.price_data[“AvailableCash”] = self.starting_capital # Money accessible for buying and selling
self.price_data[“PortfolioValue”] = self.starting_capital # Complete worth of the portfolio
# Iterate via the information to replace portfolio values
for i in vary(len(self.price_data)):
if self.price_data.loc[i, “Signal”] == 1: # Purchase sign
shares_to_buy = self.price_data.loc[i, “AvailableCash”] // self.price_data.loc[i, “Close”]
price = shares_to_buy * self.price_data.loc[i, “Close”] * (1 + self.transaction_fee)
self.price_data.loc[i, “SharesHeld”] = shares_to_buy
self.price_data.loc[i, “TransactionCosts”] += price
self.price_data.loc[i, “AvailableCash”] -= price
elif self.price_data.loc[i, “Signal”] == -1: # Promote sign
sell_value = self.price_data.loc[i – 1, “SharesHeld”] * self.price_data.loc[i, “Close”] * (1 – self.transaction_fee)
self.price_data.loc[i, “SharesHeld”] = 0
self.price_data.loc[i, “AvailableCash”] += sell_value
self.price_data.loc[i, “TransactionCosts”] += sell_value * self.transaction_fee
# Replace place and whole portfolio worth
self.price_data.loc[i, “PositionValue”] = self.price_data.loc[i, “SharesHeld”] * self.price_data.loc[i, “Close”]
self.price_data.loc[i, “PortfolioValue”] = self.price_data.loc[i, “PositionValue”] + self.price_data.loc[i, “AvailableCash”]
# Calculate benchmark and technique returns
self.price_data[“BenchmarkReturns”] = self.price_data[“Close”].pct_change().fillna(0)
self.price_data[“StrategyReturns”] = self.price_data[“PortfolioValue”].pct_change().fillna(0)Key Factors: