コード例 #1
0
def primeDesireCache(step, startKey = None, stopKey = None):
    import princeFunc
    
    if stopKey is None and startKey is None:
        startKey = 1
        stopKey = int(meSchema.tradeCue.all(keys_only=True).order('-__key__').get().name())
    elif stopKey is None or startKey is None:
        raise(BaseException('Must define both startKey and stopKey, or both must be None!'))
    
    memdict = {}
    clockKeyStep = step
    queryStr = princeFunc.getDesireQueryStr(max(step-405,0),step)
    desires = db.GqlQuery(queryStr).fetch(20000)
    for desire in desires:
        desirekey = desire.key().name()
        stckID = meTools.getStckID(desire.Symbol)
        cueKey = desirekey.split("_")[-2]      # Extract cueKey from middle.
        memkey = 'desire_' + cueKey + '_' + str(stckID)
        step = int(desirekey.split("_")[0])    # Extract step from front part of desirekey.
        if not memdict.__contains__(memkey):
            memdict[memkey] = step
        elif memdict[memkey] < step:
            memdict[memkey] = step
    memcache.set_multi(memdict)
    cachepy.set_multi(memdict, priority = 1)
    cachepy.set('stepclock_' + str(startKey) + '_' + str(stopKey), clockKeyStep) # Manually syncing stepclock until get saner method.
コード例 #2
0
def updateAlgStat(algKey, startStep, stopStep, namespace, memprefix = "unpacked_"):
    if namespace == '':
        stckIDs = [1,2,3,4]
        accumulate = False
    else:
        stckIDs = [meTools.getStckID(namespace)]
        accumulate = True

    alginfo = meTools.memGet(meSchema.meAlg, algKey)
    stats = resetAlgstats(memprefix, alginfo.Cash, int(algKey), int(algKey))[memprefix+algKey]
    
    stats = doAlgSteps(algKey, int(startStep), int(stopStep), stats, stckIDs)
    
    bTestReturns = getBackTestReturns([memprefix + algKey],stopStep, {memprefix + algKey: stats}, namespace)
    return bTestReturns
コード例 #3
0
ファイル: liveAlg.py プロジェクト: eliwjones/meprojectholder
def processStepRangeDesires(start, stop, bestAlgs, liveAlgInfo, stckIDorder=[1, 2, 3, 4], MaxTrade=False):
    originalNameSpace = namespace_manager.get_namespace()
    namespace_manager.set_namespace("")
    if originalNameSpace == "":
        accumulate = False
    else:
        accumulate = True
        stckIDorder = [meTools.getStckID(originalNameSpace)]

    for liveAlgKey in bestAlgs:
        algKey = bestAlgs[liveAlgKey]
        stats = convertLiveAlgInfoToStatDict(liveAlgInfo[liveAlgKey])

        stats = processDesires.doAlgSteps(algKey, start, stop, stats, stckIDorder, MaxTrade)

        liveAlgInfo[liveAlgKey] = mergeStatDictIntoLiveAlgInfo(stats, liveAlgInfo[liveAlgKey])
    namespace_manager.set_namespace(originalNameSpace)
    return liveAlgInfo
コード例 #4
0
def doStops(step, statDict, alginfo, stopRange, scaleFactor = 0.0):
    from random import random

    stopDesires = []
    stckKeys = [str(stckID) + '_' + str(step) for stckID in [1,2,3,4]]
    stocks = memGetStcks(stckKeys)
    stckQuotes = {}
    for stock in stocks:
        if stock is None:
            return statDict
        else:
            stckQuotes[meTools.getStckSymbol(stock.ID)] = stock.quote
    for pos in statDict['Positions']:
        stckID = meTools.getStckID(pos)
        stckDeltas = calculateDeltas(stckID,step)
        shares = statDict['Positions'][pos]['Shares']
        longshort = cmp(shares,0)                                  # -1 for short, +1 for long
        stckQuote = stckQuotes[pos]
        offsetDesire = meSchema.desire(Symbol = pos,
                                       Quote = stckQuote,
                                       CueKey = '0000')
        dictDesire = convertDesireToDict(offsetDesire, -1*longshort, alginfo.TradeSize, alginfo.Cash, -1*shares)
        
        # Now only using maxmin deviations for stops.
        maxDevStop, minDevStop = getMaxMinDevMeans(stckDeltas)
        # Using scaleFactor for metaAlgs. Moves stop 40% closer to 1.0

        stopLoss = statDict['Positions'][pos]['StopLoss']
        stopProfit = statDict['Positions'][pos]['StopProfit']
        if longshort == 1:
            if stckQuote < stopLoss or stckQuote > stopProfit:
                stopDesires.append(dictDesire)
            else:
                stopLoss = max(statDict['Positions'][pos]['StopLoss'], stckQuote*minDevStop)
                if stopProfit > 1.15*statDict['Positions'][pos]['Price']:
                    stopPrice = stckQuote*(maxDevStop - ((maxDevStop-1)*scaleFactor))
                    stopProfit = min(statDict['Positions'][pos]['StopProfit'], stopPrice)
        elif longshort == -1:
            if stckQuote > stopLoss or stckQuote < stopProfit:
                stopDesires.append(dictDesire)
            else:
                stopLoss = min(statDict['Positions'][pos]['StopLoss'], stckQuote*maxDevStop)
                if stopProfit < 0.85*statDict['Positions'][pos]['Price']:
                    stopPrice = stckQuote*(minDevStop + ((1-minDevStop)*scaleFactor))
                    stopProfit = max(statDict['Positions'][pos]['StopProfit'], stopPrice)
        statDict['Positions'][pos]['StopLoss'] = stopLoss
        statDict['Positions'][pos]['StopProfit'] = stopProfit
    for stop in stopDesires:
        tradeCash, PandL, position = princeFunc.mergePosition(eval(stop), copy.deepcopy(statDict['Positions']), step, True)
        cash = tradeCash + copy.deepcopy(statDict['Cash'])
        Symbol = eval(stop).keys()[0]
        buysell = cmp(eval(stop)[Symbol]['Shares'], 0)
        statDict['CashDelta'].appendleft({'Symbol'  : Symbol,
                                          'buysell' : str(buysell) + '_stop',
                                          'value'   : tradeCash,
                                          'PandL'   : PandL,
                                          'step'    : step})
        if len(statDict['CashDelta']) > 800:
            statDict['CashDelta'].pop()
        statDict['Cash'] = cash
        statDict['PandL'] += PandL
        statDict['Positions'] = position
    return statDict