Overall Statistics
Total Trades
24
Average Win
0.68%
Average Loss
-0.15%
Compounding Annual Return
95.566%
Drawdown
5.900%
Expectancy
1.386
Net Profit
1.450%
Sharpe Ratio
4.938
Loss Rate
57%
Win Rate
43%
Profit-Loss Ratio
4.57
Alpha
0.458
Beta
-0.008
Annual Standard Deviation
0.093
Annual Variance
0.009
Information Ratio
4.79
Tracking Error
0.093
Treynor Ratio
-55.79
Total Fees
$85.00
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Common")

from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from datetime import timedelta

import pandas as pd
import numpy as np
from decimal import Decimal

### <summary>
### This example demonstrates how to add options for a given underlying equity security.
### It also shows how you can prefilter contracts easily based on strikes and expirations, and how you
### can inspect the option chain to pick a specific option contract to trade.
### </summary>
### <meta name="tag" content="using data" />
### <meta name="tag" content="options" />
### <meta name="tag" content="filter selection" />
class BasicTemplateOptionsAlgorithm(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2018, 6, 8)
        self.SetEndDate(2018, 6, 15)
        self.SetCash(10000)
        self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Cash)
        equity = self.AddEquity("SPY", Resolution.Minute)
        option = self.AddOption("SPY", Resolution.Minute)
        self.option_symbol = option.Symbol
        
        option.SetFilter(lambda universe: universe.IncludeWeeklys().Strikes(-20, 20).Expiration(timedelta(2), timedelta(7)))
        
        self.symbol = option.Symbol
        
        self.rsi = self.RSI("SPY", 14)
        self.quantity=None


    def OnData(self,slice):
        if not self.rsi.IsReady: 
            return
        
        for i in slice.OptionChains:
            if i.Key != self.symbol: continue
            optionchain = i.Value
            #self.Log("underlying price:" + str(optionchain.Underlying.Price))
            df = pd.DataFrame([[x.Right,float(x.Strike),x.Expiry,float(x.BidPrice),float(x.AskPrice),float(x.Volume)] for x in optionchain],
                       index=[x.Symbol.Value for x in optionchain],
                       columns=['type(call 0, put 1)', 'strike', 'expiry', 'ask price', 'bid price', 'volume'])
            #self.Log(str(df))
            
            
            call = [x for x in optionchain if x.Right == 0]
            put = [x for x in optionchain if x.Right == 1]
            
            contracts = [x for x in call if x.UnderlyingLastPrice - x.Strike < -1]
            if len(contracts) == 0: return
            
            symbol = contracts[0].Symbol
            
        if self.rsi.Current.Value < 20:
            self.Debug("RSI is less then 20")
            # if not self.Portfolio.Invested:
            self.LimitOrder(symbol, 10, contracts[0].AskPrice - Decimal(0.01), "limit order")
            self.Debug("Order was placed")

        
        # Retrieve quantity for each contract in portfolio and sell quantity using limit order
        if self.Portfolio.Invested:
            option_invested = [x.Key.Value for x in self.Portfolio if x.Value.Invested and x.Value.Type==SecurityType.Option]
            for contract in option_invested:
                quantity = self.Portfolio[contract].Quantity
                
                # Retrieve the last price of options contract
                lastPrice = self.Securities[contract].Price
                
                # Liquidate contracts using LimitOrder
                if self.rsi.Current.Value > 40 and quantity > 0:

                    self.Debug("RSI is greater then 40")
                    self.Transactions.CancelOpenOrders(contract)

                    self.LimitOrder(contract,-quantity,lastPrice, "limit order - liquidate holdings")
                
    def OnEndOfDay(self):
        self.Plot("Indicators","RSI", self.rsi.Current.Value)