def stdev(close, length=None, ddof=None, offset=None, **kwargs): """Indicator: Standard Deviation""" # Validate Arguments length = int(length) if length and length > 0 else 30 ddof = int(ddof) if ddof and ddof >= 0 and ddof < length else 1 close = verify_series(close, length) offset = get_offset(offset) if close is None: return # Calculate Result if Imports["talib"]: from talib import STDDEV stdev = STDDEV(close, length) else: stdev = variance(close=close, length=length, ddof=ddof).apply(npsqrt) # Offset if offset != 0: stdev = stdev.shift(offset) # Handle fills if "fillna" in kwargs: stdev.fillna(kwargs["fillna"], inplace=True) if "fill_method" in kwargs: stdev.fillna(method=kwargs["fill_method"], inplace=True) # Name & Category stdev.name = f"STDEV_{length}" stdev.category = "statistics" return stdev
def refresh(self, df): df = df[-(MAX_ROWS + 1):-1] open = df.open.astype("f8").values high = df.high.astype("f8").values low = df.low.astype("f8").values close = df.close.astype("f8").values volume = df.volume.astype("f8").values df["price"] = WCLPRICE(high, low, close) #Weighted Close Price df["obv"] = OBV(close, volume) df["ad"] = AD(high, low, close, volume) df["macd"], df["signal"], df["histogram"] = MACD(close) df["rsi"] = RSI(close) #relative strong index #df["willr"] = WILLR(high, low, close) + 100 #will index df["roc"] = ROC(close) #統計 df["beta"] = BETA(high, low) df["linearR"] = LINEARREG(close) #線形回帰 df["linearA"] = LINEARREG_ANGLE(close) ##線形回帰 角度 df["linearI"] = LINEARREG_INTERCEPT(close) #線形回帰 JIEJU df["linearS"] = LINEARREG_SLOPE(close) #線形回帰 坂 df["stddev"] = STDDEV(close) #標準偏差 df["tsf"] = TSF(close) #Time Series Forecast df["var"] = VAR(close) #方差 df["wramount"] = 0 df["amount"] = 0 df["memo"] = 0
# -*- coding: UTF-8 -*- # 載入函數 from function import getKbar import datetime from talib import SMA,STDDEV import numpy as np # 取得資料 KBar=getKbar() # 計算移動平均線 、 標準差 、 低點 KBar['MA'] = SMA(KBar['close'], timeperiod= 120) KBar['STD'] = STDDEV(KBar['close'], timeperiod= 120) KBar['BD'] = KBar['MA']-0.75*KBar['STD'] # 初始資金 InitCapital=1000000 # 進場價格 、 進場數量 OrderPrice = None OrderQty = 0 # 出場價格 CoverPrice = None # 停損 、 停利價 StopLoss = None TakeProfit = None # 總獲利 、 交易次數 TotalProfit = [] TotalTreadeNum = 0 for i in range(1,len(KBar['date'])):
def StopProfitLoss(self, ui, KBar): self.ui = ui #from function import getKbar import datetime from talib import SMA, STDDEV import numpy as np # 計算移動平均線 、 標準差 、 低點 KBar['MA'] = SMA(KBar['close'], timeperiod=120) KBar['STD'] = STDDEV(KBar['close'], timeperiod=120) KBar['BD'] = KBar['MA'] - 0.75 * KBar['STD'] # 初始資金 InitCapital = 1000000 # 進場價格 、 進場數量 OrderPrice = None OrderQty = 0 # 出場價格 CoverPrice = None # 停損 、 停利價 StopLoss = None TakeProfit = None # 總獲利 、 交易次數 TotalProfit = [] TotalTreadeNum = 0 data = { '買進時間': [], '買進原因': [], '買進價格': [], '售出時間': [], '售出價格': [], '售出原因': [], '數量': [], '獲利': [] #[(CoverPrice-OrderPrice)*OrderQty*1000], } for i in range(1, len(KBar['date'])): Date = KBar['date'][i] Close = KBar['close'][i] LastClose = KBar['close'][i - 1] BD = KBar['BD'][i] LastBD = KBar['BD'][i - 1] status = [] # 進場條件 if LastClose < LastBD and Close >= BD and OrderQty == 0: # 進場時間、價格、數量 OrderDate = KBar['date'][i + 1] OrderPrice = KBar['open'][i + 1] OrderQty = int(InitCapital / (Close) / 1000) # 停損價、停利價 StopLoss = OrderPrice * 0.8 TakeProfit = OrderPrice * 1.6 status = ' 低點 ' print('買進時間:', OrderDate.strftime('%Y/%m/%d'), '買進價格:', OrderPrice, '買進數量:', OrderQty) data['買進時間'].append(OrderDate.strftime('%Y/%m/%d')) data['買進原因'].append(status) data['買進價格'].append(OrderPrice) data['數量'].append(OrderQty) # 停損判斷 elif OrderQty != 0 and Close < StopLoss: # 出場時間、價格 CoverDate = KBar['date'][i + 1] CoverPrice = KBar['open'][i + 1] # 績效紀錄 Profit = (CoverPrice - OrderPrice) * OrderQty * 1000 TotalProfit += [Profit] TotalTreadeNum += 1 # InitCapital += Profit # 下單數量歸零,重新進場 OrderQty = 0 status = ' 停損 ' print('售出時間:', CoverDate.strftime('%Y/%m/%d'), '售出價格:', CoverPrice, '虧損:', Profit) data['售出時間'].append(CoverDate.strftime('%Y/%m/%d')) data['售出原因'].append(status) data['售出價格'].append(CoverPrice) data['獲利'].append(Profit) # 停利判斷 elif OrderQty != 0 and Close > TakeProfit: # 出場時間、價格 CoverDate = KBar['date'][i + 1] CoverPrice = KBar['open'][i + 1] # 績效紀錄 Profit = (CoverPrice - OrderPrice) * OrderQty * 1000 TotalProfit += [Profit] TotalTreadeNum += 1 # InitCapital += Profit # 下單數量歸零,重新進場 OrderQty = 0 status = ' 停利 ' print('售出時間:', CoverDate.strftime('%Y/%m/%d'), '售出價格:', CoverPrice, '獲利:', Profit) data['售出時間'].append(CoverDate.strftime('%Y/%m/%d')) data['售出原因'].append(status) data['售出價格'].append(CoverPrice) data['獲利'].append(Profit) # 回測時間結束,則出場 elif OrderQty != 0 and i == len(KBar['date']) - 1: # 出場時間、價格 CoverDate = Date CoverPrice = Close # 績效紀錄 Profit = (CoverPrice - OrderPrice) * OrderQty * 1000 TotalProfit += [Profit] TotalTreadeNum += 1 # InitCapital += Profit # 下單數量歸零,重新進場 OrderQty = 0 status = ' 結束 ' print('售出時間:', CoverDate.strftime('%Y/%m/%d'), '售出價格:', CoverPrice, '盈虧:', Profit) data['售出時間'].append(CoverDate.strftime('%Y/%m/%d')) data['售出原因'].append(status) data['售出價格'].append(CoverPrice) data['獲利'].append(Profit) print('交易次數:', TotalTreadeNum, '總盈虧:', sum(TotalProfit)) result = pd.DataFrame(data) print(result) self.change_data(result) import matplotlib.pyplot as plt # 匯出績效圖表 plot_X = list(range(0, len(TotalProfit))) ax = plt.subplot(111) # 新增繪圖圖片 ax.bar(plot_X, np.cumsum(TotalProfit)) # 繪製圖案 ( X軸物件, Y軸物件, 線風格 ) plt.show()
def StopProfitLoss(self, ui, KBar): self.ui = ui #from function import getKbar import datetime from talib import SMA, STDDEV import numpy as np # 計算移動平均線 、 標準差 、 低點 KBar['MA'] = SMA(KBar['close'], timeperiod=120) KBar['STD'] = STDDEV(KBar['close'], timeperiod=120) KBar['BD'] = KBar['MA'] - 0.75 * KBar['STD'] # 初始資金 InitCapital = 1000000 # 進場價格 、 進場數量 OrderPrice = None OrderQty = 0 # 出場價格 CoverPrice = None # 停損 、 停利價 StopLoss = None TakeProfit = None # 總獲利 、 交易次數 TotalProfit = [] TotalTreadeNum = 0 data = { '買進時間': [], '買進原因': [], '買進價格': [], '售出時間': [], '售出價格': [], '售出原因': [], '數量': [], '獲利': [] # [(CoverPrice-OrderPrice)*OrderQty*1000], } for i in range(1, len(KBar['date'])): Date = KBar['date'][i] Close = KBar['close'][i] LastClose = KBar['close'][i - 1] BD = KBar['BD'][i] LastBD = KBar['BD'][i - 1] status = [] # 進場條件 if LastClose < LastBD and Close >= BD and OrderQty == 0: # 進場時間、價格、數量 OrderDate = KBar['date'][i + 1] OrderPrice = KBar['open'][i + 1] OrderQty = int(InitCapital / (Close) / 1000) # 停損價、停利價 StopLoss = OrderPrice * 0.8 TakeProfit = OrderPrice * 1.6 status = ' 低點 ' print('買進時間:', OrderDate.strftime('%Y/%m/%d'), '買進價格:', OrderPrice, '買進數量:', OrderQty) data['買進時間'].append(OrderDate.strftime('%Y/%m/%d')) data['買進原因'].append(status) data['買進價格'].append(OrderPrice) data['數量'].append(OrderQty) # 停損判斷 elif OrderQty != 0 and Close < StopLoss: # 出場時間、價格 CoverDate = KBar['date'][i + 1] CoverPrice = KBar['open'][i + 1] # 績效紀錄 Profit = (CoverPrice - OrderPrice) * OrderQty * 1000 TotalProfit += [Profit] TotalTreadeNum += 1 # InitCapital += Profit # 下單數量歸零,重新進場 OrderQty = 0 status = ' 停損 ' print('售出時間:', CoverDate.strftime('%Y/%m/%d'), '售出價格:', CoverPrice, '虧損:', Profit) data['售出時間'].append(CoverDate.strftime('%Y/%m/%d')) data['售出原因'].append(status) data['售出價格'].append(CoverPrice) data['獲利'].append(Profit) # 停利判斷 elif OrderQty != 0 and Close > TakeProfit: # 出場時間、價格 CoverDate = KBar['date'][i + 1] CoverPrice = KBar['open'][i + 1] # 績效紀錄 Profit = (CoverPrice - OrderPrice) * OrderQty * 1000 TotalProfit += [Profit] TotalTreadeNum += 1 # InitCapital += Profit # 下單數量歸零,重新進場 OrderQty = 0 status = ' 停利 ' print('售出時間:', CoverDate.strftime('%Y/%m/%d'), '售出價格:', CoverPrice, '獲利:', Profit) data['售出時間'].append(CoverDate.strftime('%Y/%m/%d')) data['售出原因'].append(status) data['售出價格'].append(CoverPrice) data['獲利'].append(Profit) # 回測時間結束,則出場 elif OrderQty != 0 and i == len(KBar['date']) - 1: # 出場時間、價格 CoverDate = Date CoverPrice = Close # 績效紀錄 Profit = (CoverPrice - OrderPrice) * OrderQty * 1000 TotalProfit += [Profit] TotalTreadeNum += 1 # InitCapital += Profit # 下單數量歸零,重新進場 OrderQty = 0 status = ' 結束 ' print('售出時間:', CoverDate.strftime('%Y/%m/%d'), '售出價格:', CoverPrice, '盈虧:', Profit) data['售出時間'].append(CoverDate.strftime('%Y/%m/%d')) data['售出原因'].append(status) data['售出價格'].append(CoverPrice) data['獲利'].append(Profit) result = pd.DataFrame(data) # 把字典轉成DataFrame self.change_data(result, self.ui.tableWidget) print('交易次數:', TotalTreadeNum, '總盈虧:', sum(TotalProfit)) #result = pd.DataFrame(data) # print(result) #self.change_data(result, self.ui.tableWidget) KPI_dict = {'交易次數': [TotalTreadeNum], '總盈虧': [sum(TotalProfit)]} KPI_df = pd.DataFrame(KPI_dict) self.change_data(KPI_df, self.ui.tableWidget_2) import matplotlib.pyplot as plt # 匯出績效圖表 import matplotlib.ticker as plticker plot_X = list(range(1, len(TotalProfit) + 1)) plot_Y = np.cumsum(TotalProfit) ax = plt.subplot(111) # 新增繪圖圖片 ax.bar(plot_X, plot_Y) # 繪製圖案 ( X軸物件, Y軸物件 ) ax.ticklabel_format(style="plain") # 設定Y軸為實數顯示,否則預設顯示為科學符號 # 設定X軸間隔為1 # this locator puts ticks at regular intervals loc = plticker.MultipleLocator(base=1.0) ax.xaxis.set_major_locator(loc) # 設定文字 for x, y in zip(plot_X, plot_Y): text_show = int(y) # plt.text(X座標, Y座標, 顯示內容, 水平對齊方式, 垂直對齊方式) if y > 0: plt.text(x, y, text_show, ha="center", va="bottom") else: plt.text(x, y, text_show, ha="center", va="top") plt.savefig("bar_chart.png") self.change_plot("bar_chart.png")
def let_it_be(self, ui, KBar): self.ui = ui import datetime from talib import SMA, STDDEV import numpy as np # 計算移動平均線 、 標準差 、 低點 、 高點 KBar['MA'] = SMA(KBar['close'], timeperiod=120) KBar['STD'] = STDDEV(KBar['close'], timeperiod=120) KBar['BD'] = KBar['MA'] - 0.75 * KBar['STD'] KBar['BU'] = KBar['MA'] + 0.75 * KBar['STD'] # 初始資金 InitCapital = 1000000 # 進場價格 、 進場數量 OrderPrice = None OrderQty = 0 # 出場價格 CoverPrice = None # 停損 、 停利價 StopLoss = None TakeProfit = None # 總獲利 、 交易次數 TotalProfit = [] TotalTreadeNum = 0 data = { '買進時間': [], '買進原因': [], '買進價格': [], '售出時間': [], '售出價格': [], '售出原因': [], '數量': [], '獲利': [] #[(CoverPrice-OrderPrice)*OrderQty*1000], } for i in range(len(KBar['date'])): Date = KBar['date'][i] Close = KBar['close'][i] LastClose = KBar['close'][i - 1] MA = KBar['MA'][i] LastMA = KBar['MA'][i - 1] BD = KBar['BD'][i] LastBD = KBar['BD'][i - 1] BU = KBar['BU'][i] LastBU = KBar['BU'][i - 1] status = [] # 進場條件 if LastClose < LastBD and Close >= BD and OrderQty == 0: # 進場時間、價格、數量 OrderDate = KBar['date'][i + 1] OrderPrice = KBar['open'][i + 1] OrderQty = int(InitCapital / (Close) / 1000) # 停損價、停利價 StopLoss = OrderPrice * 0.8 TakeProfit = OrderPrice * 1.6 status = ' 低點 ' print('買進時間:', OrderDate.strftime('%Y/%m/%d'), '買進價格:', OrderPrice, '買進數量:', OrderQty) data['買進時間'].append(OrderDate.strftime('%Y/%m/%d')) data['買進原因'].append(status) data['買進價格'].append(OrderPrice) data['數量'].append(OrderQty) # 順勢 進場條件 if LastClose < LastMA and Close >= MA * 1.01 and OrderQty == 0: # 進場時間、價格、數量 OrderDate = KBar['date'][i + 1] OrderPrice = KBar['open'][i + 1] OrderQty = int(InitCapital / (Close) / 1000) # 停損價、停利價 StopLoss = OrderPrice * 0.8 TakeProfit = OrderPrice * 1.6 status = ' 順勢 ' print('買進時間:', OrderDate.strftime('%Y/%m/%d'), '買進價格:', OrderPrice, '買進數量:', OrderQty) data['買進時間'].append(OrderDate.strftime('%Y/%m/%d')) data['買進原因'].append(status) data['買進價格'].append(OrderPrice) data['數量'].append(OrderQty) # 高點賣出 elif OrderQty != 0 and LastClose > LastBU and Close <= BU: # 出場時間、價格 CoverDate = KBar['date'][i + 1] CoverPrice = KBar['open'][i + 1] # 績效紀錄 Profit = (CoverPrice - OrderPrice) * OrderQty * 1000 TotalProfit += [Profit] TotalTreadeNum += 1 # InitCapital += Profit # 下單數量歸零,重新進場 OrderQty = 0 status = ' 高點 ' print('售出時間:', CoverDate.strftime('%Y/%m/%d'), '售出價格:', CoverPrice, '獲利:', Profit) data['售出時間'].append(CoverDate.strftime('%Y/%m/%d')) data['售出原因'].append(status) data['售出價格'].append(CoverPrice) data['獲利'].append(Profit) # 停損判斷 elif OrderQty != 0 and Close < StopLoss: # 出場時間、價格 CoverDate = KBar['date'][i + 1] CoverPrice = KBar['open'][i + 1] # 績效紀錄 Profit = (CoverPrice - OrderPrice) * OrderQty * 1000 TotalProfit += [Profit] TotalTreadeNum += 1 # InitCapital += Profit # 下單數量歸零,重新進場 OrderQty = 0 status = ' 停損 ' print('售出時間:', CoverDate.strftime('%Y/%m/%d'), '售出價格:', CoverPrice, '虧損:', Profit) data['售出時間'].append(CoverDate.strftime('%Y/%m/%d')) data['售出原因'].append(status) data['售出價格'].append(CoverPrice) data['獲利'].append(Profit) # 停利判斷 elif OrderQty != 0 and Close > TakeProfit: # 出場時間、價格 CoverDate = KBar['date'][i + 1] CoverPrice = KBar['open'][i + 1] # 績效紀錄 Profit = (CoverPrice - OrderPrice) * OrderQty * 1000 TotalProfit += [Profit] TotalTreadeNum += 1 # InitCapital += Profit # 下單數量歸零,重新進場 OrderQty = 0 status = ' 停利 ' print('售出時間:', CoverDate.strftime('%Y/%m/%d'), '售出價格:', CoverPrice, '獲利:', Profit) data['售出時間'].append(CoverDate.strftime('%Y/%m/%d')) data['售出原因'].append(status) data['售出價格'].append(CoverPrice) data['獲利'].append(Profit) # 回測時間結束,則出場 elif OrderQty != 0 and i == len(KBar['date']) - 1: # 出場時間、價格 CoverDate = Date CoverPrice = Close # 績效紀錄 Profit = (CoverPrice - OrderPrice) * OrderQty * 1000 TotalProfit += [Profit] TotalTreadeNum += 1 # InitCapital += Profit # 下單數量歸零,重新進場 OrderQty = 0 status = ' 結束 ' print('售出時間:', CoverDate.strftime('%Y/%m/%d'), '售出價格:', CoverPrice, '盈虧:', Profit) data['售出時間'].append(CoverDate.strftime('%Y/%m/%d')) data['售出原因'].append(status) data['售出價格'].append(CoverPrice) data['獲利'].append(Profit)