Overall Statistics
Total Trades
20
Average Win
0.45%
Average Loss
-0.15%
Compounding Annual Return
114.360%
Drawdown
5.700%
Expectancy
2.228
Net Profit
1.650%
Sharpe Ratio
7.447
Loss Rate
20%
Win Rate
80%
Profit-Loss Ratio
3.04
Alpha
0.518
Beta
-0.005
Annual Standard Deviation
0.07
Annual Variance
0.005
Information Ratio
7.249
Tracking Error
0.07
Treynor Ratio
-105.398
Total Fees
$75.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)



    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
            
            if self.rsi.Current.Value < 20:
                self.Debug("RSI is less then 20")
                symbol = contracts[0].Symbol
                self.LimitOrder(symbol, 10, contracts[0].AskPrice - Decimal(0.01), "limit order")
                self.Debug("Order was placed")

        
            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)