| Overall Statistics |
|
Total Trades 4 Average Win 0% Average Loss -14.73% Compounding Annual Return -27.362% Drawdown 29.400% Expectancy -1 Net Profit -27.426% Sharpe Ratio -1.606 Probabilistic Sharpe Ratio 0.000% Loss Rate 100% Win Rate 0% Profit-Loss Ratio 0 Alpha -0.216 Beta 0.14 Annual Standard Deviation 0.12 Annual Variance 0.014 Information Ratio -1.362 Tracking Error 0.265 Treynor Ratio -1.375 Total Fees $23.65 Estimated Strategy Capacity $28000000.00 Lowest Capacity Asset BP R735QTJ8XC9X |
# region imports
from AlgorithmImports import *
# endregion
class BuyAndHold(QCAlgorithm):
def Initialize(self):
self.SetCash(10000)
self.SetStartDate(2010,1,1)
self.SetEndDate(2015,1,1)
self.AddEquity("AAPL", Resolution.Daily)
def OnData(self,data):
if not self.Portfolio.Invested and self.invest:
self.SetHoldings("AAPL",1)
# region imports
from AlgorithmImports import *
from datetime import datetime
# endregion
class LimitOrder(QCAlgorithm):
def Initialize(self):
self.SetCash(100000)
self.SetStartDate(2008,1,1)
self.SetEndDate(2015,1,1)
self.stock = self.AddEquity("IBM", Resolution.Daily).Symbol
self.invest = True
def OnData(self,data):
if (self.Portfolio.Invested == False) and (self.invest == True):
#Buy 10 shares of IBM -- MAX price $50 -- (current market price is $40)
self.LimitOrder(symbol=self.stock, quantity=10, limitPrice=50)
# Sell 10shares --MINIMUM price $100
self.LimitOrder(symbol=self.stock, quantity=-10, limitPrice=100)
self.invest = False# region imports
from AlgorithmImports import *
from datetime import datetime
# endregion
class MarketOnCloseOrder(QCAlgorithm):
def Initialize(self):
self.SetCash(100000)
self.SetStartDate(2020,1,1)
#self.SetEndDate(2022,1,1)
self.spy = self.AddEquity("SPY", Resolution.Daily)
self.invest = True
def OnData(self,data):
#BUYING
if (self.Portfolio.Invested == False) and (self.invest == True):
self.MarketOnCloseOrder(symbol=self.spy.Symbol,
quantity=10,
tag="Buy on Market Close")
self.invest = False# region imports
from AlgorithmImports import *
from datetime import datetime
# endregion
class MarketOnOpenOrder(QCAlgorithm):
def Initialize(self):
self.SetCash(100000)
self.SetStartDate(2020,1,1)
#self.SetEndDate(2022,1,1)
self.spy = self.AddEquity("SPY", Resolution.Daily)
self.invest = True
def OnData(self,data):
#BUYING
if (self.Portfolio.Invested == False) and (self.invest == True):
self.MarketOnOpenOrder(symbol=self.spy.Symbol, quantity=10)
self.invest = False# region imports
from AlgorithmImports import *
from datetime import datetime
# endregion
class MarketOrder(QCAlgorithm):
def Initialize(self):
self.SetCash(100000)
self.SetStartDate(2010,1,1)
self.SetEndDate(2015,1,1)
self.spy = self.AddEquity("SPY", Resolution.Daily)
self.invest = True
def OnData(self,data):
#BUYING
if (self.Portfolio.Invested == False) and (self.invest == True):
# First day Close Price
self.MarketOrder(symbol= self.spy.Symbol, quantity = 1000)
self.invest = False
#SELLING
if (self.Time == datetime(day=1, month=1, year=2014)):
self.MarketOrder(symbol= self.spy.Symbol, quantity = -1000)# region imports
from AlgorithmImports import *
from datetime import datetime
# endregion
class StopLimitOrder(QCAlgorithm):
def Initialize(self):
self.SetCash(100000)
self.SetStartDate(2020,1,1)
#self.SetEndDate(2022,1,1)
self.spy = self.AddEquity("SPY", Resolution.Daily)
self.invest = True
self.sell_ticket = None
def OnData(self,data):
#BUYING
if (self.Portfolio.Invested == False) and (self.invest == True):
#First day closeing price
close = self.Securities['SPY'].Close
#1% drop --> Stop Triggered
stop_price = close * 0.99
# Limit 1% abve close price
limit_price = close * 1.01
stop_limit_ticker = self.StopLimitOrder(symbol= self.spy.Symbol,
quantity=10,
stopPrice=stop_price,
limitPrice=limit_price)
self.invest = False# region imports
from AlgorithmImports import *
from datetime import datetime
# endregion
class StopMarketOrder(QCAlgorithm):
def Initialize(self):
self.SetCash(100000)
self.SetStartDate(2019,1,1)
#self.SetEndDate(2022,1,1)
self.stock = self.AddEquity("BA", Resolution.Daily)
self.invest = True
self.sell_ticket = None
def OnData(self,data):
#BUYING
if (self.Portfolio.Invested == False) and (self.invest == True):
# First day Close Price
self.MarketOrder(symbol = self.stock.Symbol,
quantity = 10)
self.invest = False
#SELLING
if (self.sell_ticket == None):
self.sell_ticket = self.StopMarketOrder(symbol = self.stock.Symbol,
quantity = -10,
#Stop price tigger = 60% of initial Open Price
stopPrice = self.Securities['BA'].Open * 0.6,
tag = 'sell BA at -60%')# region imports
from AlgorithmImports import *
# endregion
class OrderSystem(QCAlgorithm):
def LimitOrder(self, stock: str, quantity: int, LimitPrice: float):
"""
Send a limit order to the transaction handler.
returns: The order ticket instance.
"""
if (self.Portfolio.Invested == False) and (self.invest == True):
self.LimitOrder(symbol=stock.Symbol,
quantity=quantity,
limitPrice=LimitPrice)
self.invest = False
def MarketOrder(self, stock: str, quantity: int):
"""
Send a Market order to the transaction handler.
returns: The order ticket instance.
"""
if (self.Portfolio.Invested == False) and (self.invest == True):
# First day Close Price
self.MarketOrder(symbol= stock.Symbol,
quantity = quantity)
self.invest = False
def StopMarketOrder(self, stock: str, quantity: int, stopPrice: float):
"""
Send a Stop Market order to the transaction handler.
returns: The order ticket instance.
"""
if (self.Portfolio.Invested == False) and (self.invest == True):
# First day Close Price
self.StopMarketOrder(symbol = stock.Symbol,
quantity = -10,
stopPrice = stopPrice)
self.invest = False
def StopLimitOrder(self, stock: str, quantity: int, limitPrice: float, stopPrice: float):
"""
Send a Stop Limit Order order to the transaction handler.
returns: The order ticket instance.
"""
if (self.Portfolio.Invested == False) and (self.invest == True):
#First day closeing price
close = self.Securities['SPY'].Close
#1% drop --> Stop Triggered
stop_price = close * 0.99
# Limit 1% abve close price
limit_price = close * 1.01
stop_limit_ticket = self.StopLimitOrder(symbol= stock.Symbol,
quantity=quantity,
stopPrice=stopPrice,
limitPrice=limitPrice)
self.invest = False
def CalculateSharesQuantity(self, stock: str, PortfolioExposure: float):
"""
Takes the Portfolio percentage and the stock price.
returns: The quantity of shares to execute order.
"""
#determine Quantity of shares can i buy with my cash
shares_to_buy = int(self.Portfolio.Cash / data[self.appl.Symbol].Open)
#determine Quantity of shares i already hold
held_shares = self.Portfolio[self.appl.Symbol].Quantity# region imports
from AlgorithmImports import *
# endregion
class CalculateSharesQuantity(QCAlgorithm):
def Initialize(self):
self.SetStartDate(year=2015,month=1,day=1)
self.SetEndDate(year=2020,month=1,day=1)
self.SetCash(startingCash=100000)
self.appl= self.AddEquity(ticker = "AAPL", resolution = Resolution.Daily)
self.invest_toggle = True
self.sell_toggle = True
def OnData(self, data):
#if for some reason, the data is corrupted just dont execute code and return
if (data[self.appl.Symbol] == False):
return
#BUYING
#if not invested then invest
if (self.Portfolio.Invested == False) and (self.invest_toggle == True):
#calculate the quantity of shares to buy- how much whole shares can i buy with my cash?
shares_to_buy = int(self.Portfolio.Cash / data[self.appl.Symbol].Open)
self.MarketOrder(symbol=self.appl.Symbol, quantity= shares_to_buy)
self.invest_toggle = False
return
profit = self.Portfolio[self.appl.Symbol].UnrealizedProfitPercent
#SELLING
#if 10 profit is reached sell half of the shares
if (profit >= 0.1) and (self.sell_toggle == True):
#define the number of shares you hol in you portfolio
held_shares = self.Portfolio[self.appl.Symbol].Quantity
# send a sell order for half of the shares. quantity must be int
self.MarketOrder(symbol=self.appl.Symbol, quantity=-(held_shares//2))
self.sell_toggle = False
def OnOrderEvent(self, orderEvent):
#if the order event is not filled then do nothing and return
if (orderEvent.FillQuantity == 0):
return
fetched = self.Transactions.GetOrderById(orderEvent.OrderId)
self.Log(f"{str(fetched.Type)} was filled ")
self.Log(f"Symbol Was {str(orderEvent.Symbol)} ")
self.Log(f"Quantity filled was {str(orderEvent.FillQuantity)} ")# region imports
from AlgorithmImports import *
# endregion
class SellOnProfit(QCAlgorithm):
def Initialize(self):
self.SetCash(10000)
self.SetStartDate(2018,1,1)
self.SetEndDate(2021,1,1)
self.AddEquity("AAL", Resolution.Daily)
self.invest = True
# 50% loss --> -0.5
self.limit_profit_percent = -0.5
def OnData(self,data):
if (self.Portfolio.Invested == False) and (self.invest == True):
self.SetHoldings("AAL",1)
profit_percent = self.Portfolio['AAL'].UnrealizedProfitPercent
if (self.Portfolio.Invested == True) and (profit_percent < self.limit_profit_percent):
self.Liquidate("AAL")
self.invest = False
# region imports
from AlgorithmImports import *
# endregion
class SellAtPrice(QCAlgorithm):
def Initialize(self):
self.SetCash(10000)
self.SetStartDate(2010,1,1)
self.SetEndDate(2020,1,1)
self.apple = self.AddEquity("AAPL", Resolution.Daily)
self.limit_price = 50
self.invest = True
def OnData(self,data):
if not self.Portfolio.Invested and self.invest:
self.SetHoldings("AAPL",1)
closing_price = self.Portfolio["AAPL"].Price
if closing_price > self.limit_price and self.Portfolio.Invested:
self.Liquidate("AAPL")
self.invest = False# region imports
from AlgorithmImports import *
# endregion
class SellAfterTime(QCAlgorithm):
def Initialize(self):
self.SetCash(10000)
self.SetStartDate(2015,1,1)
self.SetEndDate(2021,1,1)
self.AddEquity("SPY", Resolution.Daily)
self.invest = True
def OnData(self,data):
if not self.Portfolio.Invested and self.invest:
self.SetHoldings("SPY",1)
self.invested_time = self.Time #DATETIME object
time_diff = (self.Time - self.invested_time).days
if time_diff > 1000 and self.Portfolio.Invested:
self.Liquidate("SPY")
self.invest = False
# region imports
from AlgorithmImports import *
# endregion
class SellOnProfit(QCAlgorithm):
def Initialize(self):
self.SetCash(10000)
self.SetStartDate(2010,1,1)
self.SetEndDate(2015,1,1)
self.AddEquity("AAPL", Resolution.Daily)
self.invest = True
# 100% Proofit --> 1
self.limit_profit_percent =1
def OnData(self,data):
if (self.Portfolio.Invested == False) and (self.invest == True):
self.SetHoldings("AAPL",1)
profit_percent = self.Portfolio['AAPL'].UnrealizedProfitPercent
if (self.Portfolio.Invested == True) and (profit_percent > self.limit_profit_percent):
self.Liquidate("AAPL")
self.invest = False
# region imports
from AlgorithmImports import *
from datetime import datetime
# endregion
class SharesQuantityCalc(QCAlgorithm):
def Initialize(self):
self.SetCash(100000)
self.SetStartDate(2015,1,1)
self.SetEndDate(2020,1,1)
self.appl = self.AddEquity("AAPL", Resolution.Daily)
self.invest = True
self.sell = True
def OnData(self,data):
if (data[self.appl.Symbol] == False):
return
#BUYING
if (self.Portfolio.Invested == False) and (self.invest == True):
# how much whole shares can i buy with my cash?
shares_to_buy = int(self.Portfolio.Cash / data[self.appl.Symbol].Open)
self.MarketOrder(symbol= self.appl.Symbol,
quantity= shares_to_buy)
self.invest = False
return
profit = self.Portfolio[self.appl.Symbol].UnrealizedProfitPercent
#SELLING
if (profit >= 0.1) and (self.sell == True):
#
held_shares = self.Portfolio[self.appl.Symbol].Quantity
half_of_held_shares = held_shares//2
# if 10% profit is reached sell half of our shares
self.MarketOrder(Symbol= self.appl.Symbol,
quantity= -(held_shares//2) )
self.sell = False
def OnOrderEvent(self, orderEvent):
#if the order is not filled do nothing
if (orderEvent.FillQuantity == 0):
return
fetched = self.Transactions.GetOrderById(orderId=orderEvent.OrderId)
self.Log(f"{str(fetched.Type)} was filled")
self.Log(f"Symbol was {str(orderEvent.Symbol)}")
self.Log(f"Quantity was {str(orderEvent.FillQuantity)}")# region imports
from AlgorithmImports import *
# endregion
class InteractiveOrderTicketObjects(QCAlgorithm):
def Initialize(self):
self.SetStartDate(year=2020,month=1,day=1)
self.SetEndDate(year=2021,month=1,day=1)
self.SetCash(startingCash=100000)
self.xom= self.AddEquity(ticker = "XOM", resolution = Resolution.Daily)
self.bp= self.AddEquity(ticker = "BP", resolution = Resolution.Daily)
self.invest_toggle = True
self.sell_xom_toggle = True
self.sell_bp_toggle = True
def OnData(self, data):
#if for some reason, the data is corrupted just dont execute code and return
if (data[self.xom.Symbol] == False) and (data[self.bp.Symbol] == Flase):
return
#BUYING
#if not invested then invest
if (self.Portfolio.Invested == False) and (self.invest_toggle == True):
#buy shares of XOM with 50% of portfolio
self.SetHoldings(symbol=self.xom.Symbol,percentage=0.5)
#store open price for XOM
self.openPrice_xom =self.Securities[self.xom.Symbol].Open
#buy shares of BP with 50% of portfolio
self.SetHoldings(symbol=self.bp.Symbol,percentage=0.5)
#store open price for BP
self.openPrice_bp =self.Securities[self.bp.Symbol].Open
# turn investing toggle off
self.invest_toggle = False
if (self.Portfolio.Invested == True) and (self.sell_xom_toggle == True):
#getting shares i hold
held_shares_xom = self.Portfolio[self.xom.Symbol].Quantity
#Selling if 20% Loss is reached
self.StopMarketOrder(symbol=self.xom.Symbol,
quantity=-(held_shares_xom),
stopPrice=self.openPrice_xom * 0.8,
tag = "Selling all shares of XOM")
#switching XOM selling toggle
self.sell_xom_toggle = False
if (self.Portfolio.Invested == True) and (self.sell_bp_toggle == True):
#Getting shares i hold
held_shares_bp = self.Portfolio[self.bp.Symbol].Quantity
#Selling if 20% Loss is reached
self.StopMarketOrder(symbol=self.bp.Symbol,
quantity=-(held_shares_bp),
stopPrice=self.openPrice_bp * 0.8,
tag = "Selling all shares of BP")
#switchin BP selling toggle
self.sell_bp_toggle = False
def OnOrderEvent(self, orderEvent):
#if the order event is not filled then do nothing and return
if (orderEvent.FillQuantity == 0):
return
fetched = self.Transactions.GetOrderById(orderEvent.OrderId)
self.Log(f"Order ID {str(fetched.Type)} for Ticker {str(orderEvent.Symbol)} is executed with Quantity {str(orderEvent.FillQuantity)}")