Overall Statistics
Total Trades
1
Average Win
0%
Average Loss
0%
Compounding Annual Return
0%
Drawdown
100.200%
Expectancy
0
Net Profit
-100.575%
Sharpe Ratio
-0.286
Probabilistic Sharpe Ratio
17.049%
Loss Rate
0%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
-1.849
Beta
-1.452
Annual Standard Deviation
3.253
Annual Variance
10.58
Information Ratio
-0.087
Tracking Error
3.39
Treynor Ratio
0.64
Total Fees
$137.59
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Common")
AddReference("QuantConnect.Algorithm")

from System import *
from QuantConnect import *
from QuantConnect.Orders import *
from QuantConnect.Algorithm import QCAlgorithm
import numpy as np
from datetime import datetime, timedelta

class MarginCallEventsAlgorithm(QCAlgorithm):

    def Initialize(self):
        self.SetCash(100000)
        self.SetStartDate(2020,1,1)
        self.SetEndDate(2020,8,11)
        self.AddEquity("PCG", Resolution.Daily)
        self.Securities["PCG"].SetLeverage(100)
        self.AddEquity("SPY", Resolution.Daily)

    def OnData(self, data):
        if not self.Portfolio.Invested:
            self.SetHoldings("PCG",3)
            self.SetHoldings("SPY",7)

    def OnMarginCall(self, requests):
        self.Debug("Margin Call")
        for order in requests:
            newQuantity = int(np.sign(order.Quantity) * order.Quantity * 1.1)
            requests.remove(order)
            requests.append(SubmitOrderRequest(order.OrderType, order.SecurityType, order.Symbol, newQuantity, order.StopPrice, order.LimitPrice, self.Time, "OnMarginCall"))
        return requests

    def OnMarginCallWarning(self):
        pcgHoldings = self.Securities["PCG"].Holdings.Quantity
        shares = int(-pcgHoldings * 0.005)
        self.Error("{0} - OnMarginCallWarning(): Liquidating {1} shares of PCG to avoid margin call.".format(self.Time, shares))
        self.MarketOrder("PCG", shares)