Overall Statistics
Total Trades
0
Average Win
0%
Average Loss
0%
Compounding Annual Return
0%
Drawdown
0%
Expectancy
0
Net Profit
0%
Sharpe Ratio
0
Loss Rate
0%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
0
Beta
0
Annual Standard Deviation
0
Annual Variance
0
Information Ratio
0
Tracking Error
0
Treynor Ratio
0
Total Fees
$0.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 QuantConnect.Securities.Option import OptionPriceModels
from datetime import timedelta
import decimal as d


class BasicTemplateOptionsHistoryAlgorithm(QCAlgorithm):
    ''' This example demonstrates how to get access to options history for a given underlying equity security.'''

    def Initialize(self):
        # this test opens position in the first day of trading, lives through stock split (7 for 1), and closes adjusted position on the second day
        self.SetStartDate(2015, 12, 24)
        self.SetEndDate(2015, 12, 24)
        self.SetCash(1000000)
        
        equity = self.AddEquity("GOOG")
        option = self.AddOption("GOOG")

        
        equity.SetDataNormalizationMode(DataNormalizationMode.Raw)
        option.PriceModel = OptionPriceModels.CrankNicolsonFD()
        
        option.SetFilter(-2,2, timedelta(0), timedelta(180))
        self.SetBenchmark(equity.Symbol)

    def OnData(self,slice):
        if not self.Portfolio.Invested:
            for chain in slice.OptionChains:
                underlying = self.Securities[chain.Key.Underlying]
                for contract in chain.Value:
                    self.Log("{0},Bid={1} Ask={2} Last={3} OI={4} sigma={5:3f} NPV={6:3f} \
                              delta={7:3f} gamma={8:3f} vega={9:3f} beta={10:2f} theta={11:2f} IV={12:2f}".format(
                    contract.Symbol.Value,
                    contract.BidPrice,
                    contract.AskPrice,
                    contract.LastPrice,
                    contract.OpenInterest,
                    underlying.VolatilityModel.Volatility,
                    contract.TheoreticalPrice,
                    contract.Greeks.Delta,
                    contract.Greeks.Gamma,
                    contract.Greeks.Vega,
                    contract.Greeks.Rho,
                    contract.Greeks.Theta / 365,
                    contract.ImpliedVolatility))

    def OnOrderEvent(self, orderEvent):
        # Order fill event handler. On an order fill update the resulting information is passed to this method.
        # Order event details containing details of the events
        self.Log(str(orderEvent))

    def OnSecuritiesChanged(self, changes):
        if changes == SecurityChanges.None: return
        for change in changes.AddedSecurities:
            history = self.History(change.Symbol, 10, Resolution.Hour).sort_index(level='time', ascending=False)[:3]

            for i in range(len(history)):
                self.Log("History: " + str(history.iloc[i].name[0])
                        + ": " + str(history.iloc[i].name[1])
                        + " > " + str(history.iloc[i]['close']))