Overall Statistics
Total Trades
39
Average Win
2.61%
Average Loss
-0.14%
Compounding Annual Return
29.868%
Drawdown
4.700%
Expectancy
14.063
Net Profit
57.448%
Sharpe Ratio
2.369
Loss Rate
23%
Win Rate
77%
Profit-Loss Ratio
18.49
Alpha
0.187
Beta
0.419
Annual Standard Deviation
0.092
Annual Variance
0.008
Information Ratio
1.337
Tracking Error
0.108
Treynor Ratio
0.521
Total Fees
$464.20
# 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.Indicators")
AddReference("QuantConnect.Common")

from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
from QuantConnect.Data import SubscriptionDataSource
from QuantConnect.Python import PythonData
from datetime import date, timedelta, datetime
import numpy as np
import math
import json


### <summary>
### Strategy example algorithm using CAPE - a bubble indicator dataset saved in dropbox. CAPE is based on a macroeconomic indicator(CAPE Ratio),
### we are looking for entry/exit points for momentum stocks CAPE data: January 1990 - December 2014
### Goals:
### Capitalize in overvalued markets by generating returns with momentum and selling before the crash
### Capitalize in undervalued markets by purchasing stocks at bottom of trough
### </summary>
### <meta name="tag" content="strategy example" />
### <meta name="tag" content="custom data" />
class PMOAlgorithm(QCAlgorithm):

    def Initialize(self):

        self.SetCash(1000000)
        self.SetStartDate(2018,1,2)
        self.SetEndDate(date.today())
        # add SPY data 
        self.spy = self.AddEquity("SPY", Resolution.Daily) 
        # add PMO data
        self.pmo = self.AddData(PMO, "PMO", Resolution.Daily)
        # self.Debug("dir(self.pmo): " + str(dir(self.pmo)))
        # self.Debug(str(self.Time) + " self.CurrentSlice: " + str(self.CurrentSlice))
        
    # Trying to find if current Cape is the lowest Cape in three months to indicate selling period
    def OnData(self, data):
        if data.ContainsKey("PMO"):
            self.SetHoldings("SPY", data["PMO"].Value)
        
# PMO indicator data 
class PMO(PythonData):
    
    # Return the URL string source of the file. This will be converted to a stream
    # <param name="config">Configuration object</param>
    # <param name="date">Date of this source file</param>
    # <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
    # <returns>String URL of source file.</returns>

    def GetSource(self, config, date, isLiveMode):
        # Remember to add the "?dl=1" for dropbox links
        return SubscriptionDataSource("https://www.dropbox.com/s/o148sdjeiubtgfk/pmo90d.csv?dl=1", SubscriptionTransportMedium.RemoteFile)
    
    
    ''' Reader Method : using set of arguements we specify read out type. Enumerate until 
        the end of the data stream or file. E.g. Read CSV file line by line and convert into data types. '''
        
    # <returns>BaseData type set by Subscription Method.</returns>
    # <param name="config">Config.</param>
    # <param name="line">Line.</param>
    # <param name="date">Date.</param>
    # <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
    
    def Reader(self, config, line, date, isLiveMode):
        if not (line.strip() and line[0].isdigit()): return None
    
        # New Nifty object
        pmo = PMO()
        pmo.Symbol = config.Symbol
    
        try:
            # Example File Format:
            # Date   |  Price |  Div  | Earning | CPI  | FractionalDate | Interest Rate | RealPrice | RealDiv | RealEarnings | CAPE
            # 2014.06  1947.09  37.38   103.12   238.343    2014.37          2.6           1923.95     36.94        101.89     25.55
            data = line.split(',')
            # Dates must be in the format YYYY-MM-DD. If your data source does not have this format, you must use
            # DateTime.ParseExact() and explicit declare the format your data source has.
            
            pmo.Time = datetime.strptime(data[2], "%Y-%m-%d")
            pmo.Value = float(data[3])
            
    
        except ValueError:
                # Do nothing
                # self.Debug(str("Error in reading PMO data. \n"))
                return None
    
        return pmo