Exemple #1
0
def main():
    dataFile.getDataIntoMatrix(args.pd)
    predictedValuesDict = dict()
    getPredictedValuesIntoDict(predictedValuesDict)
    lower_entry = totalEntryCL[0]
    upper_entry = totalEntryCL[1]
    lower_exit = totalExitCL[0]
    l_index_gap = 0.2
    l_max_gap = (upper_entry - lower_entry)/(4)
    while l_index_gap < l_max_gap:
        exitCL2 = lower_exit + float(l_index_gap) 
        exitCL1 = lower_exit + 2*float(l_index_gap) 
        exitCL0 = lower_exit + 3*float(l_index_gap) 
        exitCL = lower_exit + 4*float(l_index_gap)
        if(lower_entry < exitCL):
            lower_entry = lower_exit + 4*float(l_index_gap)
        entryCL2 = lower_entry + float(l_index_gap)
        entryCL1 = lower_entry + 2*float(l_index_gap) 
        entryCL0 = lower_entry + 3*float(l_index_gap) 
        entryCL = lower_entry + 4*float(l_index_gap)
        l_entry_list = [entryCL2,entryCL1,entryCL0 , entryCL]
        l_exit_list = [exitCL2,exitCL1,exitCL0 , exitCL]
        print("Entry Exit list" + str(l_entry_list)+ str(l_exit_list))
        if(exitCL < entryCL2 and entryCL <= upper_entry):
            lInitialFileName = args.a + '-td.' + os.path.basename(os.path.abspath(args.td)) + \
                           '-dt.' + args.dt + '-targetClass.' + args.targetClass + '-f.' + experimentName + "-wt." + args.wt+ attribute.generateExtension() + \
                           '-l.'+entryCL+"-"+entryCL0+"-"+entryCL1+"-"+entryCL2+"-"+exitCL +"-"+exitCL0 +"-"+exitCL1 +"-"+exitCL2 + "-tq." + args.orderQty  + "-te.10" 
            initialFileName.append(lInitialFileName)
            for lFileName in initialFileName:
                readOnceAndWrite(lFileName, l_entry_list, l_exit_list, predictedValuesDict)
        else:
            l_index_gap = l_index_gap + 0.1
Exemple #2
0
def main():
    dataFile.getDataIntoMatrix(args.pd)
    predictedValuesDict = dict()
    getPredictedValuesIntoDict(predictedValuesDict)
    lIndexOfEntryOrExitCL = 0
    for lFileName in initialFileName:
        readOnceAndWrite(lFileName, lIndexOfEntryOrExitCL, predictedValuesDict)
        lIndexOfEntryOrExitCL = lIndexOfEntryOrExitCL + 1
Exemple #3
0
def main():
    dataFile.getDataIntoMatrix(args.pd)
    predictedValuesDict = dict()
    getPredictedValuesIntoDict(predictedValuesDict)
    lIndexOfEntryOrExitCL = 0
    for lFileName in initialFileName:
        readOnceAndWrite(lFileName, lIndexOfEntryOrExitCL, predictedValuesDict)
        lIndexOfEntryOrExitCL = lIndexOfEntryOrExitCL + 1
Exemple #4
0
def main():
    dataFile.getDataIntoMatrix(args.pd)
    predictedValuesDict = dict()
    getPredictedValuesIntoDict(predictedValuesDict)
    lIndexOfEntryOrExitCL = 0
    for lFileName in initialFileName:
        entryCL = float("." + gEntryCLList[lIndexOfEntryOrExitCL] )
        exitCL = float("." + gExitCLList[lIndexOfEntryOrExitCL] )
        readOnceAndWrite(lFileName,entryCL,exitCL, predictedValuesDict)
        lIndexOfEntryOrExitCL = lIndexOfEntryOrExitCL + 1
Exemple #5
0
def main():
    dataFile.getDataIntoMatrix(args.d)
    targetValuesDict = dict()
    getTargetValuesIntoDict(targetValuesDict)
    lIndexOfEntryOrExitCL = 0
    for lFileName in initialFileName:
        if os.path.isfile(fileName) and args.skipT.lower() == "yes":
            print("\nFile already exists")
        else:
            readOnceAndWrite(lFileName, lIndexOfEntryOrExitCL,
                             targetValuesDict)
        lIndexOfEntryOrExitCL = lIndexOfEntryOrExitCL + 1
Exemple #6
0
def main():
    dataFile.getDataIntoMatrix(args.pd)
    predictedValuesDict = dict()
    getPredictedValuesIntoDict(predictedValuesDict)
    lIndexOfEntryOrExitCL = 0
    for lFileName in initialFileName:
        entryCL4 = float("." + gEntryCL4List[lIndexOfEntryOrExitCL])
        entryCL3 = float("." + gEntryCL3List[lIndexOfEntryOrExitCL])
        entryCL2 = float("." + gEntryCL2List[lIndexOfEntryOrExitCL])
        entryCL1 = float("." + gEntryCL1List[lIndexOfEntryOrExitCL])
        exitCL4 = float("." + gExitCL4List[lIndexOfEntryOrExitCL])
        exitCL3 = float("." + gExitCL3List[lIndexOfEntryOrExitCL])
        exitCL2 = float("." + gExitCL2List[lIndexOfEntryOrExitCL])
        exitCL1 = float("." + gExitCL1List[lIndexOfEntryOrExitCL])
        readOnceAndWrite(lFileName, entryCL1, entryCL2, entryCL3, entryCL4,
                         exitCL1, exitCL2, exitCL3, exitCL4,
                         predictedValuesDict)
        lIndexOfEntryOrExitCL = lIndexOfEntryOrExitCL + 1
Exemple #7
0
def main():
#   try:
      attribute.initializeInstDetails(args.iT,args.sP,args.oT) 
      dataFile.getDataIntoMatrix(args.d)
      attribute.checkIfNewDataFileExists(args.d)
      newFileName = dataFile.getNewDataFileName(args.d)
      header = "Instrument;AskQ0;AskP0;AskQ1;AskP1;AskQ2;AskP2;AskQ3;AskP3;AskQ4;AskP4;BidQ0;BidP0;BidQ1;BidP1;BidQ2;BidP2;BidQ3;BidP3;BidQ4;BidP4;TTQ;LTP;LTQ;LTT;ATP;TBQ;TSQ;CP;OP;HP;LP;TimeStamp;SerialNo;MsgCode;OrderType;Quantity1;Price1;Quantity2;Price2;ExchangeTS;BestBidQ;BestBidP;BestAskQ;BestAskP\n"
      print newFileName
      newFileObject = open(newFileName,"w")
      newFileObject.write(header)
      previousLine = ""
      currentRowCount = 0
      for dataRow in dataFile.matrix:
        
        lineWithoutBestPrices = ";".join(dataRow[:colNumberOfData.TTQ])
        if previousLine <> lineWithoutBestPrices:
            newFileObject.write(";".join(dataRow) + "\n")
            previousLine = lineWithoutBestPrices
        currentRowCount = currentRowCount + 1
        if(currentRowCount % 1000 == 0):
            print "Processed row number " + str(currentRowCount)
Exemple #8
0
def main():

    dirName = args.pd.replace('/ro/', '/rs/')
    tradeResultMainDirName = dirName + "/r/"
    if not os.path.exists(tradeResultMainDirName):
        os.mkdir(tradeResultMainDirName)
    tradeResultSubDirectoryName = tradeResultMainDirName + mainExperimentName + "/"
    if not os.path.exists(tradeResultSubDirectoryName):
        os.mkdir(tradeResultSubDirectoryName)
    outputFileName = tradeResultSubDirectoryName + experimentName + initialFileName + ".result"

    #if os.path.isfile(outputFileName):
    #    print("The results file already exisits. Delete it to run the program again" + outputFileName)
    #    return 1
    dataFile.getDataIntoMatrix(args.pd)
    predictedValuesDict = dict()
    getPredictedValuesIntoDict(predictedValuesDict)
    enterTrade = 0
    ttqAtTimeOfPreviousDataRow = 0
    askP0AtTimeOfPreviousDataRow = 0
    bidP0AtTimeOfPreviousDataRow = 0
    tradeStats = dict()
    tradeStats['totalSellValue'] = 0
    tradeStats['totalBuyValue'] = 0
    tradeStats['currentPosition'] = 0
    noPredictionForThisRow = 0
    currentPredictedValue = 0
    entryCL = float(args.entryCL) / 100
    exitCL = float(args.exitCL) / 100
    numberOfTimesAskedToEnterTrade = 0
    numberOfTimesAskedToExitTrade = 0
    reasonForTrade = dict()
    reasonForTrade['LTPDoesNotEqualBidP0'] = 0
    reasonForTrade['VolumeDidNotIncreaseSufficientlyDuringBuyAttempt'] = 0
    reasonForTrade['AssumingBuyTradeHappened'] = 0
    reasonForTrade['LTPDoesNotEqualAskP0'] = 0
    reasonForTrade['VolumeDidNotIncreaseSufficientlyDuringSellAttempt'] = 0
    reasonForTrade['AssumingSellTradeHappened'] = 0
    varsAtTimeOfTradeDecision = dict()
    varsAtTimeOfTradeDecision['decision'] = 0
    varsAtTimeOfTradeDecision['bidP0'] = 0
    varsAtTimeOfTradeDecision['qtyTradedAtBidP0'] = 0
    varsAtTimeOfTradeDecision['ttq'] = 0
    varsAtTimeOfTradeDecision['askP0'] = 0
    varsAtTimeOfTradeDecision['qtyTradedAtAskP0'] = 0

    print("Processing the data file for trades :")

    for currentDataRow in dataFile.matrix:  #currentDataRow has the new tick
        if (enterTrade == varsAtTimeOfTradeDecision['decision']
                and enterTrade == 1 and varsAtTimeOfTradeDecision['bidP0'] >=
                float(currentDataRow[colNumberOfData.BidP0])):
            print("Position not lost in the queue")
            if (varsAtTimeOfTradeDecision['bidP0'] == float(
                    currentDataRow[colNumberOfData.LTP])
                    and float(currentDataRow[colNumberOfData.TTQ]) >
                    varsAtTimeOfTradeDecision['ttq']):
                varsAtTimeOfTradeDecision['qtyTradedAtBidP0'] += float(
                    currentDataRow[colNumberOfData.
                                   TTQ]) - varsAtTimeOfTradeDecision['ttq']
        elif (enterTrade == varsAtTimeOfTradeDecision['decision']
              and enterTrade == -1 and varsAtTimeOfTradeDecision['askP0'] <=
              float(currentDataRow[colNumberOfData.AskP0])):
            print("Position not lost in the queue")
            if (varsAtTimeOfTradeDecision['askP0'] == float(
                    currentDataRow[colNumberOfData.LTP])
                    and float(currentDataRow[colNumberOfData.TTQ]) >
                    varsAtTimeOfTradeDecision['ttq']):
                varsAtTimeOfTradeDecision['qtyTradedAtAskP0'] += float(
                    currentDataRow[colNumberOfData.
                                   TTQ]) - varsAtTimeOfTradeDecision['ttq']
        else:
            positionLostInQueue = True

        checkIfPreviousDecisionToEnterOrExitTradeWasSuccessful(
            currentDataRow, varsAtTimeOfTradeDecision, enterTrade, tradeStats,
            reasonForTrade)

        currentTimeStamp = common.convertTimeStampFromStringToFloat(
            currentDataRow[colNumberOfData.TimeStamp])

        try:
            currentPredictedValue = float(
                predictedValuesDict[currentTimeStamp])
        except:
            noPredictionForThisRow += 1

        if (currentPredictedValue > entryCL):
            enterTrade = 1
            numberOfTimesAskedToEnterTrade += 1
        elif (currentPredictedValue < exitCL
              and tradeStats['currentPosition'] > 0):
            numberOfTimesAskedToExitTrade += 1
            enterTrade = -1  # Implies to exit the trade
        else:
            enterTrade = 0  # Implies make no change

        if (positionLostInQueue == True):
            varsAtTimeOfTradeDecision = updateVarsAtTimeOfTradeDecision(
                currentDataRow, enterTrade
            )  # This implies that the position in the queue is lost.

    outputFile = open(outputFileName, "w")
    print("Starting to write: " + outputFileName)
    print("The net results are: " +
          str(tradeStats['totalSellValue'] - tradeStats['totalBuyValue']),
          file=outputFile)
    print("Number of rows for which there is no prediction: " +
          str(noPredictionForThisRow),
          file=outputFile)
    print("Number of times asked to enter trade: " +
          str(numberOfTimesAskedToEnterTrade),
          file=outputFile)
    print("Number of times asked to exit trade: " +
          str(numberOfTimesAskedToExitTrade),
          file=outputFile)
    print(
        "Assumed buy trade did not happen since volume did not increase: " +
        str(reasonForTrade['VolumeDidNotIncreaseSufficientlyDuringBuyAttempt']
            ),
        file=outputFile)
    print("Assumed buy trade did not happen since bidP0 not same as LTP: " +
          str(reasonForTrade['LTPDoesNotEqualBidP0']),
          file=outputFile)
    print("Assumed buy trade happened: " +
          str(reasonForTrade['AssumingBuyTradeHappened']),
          file=outputFile)
    print(
        "Assumed sell trade did not happen since volume did not increase: " +
        str(reasonForTrade['VolumeDidNotIncreaseSufficientlyDuringSellAttempt']
            ),
        file=outputFile)
    print("Assumed sell trade did not happen since bidP0 not same as LTP: " +
          str(reasonForTrade['LTPDoesNotEqualAskP0']),
          file=outputFile)
    print("Assumed sell trade happened: " +
          str(reasonForTrade['AssumingSellTradeHappened']),
          file=outputFile)
    print("The total sell value is: " + str(tradeStats['totalSellValue']),
          file=outputFile)
    print("The total buy value is: " + str(tradeStats['totalBuyValue']),
          file=outputFile)
    try:
        averageSellPrice = tradeStats['totalSellValue'] / reasonForTrade[
            'AssumingSellTradeHappened']
        averageBuyPrice = tradeStats['totalBuyValue'] / reasonForTrade[
            'AssumingBuyTradeHappened']
    except:
        averageSellPrice = 0
        averageBuyPrice = 0
    print("Average sell price per unit is: " + str(averageSellPrice),
          file=outputFile)
    print("Average buy price per unit is: " + str(averageBuyPrice),
          file=outputFile)
    print("The current position: " + str(tradeStats['currentPosition']),
          file=outputFile)
    print("Profit or loss per Qty traded is: " +
          str(averageSellPrice - averageBuyPrice),
          file=outputFile)
    pLPerLot = (averageSellPrice - averageBuyPrice) * 1000
    print("1 lot has 1000 qty's so P/L per lot is: " + str(pLPerLot),
          file=outputFile)
    print("P/L for trading 10 lots is: " + str(pLPerLot * 10), file=outputFile)
Exemple #9
0
def main():
    dataFile.getDataIntoMatrix(args.pd)
    predictedValuesDict = dict()
    getPredictedValuesIntoDict(predictedValuesDict)
    enterTrade = 0
    ttqAtTimeOfPreviousDataRow = 0
    askP0AtTimeOfPreviousDataRow = 0
    bidP0AtTimeOfPreviousDataRow = 0
    tradeStats = dict()
    tradeStats['totalSellValue'] = 0
    tradeStats['totalBuyValue'] = 0
    tradeStats['currentPosition'] = 0
    noPredictionForThisRow = 0
    currentPredictedValue = 0
    entryCL = float(args.entryCL) / 100
    exitCL = float(args.exitCL) / 100
    numberOfTimesAskedToEnterTrade = 0
    numberOfTimesAskedToExitTrade = 0
    reasonForTrade = dict()
    reasonForTrade['LTPDoesNotEqualBidP0'] = 0
    reasonForTrade['VolumeDidNotIncreaseDuringBuyAttempt'] = 0
    reasonForTrade['AssumingBuyTradeHappened'] = 0
    reasonForTrade['LTPDoesNotEqualAskP0'] = 0
    reasonForTrade['VolumeDidNotIncreaseDuringSellAttempt'] = 0
    reasonForTrade['AssumingSellTradeHappened'] = 0

    print("Processing the data file for trades :")

    for currentDataRow in dataFile.matrix:
        checkIfPreviousDecisionToEnterOrExitTradeWasSuccessful(
            currentDataRow, ttqAtTimeOfPreviousDataRow,
            askP0AtTimeOfPreviousDataRow, bidP0AtTimeOfPreviousDataRow,
            enterTrade, tradeStats, reasonForTrade)
        currentTimeStamp = common.convertTimeStampFromStringToFloat(
            currentDataRow[colNumberOfData.TimeStamp])

        try:
            currentPredictedValue = float(
                predictedValuesDict[currentTimeStamp])
        except:
            noPredictionForThisRow += 1

        if (currentPredictedValue > entryCL):
            enterTrade = 1
            numberOfTimesAskedToEnterTrade += 1
        elif (currentPredictedValue < exitCL
              and tradeStats['currentPosition'] > 0):
            numberOfTimesAskedToExitTrade += 1
            enterTrade = -1  # Implies to exit the trade
        else:
            enterTrade = 0  # Implies make no change

        ttqAtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.TTQ])
        askP0AtTimeOfPreviousDataRow = float(
            currentDataRow[colNumberOfData.AskP0])
        bidP0AtTimeOfPreviousDataRow = float(
            currentDataRow[colNumberOfData.BidP0])

    dirName = args.pd.replace('/ro/', '/rs/')
    tradeResultMainDirName = dirName + "/r/"
    if not os.path.exists(tradeResultMainDirName):
        os.mkdir(tradeResultMainDirName)
    tradeResultSubDirectoryName = tradeResultMainDirName + mainExperimentName + "/"
    if not os.path.exists(tradeResultSubDirectoryName):
        os.mkdir(tradeResultSubDirectoryName)
    fileName = tradeResultSubDirectoryName + experimentName + initialFileName + ".result"
    outputFile = open(fileName, "w")

    print("Starting to write: " + fileName)
    print("The net results are: " +
          str(tradeStats['totalSellValue'] - tradeStats['totalBuyValue']),
          file=outputFile)
    print("Number of rows for which there is no prediction: " +
          str(noPredictionForThisRow),
          file=outputFile)
    print("Number of times asked to enter trade: " +
          str(numberOfTimesAskedToEnterTrade),
          file=outputFile)
    print("Number of times asked to exit trade: " +
          str(numberOfTimesAskedToExitTrade),
          file=outputFile)
    print("Assumed buy trade did not happen since volume did not increase: " +
          str(reasonForTrade['VolumeDidNotIncreaseDuringBuyAttempt']),
          file=outputFile)
    print("Assumed buy trade did not happen since bidP0 not same as LTP: " +
          str(reasonForTrade['LTPDoesNotEqualBidP0']),
          file=outputFile)
    print("Assumed buy trade happened: " +
          str(reasonForTrade['AssumingBuyTradeHappened']),
          file=outputFile)
    print("Assumed sell trade did not happen since volume did not increase: " +
          str(reasonForTrade['VolumeDidNotIncreaseDuringSellAttempt']),
          file=outputFile)
    print("Assumed sell trade did not happen since bidP0 not same as LTP: " +
          str(reasonForTrade['LTPDoesNotEqualAskP0']),
          file=outputFile)
    print("Assumed sell trade happened: " +
          str(reasonForTrade['AssumingSellTradeHappened']),
          file=outputFile)
    print("The total sell value is: " + str(tradeStats['totalSellValue']),
          file=outputFile)
    print("The total buy value is: " + str(tradeStats['totalBuyValue']),
          file=outputFile)
    try:
        averageSellPrice = tradeStats['totalSellValue'] / reasonForTrade[
            'AssumingSellTradeHappened']
        averageBuyPrice = tradeStats['totalBuyValue'] / reasonForTrade[
            'AssumingBuyTradeHappened']
    except:
        averageSellPrice = 0
        averageBuyPrice = 0
    print("Average sell price per unit is: " + str(averageSellPrice),
          file=outputFile)
    print("Average buy price per unit is: " + str(averageBuyPrice),
          file=outputFile)
    print("The current position: " + str(tradeStats['currentPosition']),
          file=outputFile)
    print("Profit or loss per Qty traded is: " +
          str(averageSellPrice - averageBuyPrice),
          file=outputFile)
    pLPerLot = (averageSellPrice - averageBuyPrice) * 1000
    print("1 lot has 1000 qty's so P/L per lot is: " + str(pLPerLot),
          file=outputFile)
    print("P/L for trading 10 lots is: " + str(pLPerLot * 10), file=outputFile)
Exemple #10
0
def main():
    dataFile.getDataIntoMatrix(args.d)
    targetValuesDict = dict()
    getTargetValuesIntoDict(targetValuesDict)
    readOnceAndWrite(initialFileName, targetValuesDict)
Exemple #11
0
Fichier : aGen.py Projet : grmte/ml
def main():
   try:
      attribute.initializeInstDetails(args.iT,args.sP,args.oT,args.rev) 
      if args.i is not None: 
          attribute.checkIfAttributeOutputFileExists(os.path.basename(moduleName),args.n,args.i,args.o,args.m,args.d)
      else:
          attribute.checkIfAttributeOutputFileExists(os.path.basename(moduleName),args.n,args.c,args.o,args.m,args.d)
      if args.rev!= None and args.rev.lower()=="yes":
          dataFile.getSelectedDataIntoMatrix(args.d)
      else:
          if(args.cType == "synthetic"):
              if "For6Levels" not in args.g:
                  dataFile.getDataIntoMatrix(args.d,args.c , level=5)
              else:
                  try:
                      dataFile.getDataIntoMatrix(args.d,args.c, level=5)
                  except:
                      dataFile.getDataIntoMatrix(args.d,args.c, level=6)
          else:
              if "For6Levels" not in args.g:
                  dataFile.getDataIntoMatrix(args.d , level=5)
              else:
                  try:
                      dataFile.getDataIntoMatrix(args.d, level=5)
                  except:
                      dataFile.getDataIntoMatrix(args.d, level=6)

      attribute.initList()
      lHeaderColumnNamesList = userModule.extractAttributeFromDataMatrix(args)
      if args.i is not None:
          fileName = attribute.getOutputFileNameFromGeneratorName(os.path.basename(moduleName),args.n,args.i,args.o,args.m,args.d )
      else:
          fileName = attribute.getOutputFileNameFromGeneratorName(os.path.basename(moduleName),args.n,args.c,args.o,args.m,args.d )
      print fileName
      attribute.writeToFile(fileName , lHeaderColumnNamesList)
      attribute.callRProgramToConvertToBinary(fileName) 
   except:
      traceback.print_exc()
      e = sys.exc_info()[0]
      print e
      os._exit(-1)
Exemple #12
0
def main():
   dataFile.getDataIntoMatrix(args.pd)
   predictedValuesDict = dict()
   getPredictedValuesIntoDict(predictedValuesDict)
   enterTrade = 0
   ttqAtTimeOfPreviousDataRow = 0
   askP0AtTimeOfPreviousDataRow = 0
   bidP0AtTimeOfPreviousDataRow = 0
   tradeStats = dict()
   tradeStats['totalSellValue'] = 0
   tradeStats['totalBuyValue'] = 0
   tradeStats['currentPosition'] = 0
   noPredictionForThisRow = 0
   currentPredictedValue = 0
   entryCL = float(args.entryCL)/100
   exitCL = float(args.exitCL)/100
   numberOfTimesAskedToEnterTrade = 0
   numberOfTimesAskedToExitTrade = 0
   reasonForTrade = dict()
   reasonForTrade['LTPDoesNotEqualBidP0'] = 0
   reasonForTrade['VolumeDidNotIncreaseDuringBuyAttempt'] = 0
   reasonForTrade['AssumingBuyTradeHappened'] = 0
   reasonForTrade['LTPDoesNotEqualAskP0'] = 0
   reasonForTrade['VolumeDidNotIncreaseDuringSellAttempt'] = 0
   reasonForTrade['AssumingSellTradeHappened'] = 0


   print("Processing the data file for trades :")

   for currentDataRow in dataFile.matrix:
       checkIfPreviousDecisionToEnterOrExitTradeWasSuccessful(currentDataRow,ttqAtTimeOfPreviousDataRow,askP0AtTimeOfPreviousDataRow,bidP0AtTimeOfPreviousDataRow,enterTrade,tradeStats,reasonForTrade)
       currentTimeStamp = common.convertTimeStampFromStringToFloat(currentDataRow[colNumberOfData.TimeStamp])

       try:
           currentPredictedValue = float(predictedValuesDict[currentTimeStamp])
       except:
           noPredictionForThisRow += 1

       if(currentPredictedValue > entryCL):
           enterTrade = 1
           numberOfTimesAskedToEnterTrade += 1
       elif(currentPredictedValue < exitCL and tradeStats['currentPosition'] > 0):
           numberOfTimesAskedToExitTrade += 1
           enterTrade = -1  # Implies to exit the trade
       else:
           enterTrade = 0  # Implies make no change

       ttqAtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.TTQ]) 
       askP0AtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.AskP0])
       bidP0AtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.BidP0])

   dirName = args.pd.replace('/ro/','/rs/')  
   tradeResultMainDirName = dirName+"/r/"
   if not os.path.exists(tradeResultMainDirName):
        os.mkdir(tradeResultMainDirName)
   tradeResultSubDirectoryName =  tradeResultMainDirName + mainExperimentName+"/"
   if not os.path.exists(tradeResultSubDirectoryName):
        os.mkdir(tradeResultSubDirectoryName)
   fileName = tradeResultSubDirectoryName+experimentName+initialFileName+".result" 
   outputFile = open(fileName,"w")

   print("Starting to write: "+fileName)
   print("The net results are: " + str(tradeStats['totalSellValue'] - tradeStats['totalBuyValue']), file = outputFile)    
   print("Number of rows for which there is no prediction: " + str(noPredictionForThisRow), file = outputFile)    
   print("Number of times asked to enter trade: " + str(numberOfTimesAskedToEnterTrade), file = outputFile)    
   print("Number of times asked to exit trade: " + str(numberOfTimesAskedToExitTrade), file = outputFile)    
   print("Assumed buy trade did not happen since volume did not increase: " + str(reasonForTrade['VolumeDidNotIncreaseDuringBuyAttempt']), file = outputFile)
   print("Assumed buy trade did not happen since bidP0 not same as LTP: " + str(reasonForTrade['LTPDoesNotEqualBidP0']), file = outputFile)
   print("Assumed buy trade happened: " + str(reasonForTrade['AssumingBuyTradeHappened']), file = outputFile)
   print("Assumed sell trade did not happen since volume did not increase: " + str(reasonForTrade['VolumeDidNotIncreaseDuringSellAttempt']), file = outputFile)
   print("Assumed sell trade did not happen since bidP0 not same as LTP: " + str(reasonForTrade['LTPDoesNotEqualAskP0']), file = outputFile)
   print("Assumed sell trade happened: " + str(reasonForTrade['AssumingSellTradeHappened']), file = outputFile)
   print("The total sell value is: " + str(tradeStats['totalSellValue']), file = outputFile)
   print("The total buy value is: " + str(tradeStats['totalBuyValue']), file = outputFile)
   try:
       averageSellPrice = tradeStats['totalSellValue']/reasonForTrade['AssumingSellTradeHappened']
       averageBuyPrice = tradeStats['totalBuyValue']/reasonForTrade['AssumingBuyTradeHappened']
   except:
       averageSellPrice = 0 
       averageBuyPrice = 0
   print("Average sell price per unit is: " + str(averageSellPrice), file = outputFile)
   print("Average buy price per unit is: " + str(averageBuyPrice), file = outputFile)
   print("The current position: " + str(tradeStats['currentPosition']), file = outputFile)
   print("Profit or loss per Qty traded is: " + str(averageSellPrice - averageBuyPrice), file = outputFile)
   pLPerLot=(averageSellPrice - averageBuyPrice)* 1000
   print("1 lot has 1000 qty's so P/L per lot is: " + str(pLPerLot), file = outputFile)
   print("P/L for trading 10 lots is: " + str(pLPerLot * 10), file = outputFile)
Exemple #13
0
def main():
    
   dirName = args.pd.replace('/ro/','/rs/')  
   tradeResultMainDirName = dirName+"/r/"
   if not os.path.exists(tradeResultMainDirName):
        os.mkdir(tradeResultMainDirName)
   tradeResultSubDirectoryName =  tradeResultMainDirName + mainExperimentName+"/"
   if not os.path.exists(tradeResultSubDirectoryName):
        os.mkdir(tradeResultSubDirectoryName)
   outputFileName = tradeResultSubDirectoryName+experimentName+initialFileName+".result" 
   
   #if os.path.isfile(outputFileName):
   #    print("The results file already exisits. Delete it to run the program again" + outputFileName)
   #    return 1
   dataFile.getDataIntoMatrix(args.pd)
   predictedValuesDict = dict()
   getPredictedValuesIntoDict(predictedValuesDict)
   enterTrade = 0
   ttqAtTimeOfPreviousDataRow = 0
   askP0AtTimeOfPreviousDataRow = 0
   bidP0AtTimeOfPreviousDataRow = 0
   tradeStats = dict()
   tradeStats['totalSellValue'] = 0
   tradeStats['totalBuyValue'] = 0
   tradeStats['currentPosition'] = 0
   noPredictionForThisRow = 0
   currentPredictedValue = 0
   entryCL = float(args.entryCL)/100
   exitCL = float(args.exitCL)/100
   numberOfTimesAskedToEnterTrade = 0
   numberOfTimesAskedToExitTrade = 0
   reasonForTrade = dict()
   reasonForTrade['LTPDoesNotEqualBidP0'] = 0
   reasonForTrade['VolumeDidNotIncreaseSufficientlyDuringBuyAttempt'] = 0
   reasonForTrade['AssumingBuyTradeHappened'] = 0
   reasonForTrade['LTPDoesNotEqualAskP0'] = 0
   reasonForTrade['VolumeDidNotIncreaseSufficientlyDuringSellAttempt'] = 0
   reasonForTrade['AssumingSellTradeHappened'] = 0
   varsAtTimeOfTradeDecision = dict()
   varsAtTimeOfTradeDecision['decision'] = 0
   varsAtTimeOfTradeDecision['bidP0'] = 0
   varsAtTimeOfTradeDecision['qtyTradedAtBidP0'] = 0
   varsAtTimeOfTradeDecision['ttq'] = 0
   varsAtTimeOfTradeDecision['askP0'] = 0
   varsAtTimeOfTradeDecision['qtyTradedAtAskP0'] = 0

   print("Processing the data file for trades :")

   for currentDataRow in dataFile.matrix: #currentDataRow has the new tick
       if(enterTrade == varsAtTimeOfTradeDecision['decision'] and enterTrade == 1 and varsAtTimeOfTradeDecision['bidP0'] >= float(currentDataRow[colNumberOfData.BidP0])):
           print("Position not lost in the queue")
           if(varsAtTimeOfTradeDecision['bidP0'] == float(currentDataRow[colNumberOfData.LTP]) and float(currentDataRow[colNumberOfData.TTQ]) > varsAtTimeOfTradeDecision['ttq']):
               varsAtTimeOfTradeDecision['qtyTradedAtBidP0'] += float(currentDataRow[colNumberOfData.TTQ]) - varsAtTimeOfTradeDecision['ttq']
       elif(enterTrade == varsAtTimeOfTradeDecision['decision'] and enterTrade == -1 and varsAtTimeOfTradeDecision['askP0'] <= float(currentDataRow[colNumberOfData.AskP0])):
           print("Position not lost in the queue")
           if(varsAtTimeOfTradeDecision['askP0'] == float(currentDataRow[colNumberOfData.LTP]) and float(currentDataRow[colNumberOfData.TTQ]) > varsAtTimeOfTradeDecision['ttq']):
               varsAtTimeOfTradeDecision['qtyTradedAtAskP0'] += float(currentDataRow[colNumberOfData.TTQ]) - varsAtTimeOfTradeDecision['ttq']
       else:
           positionLostInQueue = True

       checkIfPreviousDecisionToEnterOrExitTradeWasSuccessful(currentDataRow,varsAtTimeOfTradeDecision,enterTrade,tradeStats,reasonForTrade)
       
       currentTimeStamp = common.convertTimeStampFromStringToFloat(currentDataRow[colNumberOfData.TimeStamp])

       try:
           currentPredictedValue = float(predictedValuesDict[currentTimeStamp])
       except:
           noPredictionForThisRow += 1

       if(currentPredictedValue > entryCL):
           enterTrade = 1
           numberOfTimesAskedToEnterTrade += 1
       elif(currentPredictedValue < exitCL and tradeStats['currentPosition'] > 0):
           numberOfTimesAskedToExitTrade += 1
           enterTrade = -1  # Implies to exit the trade
       else:
           enterTrade = 0  # Implies make no change
       
       if(positionLostInQueue == True):
           varsAtTimeOfTradeDecision = updateVarsAtTimeOfTradeDecision(currentDataRow,enterTrade)   # This implies that the position in the queue is lost.

    
   outputFile = open(outputFileName,"w")
   print("Starting to write: "+outputFileName)
   print("The net results are: " + str(tradeStats['totalSellValue'] - tradeStats['totalBuyValue']), file = outputFile)    
   print("Number of rows for which there is no prediction: " + str(noPredictionForThisRow), file = outputFile)    
   print("Number of times asked to enter trade: " + str(numberOfTimesAskedToEnterTrade), file = outputFile)    
   print("Number of times asked to exit trade: " + str(numberOfTimesAskedToExitTrade), file = outputFile)    
   print("Assumed buy trade did not happen since volume did not increase: " + str(reasonForTrade['VolumeDidNotIncreaseSufficientlyDuringBuyAttempt']), file = outputFile)
   print("Assumed buy trade did not happen since bidP0 not same as LTP: " + str(reasonForTrade['LTPDoesNotEqualBidP0']), file = outputFile)
   print("Assumed buy trade happened: " + str(reasonForTrade['AssumingBuyTradeHappened']), file = outputFile)
   print("Assumed sell trade did not happen since volume did not increase: " + str(reasonForTrade['VolumeDidNotIncreaseSufficientlyDuringSellAttempt']), file = outputFile)
   print("Assumed sell trade did not happen since bidP0 not same as LTP: " + str(reasonForTrade['LTPDoesNotEqualAskP0']), file = outputFile)
   print("Assumed sell trade happened: " + str(reasonForTrade['AssumingSellTradeHappened']), file = outputFile)
   print("The total sell value is: " + str(tradeStats['totalSellValue']), file = outputFile)
   print("The total buy value is: " + str(tradeStats['totalBuyValue']), file = outputFile)
   try:
       averageSellPrice = tradeStats['totalSellValue']/reasonForTrade['AssumingSellTradeHappened']
       averageBuyPrice = tradeStats['totalBuyValue']/reasonForTrade['AssumingBuyTradeHappened']
   except:
       averageSellPrice = 0 
       averageBuyPrice = 0
   print("Average sell price per unit is: " + str(averageSellPrice), file = outputFile)
   print("Average buy price per unit is: " + str(averageBuyPrice), file = outputFile)
   print("The current position: " + str(tradeStats['currentPosition']), file = outputFile)
   print("Profit or loss per Qty traded is: " + str(averageSellPrice - averageBuyPrice), file = outputFile)
   pLPerLot=(averageSellPrice - averageBuyPrice)* 1000
   print("1 lot has 1000 qty's so P/L per lot is: " + str(pLPerLot), file = outputFile)
   print("P/L for trading 10 lots is: " + str(pLPerLot * 10), file = outputFile)
Exemple #14
0
def main():
   attribute.initList()
   dataFile.getDataIntoMatrix(args.pd)
   predictedValuesDict = dict()
   getPredictedValuesIntoDict(predictedValuesDict)
   enterTradeShort = 0
   enterTradeLong = 0
   ttqAtTimeOfPreviousDataRow = 0
   askP0AtTimeOfPreviousDataRow = 0
   bidP0AtTimeOfPreviousDataRow = 0
   askQ0AtTimeOfPreviousDataRow = 0
   bidQ0AtTimeOfPreviousDataRow = 0
   tradeStats = dict()
   tradeStats['totalSellValueShort'] = 0
   tradeStats['totalBuyValueShort'] = 0
   tradeStats['currentPositionShort'] = 0
   tradeStats['totalSellValueLong'] = 0
   tradeStats['totalBuyValueLong'] = 0
   tradeStats['currentPositionLong'] = 0
   noPredictionForThisRow = 0
   currentPredictedValueShort = 0
   currentPredictedValueLong = 0
   entryCL = float(args.entryCL)/100
   exitCL = float(args.exitCL)/100
 #  entryCLCutoff = float(args.entryCLCutoff)
 #  exitCLCutoff = float(args.exitCLCutoff)
   numberOfTimesAskedToEnterTradeShort = 0
   numberOfTimesAskedToEnterTradeLong = 0
   numberOfTimesAskedToExitTradeShort = 0
   numberOfTimesAskedToExitTradeLong = 0
   reasonForTrade = dict()
   reasonForTrade['LTPDoesNotEqualBidP0Short'] = 0
   reasonForTrade['LTPDoesNotEqualAskP0Short'] = 0
   reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptShort'] = 0
   reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptLong'] = 0
   reasonForTrade['AssumingBuyTradeHappenedShort'] = 0
   reasonForTrade['AssumingBuyTradeHappenedLong'] = 0
   reasonForTrade['LTPDoesNotEqualAskP0Long'] = 0
   reasonForTrade['LTPDoesNotEqualBidP0Long'] = 0
   reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptShort'] = 0
   reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptLong'] = 0
   reasonForTrade['AssumingSellTradeHappenedShort'] = 0
   reasonForTrade['AssumingSellTradeHappenedLong'] = 0
   currentIndex = 0
   print("Processing the data file for trades :")
   attribute.initList()
   for currentDataRow in dataFile.matrix:
       
       lReturnList = checkIfPreviousDecisionToEnterOrExitTradeWasSuccessful(currentDataRow,ttqAtTimeOfPreviousDataRow,askP0AtTimeOfPreviousDataRow,bidP0AtTimeOfPreviousDataRow,askQ0AtTimeOfPreviousDataRow , bidQ0AtTimeOfPreviousDataRow , enterTradeShort,enterTradeLong,tradeStats,reasonForTrade )

       lReasonForTradingOrNotTradingShort = lReturnList[0]
       lReasonForTradingOrNotTradingLong = lReturnList[1] 
       lDummyBidQ0 = lReturnList[2]
       lDummyAskQ0 = lReturnList[3]
       lDummyTTQForBuy = lReturnList[4]
       lDummyTTQForSell = lReturnList[5]
       if currentIndex > 0:
           attribute.aList[currentIndex-1][0] = currentTimeStamp
           attribute.aList[currentIndex-1][1] = tradeStats['currentPositionLong']
           attribute.aList[currentIndex-1][2] = tradeStats['currentPositionShort']
           listOfStringsToPrint = [ str(bidQ0AtTimeOfPreviousDataRow) , str(bidP0AtTimeOfPreviousDataRow) , str(askP0AtTimeOfPreviousDataRow) , str(askQ0AtTimeOfPreviousDataRow) , str(ttqAtTimeOfPreviousDataRow) , str(ltpAtTimeOfPreviousDataRow) , str(currentPredictedValueShort) , str(enterTradeShort) ,lReasonForTradingOrNotTradingShort , str(currentPredictedValueLong) , str(enterTradeLong) ,lReasonForTradingOrNotTradingLong , str(reasonForTrade['AssumingBuyTradeHappenedShort']),str(reasonForTrade['AssumingBuyTradeHappenedLong']),str(reasonForTrade['AssumingSellTradeHappenedShort']),str(reasonForTrade['AssumingSellTradeHappenedLong']),str(lDummyBidQ0),str(lDummyAskQ0),str(lDummyTTQForBuy),str(lDummyTTQForSell)]
           attribute.aList[currentIndex-1][3] =  ";".join(listOfStringsToPrint)
       currentTimeStamp = common.convertTimeStampFromStringToFloat(currentDataRow[colNumberOfData.TimeStamp])

       try:
           currentPredictedValueShort = (float(predictedValuesDict[currentTimeStamp][-2]) + float(predictedValuesDict[currentTimeStamp][-1])) 
           currentPredictedValueLong = (float(predictedValuesDict[currentTimeStamp][2]) + float(predictedValuesDict[currentTimeStamp][1])) 
       except:
           noPredictionForThisRow += 1

       #short decisions
       if(currentPredictedValueShort > entryCL):
           enterTradeShort = 1
           numberOfTimesAskedToEnterTradeShort += 1
       elif(currentPredictedValueShort < exitCL and tradeStats['currentPositionShort'] > 0):
           numberOfTimesAskedToExitTradeShort += 1
           enterTradeShort = -1  # Implies to exit the trade
       else:
           enterTradeShort = 0  # Implies make no change
           
#       if enterTradeShort == 1:
#           if currentPredictedValue <= entryCLCutoff:
#               enterTrade = 0
#       if enterTrade == -1:
#           if currentPredictedValue >= exitCLCutoff:
#               enterTrade = 0
               
       #long decisions
       if(currentPredictedValueLong > entryCL):
           enterTradeLong = 1
           numberOfTimesAskedToEnterTradeLong += 1
       elif(currentPredictedValueLong < exitCL and tradeStats['currentPositionLong'] > 0):
           numberOfTimesAskedToExitTradeLong += 1
           enterTradeLong = -1  # Implies to exit the trade
       else:
           enterTradeLong = 0  # Implies make no change
       
       ttqAtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.TTQ]) 
       askP0AtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.AskP0])
       bidP0AtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.BidP0])
       askQ0AtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.AskQ0])
       bidQ0AtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.BidQ0])
       ltpAtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.LTP])
       currentIndex = currentIndex + 1

# Squaring off if some open position there   
   if tradeStats['currentPositionLong'] > 0:
       reasonForTrade['AssumingSellTradeHappenedLong'] += tradeStats['currentPositionLong']
       tradeStats['totalSellValueLong'] += tradeStats['currentPositionLong'] * (bidP0AtTimeOfPreviousDataRow)
       tradeStats['currentPositionLong'] = 0
       lReasonForTradingOrNotTradingLong = 'CloseSell(Hitting)'
   elif tradeStats['currentPositionShort'] > 0:
       reasonForTrade['AssumingBuyTradeHappenedShort'] += tradeStats['currentPositionShort']
       tradeStats['totalBuyValueShort'] += tradeStats['currentPositionShort'] * (askP0AtTimeOfPreviousDataRow)
       tradeStats['currentPositionShort'] = 0
       lReasonForTradingOrNotTradingLong = 'CloseBuy(Hitting)'

   attribute.aList[currentIndex-1][0] = currentTimeStamp
   attribute.aList[currentIndex-1][1] = tradeStats['currentPositionLong']
   attribute.aList[currentIndex-1][2] = tradeStats['currentPositionShort']
   listOfStringsToPrint = [ str(bidQ0AtTimeOfPreviousDataRow) , str(bidP0AtTimeOfPreviousDataRow) , str(askP0AtTimeOfPreviousDataRow) , str(askQ0AtTimeOfPreviousDataRow) , str(ttqAtTimeOfPreviousDataRow) , str(ltpAtTimeOfPreviousDataRow) , str(currentPredictedValueShort) , str(enterTradeShort) , "" , str(currentPredictedValueLong) , str(enterTradeLong) ,"" , str(reasonForTrade['AssumingBuyTradeHappenedShort']),str(reasonForTrade['AssumingBuyTradeHappenedLong']),str(reasonForTrade['AssumingSellTradeHappenedShort']),str(reasonForTrade['AssumingSellTradeHappenedLong']),str(lDummyBidQ0),str(lDummyAskQ0),str(lDummyTTQForBuy),str(lDummyTTQForSell)]
   attribute.aList[currentIndex-1][3] =  ";".join(listOfStringsToPrint) 
   dirName = args.pd.replace('/ro/','/rs/')
   tradeLogMainDirName = dirName+"/t/"
   if not os.path.exists(tradeLogMainDirName):
        os.mkdir(tradeLogMainDirName)
   tradeLogSubDirectoryName =  tradeLogMainDirName + mainExperimentName+"/"
   if not os.path.exists(tradeLogSubDirectoryName):
        os.mkdir(tradeLogSubDirectoryName)
   fileName = tradeLogSubDirectoryName+experimentName+initialFileName+".trade" 
   lHeaderColumnNamesList  = ['TimeStamp','CurrentPositionLong','CurrentPositionShort','BidQ0','BidP0','AskP0','AskQ0','TTQ','LTP','CurPredValueShort','EnterTradeShort','ReasonForTradingOrNotTradingShort','CurPredValueLong','EnterTradeLong','ReasonForTradingOrNotTradingLong','totalBuyTradeShort','totalBuyLong','totalSellShort','totalSellLong','DummyBidQ0','DummyAskQ0','DummyTTQChangeForSell','DummyTTQChangeForBuy']
   attribute.writeToFile(fileName , lHeaderColumnNamesList)

   tradeResultMainDirName = dirName+"/r/"
   if not os.path.exists(tradeResultMainDirName):
        os.mkdir(tradeResultMainDirName)
   tradeResultSubDirectoryName =  tradeResultMainDirName + mainExperimentName+"/"
   if not os.path.exists(tradeResultSubDirectoryName):
        os.mkdir(tradeResultSubDirectoryName)
   fileName = tradeResultSubDirectoryName+experimentName+initialFileName+".result" 
   outputFile = open(fileName,"w")
 
   #changed file write to modify it to Short Long version
   print("Starting to write: "+fileName)
   print("The net results for Short are: " + str(tradeStats['totalSellValueShort'] - tradeStats['totalBuyValueShort']), file = outputFile)
   print("The net results for Long are: " + str(tradeStats['totalSellValueLong'] - tradeStats['totalBuyValueLong']), file = outputFile)
   print("Number of rows for which there is no prediction: " + str(noPredictionForThisRow), file = outputFile)    
   print("Number of times asked to enter trade Short: " + str(numberOfTimesAskedToEnterTradeShort), file = outputFile)    
   print("Number of times asked to enter trade Long: " + str(numberOfTimesAskedToEnterTradeLong), file = outputFile)    
   print("Number of times asked to exit trade Short: " + str(numberOfTimesAskedToExitTradeShort), file = outputFile)
   print("Number of times asked to exit trade Long: " + str(numberOfTimesAskedToExitTradeLong), file = outputFile)
   print("Assumed close buy trade did not happen since volume did not increase: " + str(reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptShort']), file = outputFile)
   print("Assumed open buy trade did not happen since volume did not increase: " + str(reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptLong']), file = outputFile)
   print("Assumed close buy trade did not happen since bidP0 not same as LTP: " + str(reasonForTrade['LTPDoesNotEqualBidP0Short']), file = outputFile)
   print("Assumed open buy trade did not happen since bidP0 not same as LTP: " + str(reasonForTrade['LTPDoesNotEqualBidP0Long']), file = outputFile)
   print("Assumed close buy trade happened: " + str(reasonForTrade['AssumingBuyTradeHappenedShort']), file = outputFile)
   print("Assumed open buy trade happened: " + str(reasonForTrade['AssumingBuyTradeHappenedLong']), file = outputFile)
   print("Assumed open sell trade did not happen since volume did not increase: " + str(reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptShort']), file = outputFile)
   print("Assumed close sell trade did not happen since volume did not increase: " + str(reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptLong']), file = outputFile)
   print("Assumed open sell trade did not happen since bidP0 not same as LTP: " + str(reasonForTrade['LTPDoesNotEqualAskP0Short']), file = outputFile)
   print("Assumed close sell trade did not happen since bidP0 not same as LTP: " + str(reasonForTrade['LTPDoesNotEqualAskP0Long']), file = outputFile)
   print("Assumed open sell trade happened: " + str(reasonForTrade['AssumingSellTradeHappenedShort']), file = outputFile)
   print("Assumed close sell trade happened: " + str(reasonForTrade['AssumingSellTradeHappenedLong']), file = outputFile)
   print("The total open sell value is: " + str(tradeStats['totalSellValueShort']), file = outputFile)
   print("The total close sell value is: " + str(tradeStats['totalSellValueLong']), file = outputFile)
   print("The total close buy value is: " + str(tradeStats['totalBuyValueShort']), file = outputFile)
   print("The total open buy value is: " + str(tradeStats['totalBuyValueLong']), file = outputFile)

   try:
       averageOpenSellPrice = tradeStats['totalSellValueShort']/reasonForTrade['AssumingSellTradeHappenedShort']
       averageCloseBuyPrice = tradeStats['totalBuyValueShort']/reasonForTrade['AssumingBuyTradeHappenedShort']
   except:
       averageOpenSellPrice = 0 
       averageCloseBuyPrice = 0
   try:
       averageCloseSellPrice = tradeStats['totalSellValueLong']/reasonForTrade['AssumingSellTradeHappenedLong']
       averageOpenBuyPrice = tradeStats['totalBuyValueLong']/reasonForTrade['AssumingBuyTradeHappenedLong']
   except:
       averageCloseSellPrice = 0
       averageOpenBuyPrice = 0 

   print("Average open sell price per unit is: " + str(averageOpenSellPrice), file = outputFile)
   print("Average close sell price per unit is: " + str(averageCloseSellPrice), file = outputFile)
   print("Average open buy price per unit is: " + str(averageOpenBuyPrice), file = outputFile)
   print("Average close buy price per unit is: " + str(averageCloseBuyPrice), file = outputFile)
   print("The current position Short: " + str(tradeStats['currentPositionShort']), file = outputFile)
   print("The current position Long: " + str(tradeStats['currentPositionLong']), file = outputFile)
   print("Profit or loss per Qty traded Short is: " + str(averageOpenSellPrice - averageCloseBuyPrice), file = outputFile)
   print("Profit or loss per Qty traded Long is: " + str(averageCloseSellPrice - averageOpenBuyPrice), file = outputFile)
   pLPerLotShort=(averageOpenSellPrice - averageCloseBuyPrice)* 1000
   pLPerLotLong=(averageCloseSellPrice - averageOpenBuyPrice)* 1000
   print("1 lot has 1000 qty's so P/L Short per lot is: " + str(pLPerLotShort), file = outputFile)
   print("1 lot has 1000 qty's so P/L Long per lot is: " + str(pLPerLotLong), file = outputFile)
   print("P/L for Short trading 10 lots is: " + str(pLPerLotShort * 10), file = outputFile)
   print("P/L for Long trading 10 lots is: " + str(pLPerLotLong * 10), file = outputFile)
Exemple #15
0
def main():
    attribute.initList()
    dataFile.getDataIntoMatrix(args.pd)
    predictedValuesDict = dict()
    getPredictedValuesIntoDict(predictedValuesDict)
    enterTradeShort = 0
    enterTradeLong = 0
    ttqAtTimeOfPreviousDataRow = 0
    askP0AtTimeOfPreviousDataRow = 0
    bidP0AtTimeOfPreviousDataRow = 0
    askQ0AtTimeOfPreviousDataRow = 0
    bidQ0AtTimeOfPreviousDataRow = 0
    tradeStats = dict()
    tradeStats['totalSellValueShort'] = 0
    tradeStats['totalBuyValueShort'] = 0
    tradeStats['currentPositionShort'] = 0
    tradeStats['totalSellValueLong'] = 0
    tradeStats['totalBuyValueLong'] = 0
    tradeStats['currentPositionLong'] = 0
    noPredictionForThisRow = 0
    currentPredictedValueShort = 0
    currentPredictedValueLong = 0
    entryCL = float(args.entryCL) / 100
    exitCL = float(args.exitCL) / 100
    #  entryCLCutoff = float(args.entryCLCutoff)
    #  exitCLCutoff = float(args.exitCLCutoff)
    numberOfTimesAskedToEnterTradeShort = 0
    numberOfTimesAskedToEnterTradeLong = 0
    numberOfTimesAskedToExitTradeShort = 0
    numberOfTimesAskedToExitTradeLong = 0
    reasonForTrade = dict()
    reasonForTrade['LTPDoesNotEqualBidP0Short'] = 0
    reasonForTrade['LTPDoesNotEqualAskP0Short'] = 0
    reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptShort'] = 0
    reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptLong'] = 0
    reasonForTrade['AssumingBuyTradeHappenedShort'] = 0
    reasonForTrade['AssumingBuyTradeHappenedLong'] = 0
    reasonForTrade['LTPDoesNotEqualAskP0Long'] = 0
    reasonForTrade['LTPDoesNotEqualBidP0Long'] = 0
    reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptShort'] = 0
    reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptLong'] = 0
    reasonForTrade['AssumingSellTradeHappenedShort'] = 0
    reasonForTrade['AssumingSellTradeHappenedLong'] = 0
    currentIndex = 0
    print("Processing the data file for trades :")
    attribute.initList()
    for currentDataRow in dataFile.matrix:

        lReturnList = checkIfPreviousDecisionToEnterOrExitTradeWasSuccessful(
            currentDataRow, ttqAtTimeOfPreviousDataRow,
            askP0AtTimeOfPreviousDataRow, bidP0AtTimeOfPreviousDataRow,
            askQ0AtTimeOfPreviousDataRow, bidQ0AtTimeOfPreviousDataRow,
            enterTradeShort, enterTradeLong, tradeStats, reasonForTrade)

        lReasonForTradingOrNotTradingShort = lReturnList[0]
        lReasonForTradingOrNotTradingLong = lReturnList[1]
        lDummyBidQ0 = lReturnList[2]
        lDummyAskQ0 = lReturnList[3]
        lDummyTTQForBuy = lReturnList[4]
        lDummyTTQForSell = lReturnList[5]
        if currentIndex > 0:
            attribute.aList[currentIndex - 1][0] = currentTimeStamp
            attribute.aList[currentIndex -
                            1][1] = tradeStats['currentPositionLong']
            attribute.aList[currentIndex -
                            1][2] = tradeStats['currentPositionShort']
            listOfStringsToPrint = [
                str(bidQ0AtTimeOfPreviousDataRow),
                str(bidP0AtTimeOfPreviousDataRow),
                str(askP0AtTimeOfPreviousDataRow),
                str(askQ0AtTimeOfPreviousDataRow),
                str(ttqAtTimeOfPreviousDataRow),
                str(ltpAtTimeOfPreviousDataRow),
                str(currentPredictedValueShort),
                str(enterTradeShort), lReasonForTradingOrNotTradingShort,
                str(currentPredictedValueLong),
                str(enterTradeLong), lReasonForTradingOrNotTradingLong,
                str(reasonForTrade['AssumingBuyTradeHappenedShort']),
                str(reasonForTrade['AssumingBuyTradeHappenedLong']),
                str(reasonForTrade['AssumingSellTradeHappenedShort']),
                str(reasonForTrade['AssumingSellTradeHappenedLong']),
                str(lDummyBidQ0),
                str(lDummyAskQ0),
                str(lDummyTTQForBuy),
                str(lDummyTTQForSell)
            ]
            attribute.aList[currentIndex -
                            1][3] = ";".join(listOfStringsToPrint)
        currentTimeStamp = common.convertTimeStampFromStringToFloat(
            currentDataRow[colNumberOfData.TimeStamp])

        try:
            currentPredictedValueShort = (
                float(predictedValuesDict[currentTimeStamp][-2]) +
                float(predictedValuesDict[currentTimeStamp][-1]))
            currentPredictedValueLong = (
                float(predictedValuesDict[currentTimeStamp][2]) +
                float(predictedValuesDict[currentTimeStamp][1]))
        except:
            noPredictionForThisRow += 1

        #short decisions
        if (currentPredictedValueShort > entryCL):
            enterTradeShort = 1
            numberOfTimesAskedToEnterTradeShort += 1
        elif (currentPredictedValueShort < exitCL
              and tradeStats['currentPositionShort'] > 0):
            numberOfTimesAskedToExitTradeShort += 1
            enterTradeShort = -1  # Implies to exit the trade
        else:
            enterTradeShort = 0  # Implies make no change

#       if enterTradeShort == 1:
#           if currentPredictedValue <= entryCLCutoff:
#               enterTrade = 0
#       if enterTrade == -1:
#           if currentPredictedValue >= exitCLCutoff:
#               enterTrade = 0

#long decisions
        if (currentPredictedValueLong > entryCL):
            enterTradeLong = 1
            numberOfTimesAskedToEnterTradeLong += 1
        elif (currentPredictedValueLong < exitCL
              and tradeStats['currentPositionLong'] > 0):
            numberOfTimesAskedToExitTradeLong += 1
            enterTradeLong = -1  # Implies to exit the trade
        else:
            enterTradeLong = 0  # Implies make no change

        ttqAtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.TTQ])
        askP0AtTimeOfPreviousDataRow = float(
            currentDataRow[colNumberOfData.AskP0])
        bidP0AtTimeOfPreviousDataRow = float(
            currentDataRow[colNumberOfData.BidP0])
        askQ0AtTimeOfPreviousDataRow = float(
            currentDataRow[colNumberOfData.AskQ0])
        bidQ0AtTimeOfPreviousDataRow = float(
            currentDataRow[colNumberOfData.BidQ0])
        ltpAtTimeOfPreviousDataRow = float(currentDataRow[colNumberOfData.LTP])
        currentIndex = currentIndex + 1


# Squaring off if some open position there
    if tradeStats['currentPositionLong'] > 0:
        reasonForTrade['AssumingSellTradeHappenedLong'] += tradeStats[
            'currentPositionLong']
        tradeStats['totalSellValueLong'] += tradeStats[
            'currentPositionLong'] * (bidP0AtTimeOfPreviousDataRow)
        tradeStats['currentPositionLong'] = 0
        lReasonForTradingOrNotTradingLong = 'CloseSell(Hitting)'
    elif tradeStats['currentPositionShort'] > 0:
        reasonForTrade['AssumingBuyTradeHappenedShort'] += tradeStats[
            'currentPositionShort']
        tradeStats['totalBuyValueShort'] += tradeStats[
            'currentPositionShort'] * (askP0AtTimeOfPreviousDataRow)
        tradeStats['currentPositionShort'] = 0
        lReasonForTradingOrNotTradingLong = 'CloseBuy(Hitting)'

    attribute.aList[currentIndex - 1][0] = currentTimeStamp
    attribute.aList[currentIndex - 1][1] = tradeStats['currentPositionLong']
    attribute.aList[currentIndex - 1][2] = tradeStats['currentPositionShort']
    listOfStringsToPrint = [
        str(bidQ0AtTimeOfPreviousDataRow),
        str(bidP0AtTimeOfPreviousDataRow),
        str(askP0AtTimeOfPreviousDataRow),
        str(askQ0AtTimeOfPreviousDataRow),
        str(ttqAtTimeOfPreviousDataRow),
        str(ltpAtTimeOfPreviousDataRow),
        str(currentPredictedValueShort),
        str(enterTradeShort), "",
        str(currentPredictedValueLong),
        str(enterTradeLong), "",
        str(reasonForTrade['AssumingBuyTradeHappenedShort']),
        str(reasonForTrade['AssumingBuyTradeHappenedLong']),
        str(reasonForTrade['AssumingSellTradeHappenedShort']),
        str(reasonForTrade['AssumingSellTradeHappenedLong']),
        str(lDummyBidQ0),
        str(lDummyAskQ0),
        str(lDummyTTQForBuy),
        str(lDummyTTQForSell)
    ]
    attribute.aList[currentIndex - 1][3] = ";".join(listOfStringsToPrint)
    dirName = args.pd.replace('/ro/', '/rs/')
    tradeLogMainDirName = dirName + "/t/"
    if not os.path.exists(tradeLogMainDirName):
        os.mkdir(tradeLogMainDirName)
    tradeLogSubDirectoryName = tradeLogMainDirName + mainExperimentName + "/"
    if not os.path.exists(tradeLogSubDirectoryName):
        os.mkdir(tradeLogSubDirectoryName)
    fileName = tradeLogSubDirectoryName + experimentName + initialFileName + ".trade"
    lHeaderColumnNamesList = [
        'TimeStamp', 'CurrentPositionLong', 'CurrentPositionShort', 'BidQ0',
        'BidP0', 'AskP0', 'AskQ0', 'TTQ', 'LTP', 'CurPredValueShort',
        'EnterTradeShort', 'ReasonForTradingOrNotTradingShort',
        'CurPredValueLong', 'EnterTradeLong',
        'ReasonForTradingOrNotTradingLong', 'totalBuyTradeShort',
        'totalBuyLong', 'totalSellShort', 'totalSellLong', 'DummyBidQ0',
        'DummyAskQ0', 'DummyTTQChangeForSell', 'DummyTTQChangeForBuy'
    ]
    attribute.writeToFile(fileName, lHeaderColumnNamesList)

    tradeResultMainDirName = dirName + "/r/"
    if not os.path.exists(tradeResultMainDirName):
        os.mkdir(tradeResultMainDirName)
    tradeResultSubDirectoryName = tradeResultMainDirName + mainExperimentName + "/"
    if not os.path.exists(tradeResultSubDirectoryName):
        os.mkdir(tradeResultSubDirectoryName)
    fileName = tradeResultSubDirectoryName + experimentName + initialFileName + ".result"
    outputFile = open(fileName, "w")

    #changed file write to modify it to Short Long version
    print("Starting to write: " + fileName)
    print("The net results for Short are: " +
          str(tradeStats['totalSellValueShort'] -
              tradeStats['totalBuyValueShort']),
          file=outputFile)
    print("The net results for Long are: " +
          str(tradeStats['totalSellValueLong'] -
              tradeStats['totalBuyValueLong']),
          file=outputFile)
    print("Number of rows for which there is no prediction: " +
          str(noPredictionForThisRow),
          file=outputFile)
    print("Number of times asked to enter trade Short: " +
          str(numberOfTimesAskedToEnterTradeShort),
          file=outputFile)
    print("Number of times asked to enter trade Long: " +
          str(numberOfTimesAskedToEnterTradeLong),
          file=outputFile)
    print("Number of times asked to exit trade Short: " +
          str(numberOfTimesAskedToExitTradeShort),
          file=outputFile)
    print("Number of times asked to exit trade Long: " +
          str(numberOfTimesAskedToExitTradeLong),
          file=outputFile)
    print(
        "Assumed close buy trade did not happen since volume did not increase: "
        + str(reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptShort']),
        file=outputFile)
    print(
        "Assumed open buy trade did not happen since volume did not increase: "
        + str(reasonForTrade['VolumeDidNotIncreaseDuringBuyAttemptLong']),
        file=outputFile)
    print(
        "Assumed close buy trade did not happen since bidP0 not same as LTP: "
        + str(reasonForTrade['LTPDoesNotEqualBidP0Short']),
        file=outputFile)
    print(
        "Assumed open buy trade did not happen since bidP0 not same as LTP: " +
        str(reasonForTrade['LTPDoesNotEqualBidP0Long']),
        file=outputFile)
    print("Assumed close buy trade happened: " +
          str(reasonForTrade['AssumingBuyTradeHappenedShort']),
          file=outputFile)
    print("Assumed open buy trade happened: " +
          str(reasonForTrade['AssumingBuyTradeHappenedLong']),
          file=outputFile)
    print(
        "Assumed open sell trade did not happen since volume did not increase: "
        + str(reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptShort']),
        file=outputFile)
    print(
        "Assumed close sell trade did not happen since volume did not increase: "
        + str(reasonForTrade['VolumeDidNotIncreaseDuringSellAttemptLong']),
        file=outputFile)
    print(
        "Assumed open sell trade did not happen since bidP0 not same as LTP: "
        + str(reasonForTrade['LTPDoesNotEqualAskP0Short']),
        file=outputFile)
    print(
        "Assumed close sell trade did not happen since bidP0 not same as LTP: "
        + str(reasonForTrade['LTPDoesNotEqualAskP0Long']),
        file=outputFile)
    print("Assumed open sell trade happened: " +
          str(reasonForTrade['AssumingSellTradeHappenedShort']),
          file=outputFile)
    print("Assumed close sell trade happened: " +
          str(reasonForTrade['AssumingSellTradeHappenedLong']),
          file=outputFile)
    print("The total open sell value is: " +
          str(tradeStats['totalSellValueShort']),
          file=outputFile)
    print("The total close sell value is: " +
          str(tradeStats['totalSellValueLong']),
          file=outputFile)
    print("The total close buy value is: " +
          str(tradeStats['totalBuyValueShort']),
          file=outputFile)
    print("The total open buy value is: " +
          str(tradeStats['totalBuyValueLong']),
          file=outputFile)

    try:
        averageOpenSellPrice = tradeStats[
            'totalSellValueShort'] / reasonForTrade[
                'AssumingSellTradeHappenedShort']
        averageCloseBuyPrice = tradeStats[
            'totalBuyValueShort'] / reasonForTrade[
                'AssumingBuyTradeHappenedShort']
    except:
        averageOpenSellPrice = 0
        averageCloseBuyPrice = 0
    try:
        averageCloseSellPrice = tradeStats[
            'totalSellValueLong'] / reasonForTrade[
                'AssumingSellTradeHappenedLong']
        averageOpenBuyPrice = tradeStats['totalBuyValueLong'] / reasonForTrade[
            'AssumingBuyTradeHappenedLong']
    except:
        averageCloseSellPrice = 0
        averageOpenBuyPrice = 0

    print("Average open sell price per unit is: " + str(averageOpenSellPrice),
          file=outputFile)
    print("Average close sell price per unit is: " +
          str(averageCloseSellPrice),
          file=outputFile)
    print("Average open buy price per unit is: " + str(averageOpenBuyPrice),
          file=outputFile)
    print("Average close buy price per unit is: " + str(averageCloseBuyPrice),
          file=outputFile)
    print("The current position Short: " +
          str(tradeStats['currentPositionShort']),
          file=outputFile)
    print("The current position Long: " +
          str(tradeStats['currentPositionLong']),
          file=outputFile)
    print("Profit or loss per Qty traded Short is: " +
          str(averageOpenSellPrice - averageCloseBuyPrice),
          file=outputFile)
    print("Profit or loss per Qty traded Long is: " +
          str(averageCloseSellPrice - averageOpenBuyPrice),
          file=outputFile)
    pLPerLotShort = (averageOpenSellPrice - averageCloseBuyPrice) * 1000
    pLPerLotLong = (averageCloseSellPrice - averageOpenBuyPrice) * 1000
    print("1 lot has 1000 qty's so P/L Short per lot is: " +
          str(pLPerLotShort),
          file=outputFile)
    print("1 lot has 1000 qty's so P/L Long per lot is: " + str(pLPerLotLong),
          file=outputFile)
    print("P/L for Short trading 10 lots is: " + str(pLPerLotShort * 10),
          file=outputFile)
    print("P/L for Long trading 10 lots is: " + str(pLPerLotLong * 10),
          file=outputFile)
def main():
    dataFile.getDataIntoMatrix(args.d)
    targetValuesDict = dict()
    getTargetValuesIntoDict(targetValuesDict)
    readOnceAndWrite(initialFileName, targetValuesDict)
Exemple #17
0
Fichier : aGen.py Projet : grmte/ml
def main():
    try:
        attribute.initializeInstDetails(args.iT, args.sP, args.oT, args.rev)
        if args.i is not None:
            attribute.checkIfAttributeOutputFileExists(
                os.path.basename(moduleName), args.n, args.i, args.o, args.m,
                args.d)
        else:
            attribute.checkIfAttributeOutputFileExists(
                os.path.basename(moduleName), args.n, args.c, args.o, args.m,
                args.d)
        if args.rev != None and args.rev.lower() == "yes":
            dataFile.getSelectedDataIntoMatrix(args.d)
        else:
            if (args.cType == "synthetic"):
                if "For6Levels" not in args.g:
                    dataFile.getDataIntoMatrix(args.d, args.c, level=5)
                else:
                    try:
                        dataFile.getDataIntoMatrix(args.d, args.c, level=5)
                    except:
                        dataFile.getDataIntoMatrix(args.d, args.c, level=6)
            else:
                if "For6Levels" not in args.g:
                    dataFile.getDataIntoMatrix(args.d, level=5)
                else:
                    try:
                        dataFile.getDataIntoMatrix(args.d, level=5)
                    except:
                        dataFile.getDataIntoMatrix(args.d, level=6)

        attribute.initList()
        lHeaderColumnNamesList = userModule.extractAttributeFromDataMatrix(
            args)
        if args.i is not None:
            fileName = attribute.getOutputFileNameFromGeneratorName(
                os.path.basename(moduleName), args.n, args.i, args.o, args.m,
                args.d)
        else:
            fileName = attribute.getOutputFileNameFromGeneratorName(
                os.path.basename(moduleName), args.n, args.c, args.o, args.m,
                args.d)
        print fileName
        attribute.writeToFile(fileName, lHeaderColumnNamesList)
        attribute.callRProgramToConvertToBinary(fileName)
    except:
        traceback.print_exc()
        e = sys.exc_info()[0]
        print e
        os._exit(-1)