Overall Statistics
Total Trades
2
Average Win
0%
Average Loss
-0.25%
Compounding Annual Return
-14.496%
Drawdown
0.200%
Expectancy
-1
Net Profit
-0.250%
Sharpe Ratio
-6.481
Loss Rate
100%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
-0.105
Beta
-0.001
Annual Standard Deviation
0.016
Annual Variance
0
Information Ratio
-7.328
Tracking Error
0.016
Treynor Ratio
188.734
Total Fees
$5.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, 13)
        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.activeOrder = False



    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 and not self.activeOrder:
            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.activeOrder=True
            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
                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.LimitOrder(symbol,-quantity,contracts[0].BidPrice+Decimal(0.01), "limit order - liquidate holdings")
                    self.activerOrder=False

            
        
            # if self.rsi.Current.Value > 40:
            #     self.Debug("RSI is greater then 40")
            #     self.Liquidate()
            
            
    def OnEndOfDay(self):
        self.Plot("Indicators","RSI", self.rsi.Current.Value)