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
Probabilistic 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.31
Tracking Error
0.149
Treynor Ratio
0
Total Fees
$0.00
Estimated Strategy Capacity
$0
Lowest Capacity Asset
 # region imports
from AlgorithmImports import *
import pandas as pd
import numpy as np
import talib
from datetime import timedelta
from random import random
import random
import scipy
import matplotlib as mpl
import matplotlib.pyplot as plt
import math

# endregion

class MuscularBrownSalamander(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2021, 1, 1)  # Set Start Date
        self.SetCash(100000)  # Set Strategy Cash
        self.UniverseSettings.Resolution = Resolution.Daily
        self.AddUniverse(self.SelectCoarse)
        self.mappings = {}
        self.SetBenchmark("SPY")
        


    def SelectCoarse(self, coarse):
        tickers = ["AAPL", "IBM"]
        
        return [Symbol.Create(x, SecurityType.Option, Market.USA) for x in tickers]

    
  
        #   1. Get date for every symbol
        #   2. for every date and for every symbol go back 30 days and get volatility value
        #   3. save days value and repeat for every symbol in universe

    def OnData(self, data: Slice):
        pass

    def OnSecuritiesChanged(self, changes: SecurityChanges) -> None:
        for symbol in [x.Symbol for x in changes.AddedSecurities]:
            self.mappings[symbol] = self.AddData(SECReport10Q, symbol).Symbol
            history = self.History(SECReport10Q, self.mappings[symbol], 400, Resolution.Daily)
            self.Debug(f"We got {len(history)} items from our history request")
            a = history.drop(['datasourceid','report'], axis=1, inplace=True)
            a = history.index.droplevel('symbol')
            for date in a:

                #   1. history for date
                #   2. calculate time
                self.window = RollingWindow[TradeBar](30)
                history_std = self.History(symbol, 40, Resolution.Daily)
                self.Debug(history_std)      
                self.std = self.STD(self.mappings[symbol], 10)
                self.std.Updated += self.StdUpdated
                self.stdWin = RollingWindow[IndicatorDataPoint](30)
                
                #self.window.Add(data[symbol])
                if not (self.stdWin.IsReady and self.window.IsReady): return


                self.Debug(f"We got {len(self.std_window)} items in window")
         
                    

                n_days = 0
                i = 0

                
                average = []
                while (self.stdWin[i] != self.stdWin[stdWin.Count -1]):
                    while (self.stdWin[i] > self.stdWin[i+1]):
                        n_days = n_days+1
                        i = i+1

                average.append(n_days)

                self.std.Reset()


                average  = [i for i in average if i != 0]
                print(average)
                average = sum(average)/len(average)
                math.ceil(average)
                #self.RemoveSecurity(self.history)
            if self.Portfolio.Invested: return
            if not self.Portfolio.Invested:
                self.TradeOptions(optionchain)

               
            
        for symbol in [s.Symbol for s in changes.RemovedSecurities]:
            # If removed from the universe, liquidate and remove the custom data from the algorithm
            self.Liquidate(symbol)
            reportSymbol = self.mappings.pop(symbol, None)
    
    def StdUpdated(self, sender, updated):
        '''Adds updated values to rolling window'''
        self.stdWin.Add(updated)

        '''Adds updated values to rolling window'''
    def TradeOptions(self,optionchain):

        if not self.Time - timedelta(days=average): return
    
        for i in optionchain:
            if i.Key != self.symbol: continue
            chain = i.Value
            # sorted the optionchain by expiration date and choose the furthest date
            expiry = sorted(chain,key = lambda x: x.Expiry, reverse=True)[0].Expiry
            # filter the call options from the contracts expires on that date
            call = [i for i in chain if i.Expiry == expiry and i.Right == 0]
            # sorted the contracts according to their strike prices 
            call_contracts = sorted(call,key = lambda x: x.Strike)    
            if len(call_contracts) == 0: continue
            # choose the deep OTM call option
            self.call = call_contracts[-1]
            # select the put options which have the same expiration date with the call option 
            # sort the put options by strike price
            put_contracts = sorted([i for i in chain if i.Expiry == expiry and i.Right == 1], key = lambda x: x.Strike)
            # choose the deep OTM put option
            self.put = put_contracts[0]
                    
            self.Buy(self.call.Symbol ,1)
            self.Buy(self.put.Symbol ,1)
            self.Debug("Bought" + str(self.Time))