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)
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