量化回测框架-backtrader-KD策略

from datetime import datetime
import backtrader
import pandas

def Function_For_Build_KD_Object(KD_Period):
    
    
    class Strategy_KD_Object(backtrader.Strategy):
        
        def __init__(self):
    
            self.data_open = self.datas[0].open
            self.data_high = self.datas[0].high
            self.data_low = self.datas[0].low
            self.data_close = self.datas[0].close
            self.data_volume = self.datas[0].volume  
            
            self.RSV_Value = 0
            self.K_Value = 50
            self.D_Value = 50            
            
        def next(self):
            
            def Function_Cauculate_KD (KD_Period) :
                
                Highest_Price =  self.data_high[0]
                Lowest_Price =  self.data_low[0]
                
                for Day in range(0, -KD_Period, -1):
                    
                    if self.data_high[Day] > Highest_Price :
                        Highest_Price = self.data_high[Day]

                    if self.data_low[Day] < Lowest_Price :
                        Lowest_Price = self.data_low[Day]
                        
                RSV_Value = 100 * (self.data_close[0] - Lowest_Price) / (Highest_Price - Lowest_Price)
                
                self.K_Value = (self.K_Value * (2/3)) + (RSV_Value * (1/3))
                self.D_Value = (self.D_Value * (2/3)) + (self.K_Value * (1/3))
                
           
            Function_Cauculate_KD(KD_Period)
            
            #self.buy()
            #self.sell()
            #https://www.backtrader.com/docu/order-creation-execution/order-creation-execution/

            if self.K_Value > self.D_Value:
                self.buy()
                print("buy")
                
            if self.K_Value < self.D_Value:
                self.sell()
                print("sell")
            
            
            data_fram = pandas.DataFrame({"Open Price": self.data_open[0],
                                             "High Price": self.data_high[0],
                                             "Low Price": self.data_low[0],
                                             "Close Price": self.data_close[0],
                                             "Volumns": self.data_volume[0],
                                             "K Value": self.K_Value,
                                             "D Value": self.D_Value
                                             },index=[0])
            print(data_fram)
            
            
    return Strategy_KD_Object
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值