0

我建立了一个简单的策略,然后添加了一个系统来跟踪任何买单,并且只有在发出更高价格的卖出信号时才卖出与该买单相对应的大小。每当我这样做时,它似乎工作得很好,但是当我绘制结果时,交易停止出现,并且在图表中的某个时间,它说我只剩下 0 现金,但它继续执行买卖订单。我究竟做错了什么?

策略(RSI)代码:

class MyStrat2(bt.Strategy):
    def __init__(self) -> None:
        self.rsi = bt.talib.RSI(self.data, period=14)
        self.keltner = KeltnerChannels()
        self.pending = {}
        # Dictionary containing pending orders as (key, value) = (price, size)
        

    def next(self):
        #Check if there is cash left to trade
        if self.rsi < 30 and self.env.broker.getcash() > 0:
            price = self.data[0]
            size = self.env.broker.getcash() / self.data[0] 
            size = size / 2
            self.pending[price] = size   
            #Calculate order size and add it to pending orders
            print("Buy at {}, size {}".format(price, size))
            self.buy(size=size)

        if self.rsi > 70 and self.position:
            size, self.pending = sellSizeRSI(self.pending, self.data[0])
            #Calculate the size of sell and update the pending orders deleting the ones we  
            #We are selling 
            if size > 0:
                self.sell(size=size)
                print("Maybe sell at {}, with size {}".format(self.data[0], size))
       
def sellSizeRSI(dictionary, lastPrice):
    amount = 0
    priceList = []
    #We iterate the pending orders
    for price, size in dictionary.items():
        #If we earn profit
        if price < lastPrice:
            amount += size #Add the amount to sell to the total
            priceList.append(price) #Append key to list to latter dict update
    for price in priceList:
        dictionary.pop(price) #We update the dictionary 
            
    return amount, dictionary


在此处输入图像描述 这是开始的情节,正如你所看到的,它没有在时间线的第一季度之后绘制交易,并且还显示了购买时执行的一些负面交易,如果我没有,它怎么能说交易是负面的卖什么?

在此处输入图像描述 仔细看看剧情。您可以看到卖出和买入信号是如何触发的,但没有现金了。如果没有现金购买,怎么可能购买?可能是现金数量太少无法显示?

我不知道它是否工作得很好,但不能显示这么小的值,或者我的策略有错误。欢迎任何帮助,谢谢!

4

0 回答 0