Overall Statistics
Total Trades
108
Average Win
0.28%
Average Loss
-0.30%
Compounding Annual Return
7.961%
Drawdown
1.600%
Expectancy
0.288
Net Profit
4.747%
Sharpe Ratio
2.477
Loss Rate
33%
Win Rate
67%
Profit-Loss Ratio
0.93
Alpha
0.192
Beta
-8.058
Annual Standard Deviation
0.025
Annual Variance
0.001
Information Ratio
1.831
Tracking Error
0.025
Treynor Ratio
-0.008
Total Fees
$0.00
#import cpattern

#class PerformTrade():
    
    #def __init__():
        

#if self.algo.Portfolio[self.symbol].Quantity == 0:

    #self.SetHoldings(self.symbol, 1000)
    #self.algo.StopMarketOrder('EURUSD', -1000, float(data['EURUSD'].Close) - 0.0050)
    #self.algo.LimitOrder('EURUSD', -1000, float(data['EURUSD'].Close) + 0.0050)

# Your New Python File
import numpy as np
import yaml
from functools import reduce
import datastorage

class CPattern():

    def __init__(self, allData, algo, patLength = 30):

        self.algo = algo
        self.patLength = patLength
        self.avgLine   = allData['close'].values.tolist()
        self.patForRec = []
        self.plotPatAr = [] # Array containing recognized patterns
        #self.performanceAr = []
        self.predictedOutcomes = []
        self.predArray = [] # Array containing 1 for good outcomes and -1 for bad outcomes
        
        history = self.algo.History(self.algo.Securities.Keys, 4000, Resolution.Hour)
        
        self.data = datastorage.Data(history, 3700, self) # Object of type Data containing information

        self.lastPattern()
        self.algo.Debug(str(self.patForRec))


    def percentChange(self, startPoint, currentPoint):

        try:
            x = ((float(currentPoint)-startPoint)/abs(startPoint))*100.00

            if x == 0.0:
                return 0.0000001

            else:
                return x

        except:
            return 0.0000001


    def lastPattern(self):

        self.patForRec.clear()
        
        last = self.algo.History(self.algo.Securities.Keys, 35, Resolution.Hour)['close'].values.tolist()

        for i in range(0, self.patLength):
            self.patForRec.append(self.percentChange(last[-31], last[-30+i]))
            
        self.algo.Debug("PatForRec: " + str(self.patForRec))


    def patternRecognition(self, data):

        patFound = 0
        self.plotPatAr = []
        self.lastPattern()

        for pattern in self.data.patternArray:

            sim = []
            totalSim = 0

            for i in range(0, self.patLength):

                sim.append(100.00 - abs(self.percentChange(pattern[i], self.patForRec[i])))
                totalSim += sim[i]

            totalSim = totalSim/self.patLength
            
            #self.algo.Debug("Sim len: " + str(len(sim)))
            #self.algo.Debug("Total Sim: " + str(totalSim))

            if totalSim > 65:

                patternIndex = self.data.patternArray.index(pattern)

                patFound = 1

                xp = [i for i in range(1, self.patLength + 1)]

                self.plotPatAr.append(pattern)
                self.algo.Debug("Recognized pattern: " + str(pattern))
                
        self.algo.Debug("Recognized patterns: " + str(len(self.plotPatAr)))
        #self.algo.Debug("Patterns: " + str(self.plotPatAr))
        
        return patFound
        
    def determinePattern(self, data):
        
        self.predArray = []
        self.predictedOutcomes = []

        if self.patternRecognition(data) == 1:

            for eachPatt in self.plotPatAr:
                
                #if len(eachPatt) == 1:
                    #self.algo.Debug("Only one pattern")
                    #return

                futurePoints = self.data.patternArray.index(eachPatt)

                if self.data.performanceArray[futurePoints] > self.patForRec[29]:
                    self.predArray.append(1.000)

                else:
                    self.predArray.append(-1.000)

                self.predictedOutcomes.append(self.data.performanceArray[futurePoints])
                
                
            self.algo.Debug("PredArray: " + str(self.predArray))
            self.algo.Debug("PredOutcomes: " + str(self.predictedOutcomes))
                
    def predictOutcome(self, data):
    
        self.determinePattern(data)
        
        if len(self.predictedOutcomes) < 5:
            return None
    
        predictedAvgOutcome = reduce(lambda x, y: x+y, self.predictedOutcomes) / len(self.predictedOutcomes)

        predictionAverage = reduce(lambda x, y: x+y, self.predArray) / len(self.predArray)
        
        self.algo.Debug("PredictedAvgOutcome: " + str(predictedAvgOutcome))

        if predictionAverage < 0:

            self.algo.Debug("Drop predicted")
            return -1

        if predictionAverage > 0:

            self.algo.Debug("Rise predicted")
            return 1
import numpy as np
import yaml
from functools import reduce

class Data():
    
    def __init__(self, allData, limit, algo):
        
        self.algo = algo
        self.patternArray = []
        self.performanceArray = []
        self.toWhat = limit
        self.avgLine = allData['close'].values.tolist()
        self.avgLine = self.avgLine[:limit]
        self.avgLine = self.avgLine[::-1]
        self.patternStorage()
        
    def percentChange(self, startPoint, currentPoint):
        
        try:
            x = ((float(currentPoint)-startPoint)/abs(startPoint))*100.00
            
            if x == 0.0:
                return 0.0000001
                
            else:
                return x
        
        except:
            return 0.0000001
    
    def patternStorage(self):
        
        
        x = self.toWhat - 30
        y = 31
        n = 0
        
        while y < x:
            
            pattern = []

            for i in range(0, 30):
                
                pattern.append(self.percentChange(self.avgLine[y-30], self.avgLine[y-(29-i)]))
                
            outcomeRange = self.avgLine[y+20:y+30]
            currentPoint = self.avgLine[y]
            
            try:
                avgOutcome = (reduce(lambda x,y: x+y, outcomeRange) / len(outcomeRange))
                
            except:
                avgOutcome = 0
                
            futureOutcome = self.percentChange(currentPoint, avgOutcome)
            
            self.patternArray.append(pattern)
            self.performanceArray.append(futureOutcome)
            
            y += 1
            
        
    def getPatLen(self):
        return len(self.patternArray)
    
    def getPerfLen(self):
        return len(self.performanceArray)
        
    def getAvgLen(self):
        return len(self.avgLine)
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Indicators")
AddReference("QuantConnect.Common")

from System import *
from QuantConnect import *
from QuantConnect.Data import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
from decimal import Decimal
from datetime import datetime, timedelta

import numpy as np
import yaml
import datastorage
import cpattern
#from functools import reduce

### <summary>
### Basic template algorithm simply initializes the date range and cash. This is a skeleton
### framework you can use for designing an algorithm.
### </summary>
class BasicTemplateAlgorithm(QCAlgorithm):
    '''Basic template algorithm simply initializes the date range and cash'''
    
    def __init__(self):
        self.symbol = "EURUSD"
    
    def Initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

        self.SetStartDate(2013,10,7)   #Set Start Date
        self.SetEndDate(2014,5,15)    #Set End Date
        self.SetCash(100000)           #Set Strategy Cash
        # Find more symbols here: http://quantconnect.com/data
        self.AddForex(self.symbol, Resolution.Minute)
        self.tradePrice = 0
        self.tradeTime = self.UtcTime;
        self.results = 0;
        #self.closeWindow = RollingWindow[Decimal](4)
        self.Debug("numpy test >>> print numpy.pi: " + str(np.pi))
        
        history = self.History(self.Securities.Keys, 4000, Resolution.Hour)

        self.Debug("History length: " + str(len(history)))
        self.Debug("History in 1" + str(history['close'].values))
        
        self.cPat = cpattern.CPattern(history, self)
        
        #self.Debug("Data: " + str(self.cPat.data.patternArray))
        
        hourConsolidator = QuoteBarConsolidator(timedelta(minutes=60))
        
        hourConsolidator.DataConsolidated += self.HourBarHandler
        
        self.SubscriptionManager.AddConsolidator(self.symbol, hourConsolidator)
        
    
    
    def HourBarHandler(self, sender, bar):
        self.results = 0
        
        try:
            self.Debug("============================================================================")
            self.Debug("============================================================================")
            self.Debug("============================================================================")
            self.Debug("============================================================================")
            self.results = self.cPat.predictOutcome(bar)

        except:
            self.Debug("Error")

    def OnData(self, data):
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.

        Arguments:
            data: Slice object keyed by symbol containing the stock data
        '''
        #if not self.Portfolio.Invested:
            #self.SetHoldings(self.symbol, 1)
            
        #self.closeWindow.Add(slice["EURUSD"].Close)
        
        #if len(self.closeWindow) < 33:
            #return
        
        try:
            
            #if self.UtcTime > self.tradeTime + timedelta(hours=1):
            
            if self.UtcTime.replace(tzinfo=None) < datetime.strptime("12/28/13", "%m/%d/%y") or self.UtcTime.replace(tzinfo=None) > datetime.strptime("1/3/14", "%m/%d/%y"):
            
                if self.results == 1:
                    
                    if self.Portfolio['EURUSD'].Quantity == 0:
                        
                        self.tradeTime = self.UtcTime
                        self.SetHoldings('EURUSD', 1)
                        
                        self.tradePrice = data['EURUSD'].Close
                        
                        #self.StopMarketOrder('USDJPY', -1, float(slice['USDJPY'].Close) - 0.0030)
                        #self.LimitOrder('USDJPY', -1, float(slice['USDJPY'].Close) + 0.0030)
                        
            if self.UtcTime > self.tradeTime + timedelta(hours=20):
                    
                if self.Portfolio['EURUSD'].Quantity > 0:
                    
                    if (float(data['EURUSD'].Close)) > (float(self.tradePrice) + 0.0030):
                        
                        self.Liquidate()
                        self.tradeTime = self.UtcTime
                        
                    if (float(data['EURUSD'].Close)) < (float(self.tradePrice) - 0.0030):
                        
                        self.Liquidate()
                        self.tradeTime = self.UtcTime
                        
            if self.Portfolio['EURUSD'].Quantity > 0:
                
                if (float(data['EURUSD'].Close)) < (float(self.tradePrice) - 0.0060):
                    
                    self.Liquidate()
                    self.tradeTime = self.UtcTime
                    
            """
                
            #SHORTING STARTS HERE
            
            if self.UtcTime.replace(tzinfo=None) < datetime.strptime("12/28/13", "%m/%d/%y") or self.UtcTime.replace(tzinfo=None) > datetime.strptime("1/3/14", "%m/%d/%y"):
            
                if self.results == -1:
                    
                    if self.Portfolio['EURUSD'].Quantity == 0:
                        
                        self.tradeTime = self.UtcTime
                        self.SetHoldings('EURUSD', -1)
                        
                        self.tradePrice = data['EURUSD'].Close
                        
                        #self.StopMarketOrder('EURUSD', -1, float(slice['EURUSD'].Close) - 0.0030)
                        #self.LimitOrder('EURUSD', -1, float(slice['EURUSD'].Close) + 0.0030)
                        
            if self.UtcTime > self.tradeTime + timedelta(hours=20):
                    
                if self.Portfolio['EURUSD'].Quantity < 0:
                    
                    if (float(data['EURUSD'].Close)) > (float(self.tradePrice) + 0.0030):
                        
                        self.Liquidate()
                        self.tradeTime = self.UtcTime
                        
                    if (float(data['EURUSD'].Close)) < (float(self.tradePrice) - 0.0030):
                        
                        self.Liquidate()
                        self.tradeTime = self.UtcTime
                        
            if self.Portfolio['EURUSD'].Quantity < 0:
                
                if (float(data['EURUSD'].Close)) > (float(self.tradePrice) + 0.0060):
                    
                    self.Liquidate()
                    self.tradeTime = self.UtcTime
                    
            
            #SHORTING STOPS HERE
            
            """
            
        except:
            self.Debug("Error")