def get_volume(volumeNum, date, data=pd.DataFrame(), getMax=False): Temp_index = 0 Temp_volume2 = 0 avgDay = 5 if data.empty == False: for index, row in data.iterrows(): Temp_volume = get_stock_history.get_stock_price( str(index), tools.DateTime2String(date), get_stock_history.stock_data_kind.Volume, isSMA=True) while (Temp_volume == None): if get_stock_history.check_no_use_stock(index): break date = date + timedelta(days=-1) #加一天 Temp_volume = get_stock_history.get_stock_price( str(index), tools.DateTime2String(date), get_stock_history.stock_data_kind.Volume, isSMA=True) if Temp_volume != None and Temp_volume >= volumeNum: if (mypick.check_volum_Max.isChecked()): if Temp_volume > Temp_volume2: if (Temp_index != 0): data = data.drop(index=Temp_index) Temp_index = index Temp_volume2 = Temp_volume else: data = data.drop(index=index) else: pass else: data = data.drop(index=index) else: print("get_volume:輸入的data是空的") return data
def get_AVG_value( time, volume, days, data=pd.DataFrame()): #time = 取得資料的時間 volume = 平均成交金額 days = 平均天數 print('get_AVG_value: start') Volume_Time = time if type(Volume_Time) == str: Volume_Time = datetime.strptime(time, "%Y-%m-%d") All_monthRP = data if All_monthRP.empty == True: All_monthRP = get_allstock_monthly_report(Volume_Time) Volume_data = pd.DataFrame(columns=['公司代號', 'volume']) for i in range(0, len(All_monthRP)): Temp_AvgVolume = 0 AvgDays = days NoDataDays = 10 Temp_Volume_Time = Volume_Time while AvgDays > 0: if NoDataDays == 0: break Temp_Volume = get_stock_price( str(All_monthRP.iloc[i].name), tools.DateTime2String(Temp_Volume_Time), stock_data_kind.Volume) if Temp_Volume == None: if Temp_Volume_Time == Volume_Time: break NoDataDays = NoDataDays - 1 Temp_Volume_Time = Temp_Volume_Time + timedelta(days=-1) continue Temp_AvgVolume = Temp_AvgVolume + Temp_Volume AvgDays = AvgDays - 1 NoDataDays = 10 Temp_Volume_Time = Temp_Volume_Time + timedelta(days=-1) Temp_AvgVolume = Temp_AvgVolume / days if Temp_AvgVolume >= volume: Temp_number = int(All_monthRP.iloc[i].name) Volume_data.loc[(len(Volume_data) + 1)] = { '公司代號': Temp_number, 'volume': Temp_AvgVolume } print('get_AVG_value: ' + str(All_monthRP.iloc[i].name) + '/' + str(Temp_AvgVolume)) Volume_data['公司代號'] = Volume_data['公司代號'].astype('int') Volume_data['volume'] = Volume_data['volume'].astype('int') Volume_data.set_index('公司代號', inplace=True) print('get_AVG_value: end') return Volume_data
def avg_stock_price(date,vData = pd.DataFrame()): All_price = 0 # Count = 0 Result_avg_price = 0 if(vData.empty == True): return 0,0 for value in range(0,len(vData)): Nnumber = str(vData.iloc[value].name) Temp_stock_price = get_stock_history.get_stock_price(Nnumber,tools.DateTime2String(date), get_stock_history.stock_data_kind.AdjClose) if Temp_stock_price != None: All_price = All_price + Temp_stock_price Count = Count + 1 if All_price == 0 or Count == 0: return 0,0 Result_avg_price = All_price / Count return Result_avg_price,Count
def get_stock_price(number, date, kind, isSMA=False): #取得某股票某天的ADJ價格 global Holiday_trigger if check_no_use_stock(number) == True: print('get_stock_price: ' + str(number) + ' in no use') return None stock_data = get_stock_history(number, date, reGetInfo=False, UpdateInfo=False) if stock_data.empty == True: return None result = stock_data[kind.value] if kind == stock_data_kind.Volume: result = tools.smooth_Data(result, 5) result = stock_data[stock_data.index == date] if result.empty == True: if Holiday_trigger == True: return None if type(date) != str: date = tools.DateTime2String(date) if datetime.strptime(date, "%Y-%m-%d").isoweekday() in [1, 2, 3, 4, 5]: stock_data = get_stock_history(number, date, reGetInfo=False, UpdateInfo=False) #只會重新抓硬碟資料 result = stock_data[stock_data.index == date] if result.empty == True: print('get_stock_price: ' + '星期' + str(datetime.strptime(date, "%Y-%m-%d").isoweekday())) print('get_stock_price: ' + str(number) + '--' + date + ' is no data. Its holiday?') Holiday_trigger = True return None else: return None result = result[kind.value] close = result[date] Holiday_trigger = False return close
def backtest_KD_pick(mainParament): userInfo = get_user_info.data_user_info(mainParament.money_start, mainParament.date_start, mainParament.date_end) Temp_result_pick = pd.DataFrame(columns=['date', '選股數量']) Temp_table = get_stock_history.get_stock_history(2330, userInfo.start_day, reGetInfo=False, UpdateInfo=False) All_stock_signal = dict() for key, value in get_stock_info.ts.codes.items(): if value.market == "上市" and len(value.code) == 4: if get_stock_history.check_no_use_stock(value.code) == True: print('get_stock_price: ' + str(value.code) + ' in no use') continue table = get_stock_history.get_stock_history(value.code, userInfo.start_day, reGetInfo=False, UpdateInfo=False) table_K, table_D = talib.STOCH(table['High'], table['Low'], table['Close'], fastk_period=50, slowk_period=20, slowk_matype=0, slowd_period=20, slowd_matype=0) table_sma10 = talib.SMA(np.array(table['Close']), 10) table_sma240 = talib.SMA(np.array(table['Close']), 240) signal_buy = (table_K > table_D) signal_sell = (table_K < table_D) signal_sma10 = table.Close < table_sma10 signal_sma240 = table.Close > table_sma240 signal = signal_buy.copy() signal = (signal_sma10 & signal_sma240 & signal_buy) signal[signal_sell] = -1 All_stock_signal[value.code] = signal ROE_record_day = datetime.datetime(2000, 1, 1) buy_data = pd.DataFrame(columns=['Date', '公司代號']).set_index('Date') sell_data = pd.DataFrame(columns=['Date', '公司代號']).set_index('Date') ROE_data = {} jump_day = 240 for index, row in Temp_table.iterrows(): while userInfo.now_day < index: userInfo.add_one_day() if jump_day > 0: jump_day = jump_day - 1 continue if ROE_record_day <= index: ROE_data = {} ROE_record_day = tools.changeDateMonth(index, 1) BOOK_data = get_stock_history.get_allstock_financial_statement( tools.changeDateMonth(index, -3), get_stock_history.FS_type.BS) CPL_data = get_stock_history.get_allstock_financial_statement( tools.changeDateMonth(index, -3), get_stock_history.FS_type.CPL) ROE_data["ROE_data_1"] = pd.DataFrame({ 'ROE_data_1': (CPL_data["本期綜合損益總額(稅後)"] / BOOK_data['權益總額']) * 100 }) BOOK_data = get_stock_history.get_allstock_financial_statement( tools.changeDateMonth(index, -6), get_stock_history.FS_type.BS) CPL_data = get_stock_history.get_allstock_financial_statement( tools.changeDateMonth(index, -6), get_stock_history.FS_type.CPL) ROE_data["ROE_data_2"] = pd.DataFrame({ 'ROE_data_2': (CPL_data["本期綜合損益總額(稅後)"] / BOOK_data['權益總額']) * 100 }) BOOK_data = get_stock_history.get_allstock_financial_statement( tools.changeDateMonth(index, -9), get_stock_history.FS_type.BS) CPL_data = get_stock_history.get_allstock_financial_statement( tools.changeDateMonth(index, -9), get_stock_history.FS_type.CPL) ROE_data["ROE_data_3"] = pd.DataFrame({ 'ROE_data_3': (CPL_data["本期綜合損益總額(稅後)"] / BOOK_data['權益總額']) * 100 }) BOOK_data = get_stock_history.get_allstock_financial_statement( tools.changeDateMonth(index, -12), get_stock_history.FS_type.BS) CPL_data = get_stock_history.get_allstock_financial_statement( tools.changeDateMonth(index, -12), get_stock_history.FS_type.CPL) ROE_data["ROE_data_4"] = pd.DataFrame({ 'ROE_data_4': (CPL_data["本期綜合損益總額(稅後)"] / BOOK_data['權益總額']) * 100 }) mask = tools.MixDataFrames(ROE_data) ROE_data_result = (mask["ROE_data_1"] + mask["ROE_data_2"] + mask["ROE_data_3"] + mask["ROE_data_4"]) / 4 ROE_data_result = ROE_data_result.dropna() ROE_data = mask["ROE_data_1"] > ROE_data_result buy_numbers = [] sell_numbers = [] for i, value in All_stock_signal.items(): try: if value[index] == True: if ROE_data.index.__contains__(int(i)): if ROE_data[int(i)] == True: buy_numbers.append(i) elif value[index] < 0: sell_numbers.append(i) except: #print('error:' + str(index) + ' at ' + str(i)) continue #出場訊號篩選-------------------------------------- if len(userInfo.handle_stock) > 0: Temp_data = userInfo.handle_stock for key, value in list(Temp_data.items()): if sell_numbers.__contains__(key): userInfo.sell_stock(key, value.amount) #入場訊號篩選-------------------------------------- if len(buy_numbers) > 0: Temp_buy = pd.DataFrame(columns={'公司代號', 'volume'}) for number in buy_numbers: volume = get_stock_history.get_stock_price( number, tools.DateTime2String(userInfo.now_day), get_stock_history.stock_data_kind.Volume) Temp_buy = Temp_buy.append({ '公司代號': number, 'volume': volume }, ignore_index=True) Temp_buy = Temp_buy.sort_values(by='volume', ascending=False).set_index('公司代號') userInfo.buy_all_stock(Temp_buy) if len(buy_numbers) != 0: buy_data = buy_data.append({ 'Date': index, '公司代號': buy_numbers }, ignore_index=True) if len(sell_numbers) != 0: sell_data = sell_data.append({ 'Date': index, '公司代號': sell_numbers }, ignore_index=True) #更新資訊-------------------------------------- userInfo.Record_userInfo() userInfo.Recod_tradeInfo() Temp_result_pick = Temp_result_pick.append( { 'date': userInfo.now_day, '選股數量': len(buy_numbers) }, ignore_index=True) buy_data = buy_data.set_index('Date') buy_data.to_csv('buy.csv') sell_data = sell_data.set_index('Date') sell_data.to_csv('sell.csv') #最後總結算---------------------------- Temp_result_pick.set_index('date', inplace=True) Temp_alldata = tools.MixDataFrames( { 'draw': userInfo.Temp_result_draw, 'pick': Temp_result_pick }, 'date') draw_figur.draw_backtest(userInfo.Temp_result_draw.set_index('date')) Temp_alldata = tools.MixDataFrames( { 'all': Temp_alldata, 'userinfo': userInfo.Temp_result_All }, 'date') userInfo.Temp_result_draw.set_index('date').to_csv('backtestdata.csv') userInfo.Temp_trade_info.set_index('date').to_csv('backtesttrade.csv') Temp_alldata.set_index('date').to_csv('backtestAll.csv')
def backtest_KD_pick(mainParament): userInfo = get_user_info.data_user_info(mainParament.money_start,mainParament.date_start,mainParament.date_end) Temp_result_pick = pd.DataFrame(columns=['date','選股數量']) Temp_table = get_stock_history.get_stock_history(2330,"2005-01-01",reGetInfo = False,UpdateInfo = False) All_stock_signal = dict() ROE_record_day = datetime.strptime("2000-01-01","%Y-%m-%d") buy_data = pd.DataFrame(columns = ['Date','code']).set_index('Date') sell_data = pd.DataFrame(columns = ['Date','code']).set_index('Date') ROE_data = {} add_one_day = userInfo.add_one_day changeDateMonth = tools.changeDateMonth get_ROE_range = get_stock_history.get_ROE_range MixDataFrames = tools.MixDataFrames sell_stock = userInfo.sell_stock buy_all_stock = userInfo.buy_all_stock for index,row in Temp_table.iterrows(): if index < userInfo.now_day: continue while userInfo.now_day != index: if add_one_day() == False: break has_trade = False #ROE篩選 if ROE_record_day <= index: ROE_data = {} ROE_record_day = changeDateMonth(index,1) ROE_data["ROE_data_1"] = pd.DataFrame(get_ROE_range(changeDateMonth(index,-3),0,999)) ROE_data["ROE_data_1"].rename(columns={'ROE':'ROE_data_1'},inplace=True) ROE_data["ROE_data_2"] = pd.DataFrame(get_ROE_range(changeDateMonth(index,-6),0,999)) ROE_data["ROE_data_2"].rename(columns={'ROE':'ROE_data_2'},inplace=True) ROE_data["ROE_data_3"] = pd.DataFrame(get_ROE_range(changeDateMonth(index,-9),0,999)) ROE_data["ROE_data_3"].rename(columns={'ROE':'ROE_data_3'},inplace=True) ROE_data["ROE_data_4"] = pd.DataFrame(get_ROE_range(changeDateMonth(index,-12),0,999)) ROE_data["ROE_data_4"].rename(columns={'ROE':'ROE_data_4'},inplace=True) mask = MixDataFrames(ROE_data) ROE_data_result =(mask["ROE_data_1"]+mask["ROE_data_2"]+mask["ROE_data_3"]+mask["ROE_data_4"])/4 ROE_data_result = ROE_data_result.dropna() ROE_data_mask = mask["ROE_data_1"]> ROE_data_result ROE_data = ROE_data_mask[ROE_data_mask] for key,value in ROE_data.iteritems():#先算出股票的買賣訊號 if get_stock_history.check_no_use_stock(key) == True: print('get_stock_price: ' + str(key) + ' in no use') continue if All_stock_signal.__contains__(key): continue table = get_stock_history.get_stock_history(key,"2005-01-01",reGetInfo = False,UpdateInfo = False) table_K,table_D = talib.STOCH(table['High'],table['Low'],table['Close'],fastk_period=50, slowk_period=20, slowk_matype=0, slowd_period=20, slowd_matype=0) table_sma10 = talib.SMA(np.array(table['Close']), 10) table_sma240 = talib.SMA(np.array(table['Close']), 240) signal_buy = (table_K > table_D) signal_sell = (table_K < table_D) signal_sma10 = table.Close < table_sma10 signal_sma240 = table.Close > table_sma240 signal = signal_buy.copy() signal = (signal_sma10 & signal_sma240 & signal_buy) signal[signal_sell] = -1 All_stock_signal[key] = signal #找出買入訊號跟賣出訊號------------------------- buy_numbers = [] sell_numbers = [] for i,value in All_stock_signal.items(): try: if value[index] == True: if ROE_data.index.__contains__(int(i)): if ROE_data[int(i)] == True: buy_numbers.append(i) elif value[index] < 0 : sell_numbers.append(i) except: #print('error:' + str(index) + ' at ' + str(i)) continue #出場訊號篩選-------------------------------------- if len(userInfo.handle_stock) > 0: Temp_data = userInfo.handle_stock for key,value in list(Temp_data.items()): if sell_numbers.__contains__(int(key)): sell_stock(key,value.amount) has_trade = True #入場訊號篩選-------------------------------------- if len(buy_numbers) > 0 : Temp_buy = pd.DataFrame(columns={'code','volume'}) for number in buy_numbers: volume = get_stock_history.get_stock_price(number,tools.DateTime2String(userInfo.now_day),get_stock_history.stock_data_kind.Volume) Temp_buy = Temp_buy.append({'code':str(number),'volume':volume},ignore_index = True) Temp_buy = Temp_buy.sort_values(by='volume', ascending=False).set_index('code') buy_all_stock(Temp_buy) has_trade = True #更新資訊-------------------------------------- if has_trade: if len(buy_numbers) != 0: buy_data = buy_data.append({'Date':index,'code':buy_numbers},ignore_index = True) if len(sell_numbers) != 0: sell_data = sell_data.append({'Date':index,'code':sell_numbers},ignore_index = True) userInfo.Record_userInfo() userInfo.Recod_tradeInfo() Temp_result_pick = Temp_result_pick.append({'date':userInfo.now_day, '選股數量':len(buy_numbers)},ignore_index = True) buy_data = buy_data.set_index('Date') buy_data.to_csv('buy.csv') sell_data = sell_data.set_index('Date') sell_data.to_csv('sell.csv') #最後總結算---------------------------- Temp_result_pick.set_index('date',inplace=True) Temp_alldata = tools.MixDataFrames({'draw':userInfo.Temp_result_draw,'pick':Temp_result_pick},'date') Temp_alldata = tools.MixDataFrames({'all':Temp_alldata,'userinfo':userInfo.Temp_result_All},'date') userInfo.Temp_result_draw.set_index('date').to_csv('backtestdata.csv') userInfo.Temp_trade_info.set_index('date').to_csv('backtesttrade.csv') Temp_alldata.set_index('date').to_csv('backtestAll.csv') return userInfo.Temp_result_draw.set_index('date')
def get_stock_AD_index(date): #取得上漲和下跌家數 print('get_stock_AD_index') ADindex_result = pd.DataFrame( columns=['Date', '上漲', '下跌']).set_index('Date') if type(date) == str: date = datetime.strptime(date, "%Y-%m-%d") time = date str_date = tools.DateTime2String(time) time_yesterday = tools.backWorkDays(time, 1) while (get_stock_price(2330, time_yesterday, stock_data_kind.AdjClose) == None): time_yesterday = tools.backWorkDays(time_yesterday, 1) #加一天 str_yesterday = tools.DateTime2String(time_yesterday) fileName = filePath + '/' + fileName_index + '/' + 'AD_index' if fileName in load_memery: ADindex_result = load_memery[fileName] #=========test ADindex_result = load_other_file(fileName, 'AD_index') if ADindex_result.empty == True: if os.path.isfile(fileName + '.csv') == True: ADindex_result = pd.read_csv(fileName + '.csv', index_col='Date', parse_dates=['Date']) load_memery[fileName] = ADindex_result else: print('no csv file') #========= up = 0 down = 0 if ADindex_result.empty == False and (ADindex_result.index == time).__contains__(True): return ADindex_result[ADindex_result.index == time] for key, value in get_stock_info.ts.codes.items(): if value.market == "上市" and len(value.code) == 4: if check_no_use_stock(value.code) == True: print('get_stock_price: ' + str(value.code) + ' in no use') continue m_history = get_stock_history(value.code, str_yesterday, reGetInfo=False, UpdateInfo=False)['Close'] try: if m_history[str_yesterday] > m_history[str_date]: down = down + 1 elif m_history[str_yesterday] < m_history[str_date]: up = up + 1 except: print("get " + str(value.code) + " info fail!") m_temp = get_stock_history(2330, str_yesterday, reGetInfo=False, UpdateInfo=False)['Close'] if (m_temp.index == time).__contains__(True) != True: return pd.DataFrame() ADindex_result_new = pd.DataFrame({ 'Date': [time], '上漲': [up], '下跌': [down] }).set_index('Date') ADindex_result = ADindex_result.append(ADindex_result_new) ADindex_result = ADindex_result.sort_index() update_stock_info.saveTable('AD_index', ADindex_result) ADindex_result.to_csv(fileName + '.csv') load_memery[fileName] = ADindex_result df = ADindex_result[ADindex_result.index == time] return df