def total_money(self): from autoxd import agl df_zhijing = self.account.ZhiJing() df_stock = self.account.StockList() if len(df_stock) == 0: return self.can_use_money() num = agl.where(len(df_stock) > 0, float(df_stock.iloc[-1]['库存数量']), 0) return float(df_zhijing.iloc[-1]['可用']) + num * self.price
def Report(self): """报告技术指标""" if not hasattr(self, 'tech'): return closes, four, boll_up, boll_mid, boll_low, boll_w, adx = self.tech assert (len(closes) == len(four)) cur_pl = agl.where(self.pl, self.pl, pl) df = pd.DataFrame(closes) df['boll_w'] = boll_w df = stock.GuiYiHua(df) df['four'] = four #df[df.columns[0]] = (df[df.columns[0]]-1)*2 #index转日期 df.index = pd.DatetimeIndex(df.index) df.plot() cur_pl.show() cur_pl.close()
def Run(self): """ """ #self._log('Strategy_Boll_Pre') #以下为交易测试 code = self.data.get_code() #当前策略处理的股票 self.code = code if not self.is_backtesting and not self.AllowCode(code): return df_hisdat = self.data.get_hisdat(code) #日k线 df_five_hisdat = self.data.get_hisdat(code, dtype='5min') #5分钟k线 df_fenshi = self.data.get_fenshi(code) #日分时 if len(df_fenshi) == 0: self.data.log(code + u"未取到分时数据") return account = self._getAccount() #获取交易账户 price = float(df_fenshi.tail(1)['p']) #当前股价 closes = df_hisdat['c'] yestoday_close = closes[-2] #昨日收盘价 zhangfu = stock.ZhangFu(price, yestoday_close) self._log( 'price=%.2f %s %s' % (price, str(df_fenshi.index[-1]), str(df_five_hisdat.iloc[-1]))) account_mgr = ac.AccountMgr(account, price, code) trade_num = ac.ShouShu(account_mgr.init_money() * self.trade_num_use_money_percent / price) trade_num = max(100, trade_num) # 信号计算 four = stock.FOUR(closes) four = four[-1] upper, middle, lower = stock.TDX_BOLL(df_five_hisdat['c']) highs, lows, closes = df_five_hisdat['h'], df_five_hisdat[ 'l'], df_five_hisdat['c'] adx = stock.TDX_ADX(highs, lows, closes) self._log('boll : %.2f,%.2f,%.2f' % (upper[-1], middle[-1], lower[-1])) boll_w = abs(upper[-1] - lower[-1]) / middle[-1] * 100 #50个周期内最高值 is_high = abs(price - max(df_five_hisdat[-1000:]['h'])) / price < 0.005 boll_poss = [ upper[-1], (upper[-1] - middle[-1]) / 2 + middle[-1], middle[-1], (middle[-1] - lower[-1]) / 2 + lower[-1], lower[-1], ] self._log('boll_poss: %.2f, %.2f boll_w=%.2f adx=%.2f' % (boll_poss[0], boll_poss[1], boll_w, adx[-1])) #上一个成交的价位 pre_price = account_mgr.last_chengjiao_price() pre_pre_price = account_mgr.last_chengjiao_price(index=-2) sell_count = account_mgr.queryTradeCount(1) buy_count = account_mgr.queryTradeCount(0) #买入均价 adx = adx[-1] boll_up_ratio = 0.02 #信号判断 num = 0 if so.assemble( price > boll_poss[1], price > pre_price * (1 + self.trade_ratio), #price > boll_poss[2], #price > self.max_buy_price*(1+self.trade_ratio), #boll_w > 3.5, #adx > 60, #sell_count < 2, #pr.horizontal(df_five_hisdat), 0, ): num = -trade_num self.trade_status = self.enum.boll_up_mid #if self.order(1, code, price, num): #self._log(agl.utf8_to_ascii('一档卖出%s, %.2f, %d'%(code, price, num))) if so.assemble( price > boll_poss[0], price > pre_price * (1 + self.trade_ratio), #price > self.max_buy_price*(1+self.trade_ratio), #boll_w > 3, adx > 60, is_high, #four > self.trade_four[1], #sell_count < 2, #self.trade_status == self.enum.nothing, #0, ): num = -trade_num * 3 self.trade_status = self.enum.boll_up #if self.order(1, code, price, num): #self._log(agl.utf8_to_ascii('二档卖出%s, %.2f, %d'%(code, price, num))) if so.assemble( price < boll_poss[-2] * (1 + boll_up_ratio), price < pre_price * (1 - self.trade_ratio), #price < boll_poss[2], #price < self.min_sell_price*(1-0.03), #boll_w > 3.5, #adx>60, #buy_count < 2, #pr.horizontal(df_five_hisdat), 0, ): num = trade_num self.trade_status = self.enum.boll_down_mid #if boll_w > 6: #num *= self.trade_num_ratio #if self.order(0, code, price, num): #self._log(agl.utf8_to_ascii('一档买入%s, %.2f, %d'%(code, price, num))) if so.assemble( price < boll_poss[-1], price < pre_price * (1 - self.trade_ratio), #price < self.min_sell_price*(1-0.03), #boll_w > 3, #buy_count < 2, #self.trade_status == self.enum.nothing, #adx>70, #four < self.trade_four[0], #0, ): num = trade_num * 3 #num = account_mgr.last_chengjiao_num() self.trade_status = self.enum.boll_down #if self.order(0, code, price, num): #self._log(agl.utf8_to_ascii('二档买入%s, %.2f, %d'%(code, price, num))) #成本区间 if so.assemble( price < pre_price * (1 - 0.05), four < -0.1, self.trade_status == self.enum.boll_up, 0, ): num = trade_num * self.trade_num_ratio self.trade_status = self.enum.nothing if so.assemble( price > pre_price * (1 + 0.05), four > 0.1, self.trade_status == self.enum.boll_down, 0, ): num = -trade_num * self.trade_num_ratio self.trade_status = self.enum.nothing #zz顶抛出后回补 if so.assemble( price < pre_price * (1 - 0.02), #sell_count >= 2, self.trade_status == self.enum.zz_up, 0, ): #上次zz卖出的数量 num = account_mgr.last_chengjiao_num() self.trade_status = self.enum.zz_hui_bu if so.assemble( price > pre_price * (1 + 0.02), #sell_count >= 2, self.trade_status == self.enum.zz_down, 0, ): #上次zz卖出的数量 num = account_mgr.last_chengjiao_num() self.trade_status = self.enum.zz_hui_bu #计算分时zz zz_sign = 0 closes = df_five_hisdat['c'][-200:].values zz = stock.ZigZag(closes) if len(zz) > 2: zz_result = stock.analyzeZZ(zz) zz_line_ratio = zz_result[1] / zz_result[0] #线段比率 #扑捉大涨回头的信号 if abs(zz_result[0]) > 0.05 and abs(zz_line_ratio) > 0.05 and abs( zz_line_ratio) < 0.2 and abs(zz_result[0]) > 0.04: zz_sign = agl.where(zz_result[1] > 0, 1, -1) if num != 0: bSell = agl.where(num > 0, 0, 1) num = abs(num) #if bSell: #num = self._compensate(num, bSell, code) #基本上每天的振幅都在1个点以上 if abs(stock.ZhangFu(price, yestoday_close)) > 0.01: self.order(bSell, code, price, num) zz_pre_price = myredis.createRedisVal('policy_basesign_zz_pre_price', price) if so.assemble( zz_sign != 0, 0, ): #print self.price, getZZPrePrice(self.price),abs(self.price-getZZPrePrice(self.price))/self.price num = trade_num * 12 bSell = agl.where(zz_sign > 0, 0, 1) num = self._compensate(num, bSell, code) bCanOrder = False if so.assemble( bSell, price > zz_pre_price.get() * (1 + 0.03), #price > pre_price*(1+self.trade_ratio), ): bCanOrder = True self.trade_status = self.enum.zz_up if so.assemble( (not bSell), price < zz_pre_price.get() * (1 - 0.03), #price < pre_price*(1-self.trade_ratio) ): bCanOrder = True self.trade_status = self.enum.zz_down if bCanOrder: self._getAccount().Order(bSell, code, price, num) zz_pre_price.set(price) #信号发生时语音播报, 并通知界面回显 if not self.is_backtesting and (price > boll_poss[1] or price < boll_poss[-2]): codename = stock.GetCodeName(code) s = '%s, %.2f' % (codename, price) self.data.show(codename) #通知界面显示 self.data.speak2(s) #语音播报 #tick report if self.is_backtesting and self.is_tick_report: self._getAccount().TickReport(df_five_hisdat, 'win') return
def _Report(self, policy, start_day, end_day, last_close): policy._getAccount().Report(end_day, last_close, True) #绘制图形 if hasattr(policy, 'Report'): policy.Report() #end_day = help.MyDate.s_Dec(end_day, 1) #bars = stock.CreateFenshiPd(self.code, start_day, end_day) if self.mode == 0: bars = self.dict_fenshi[self.codes[0]] if len(bars) == 0: return bars = bars.resample('1min').mean() bars['c'] = bars['p'] else: #日线 bars = self.panel_hisdat[self.codes[0]] if self.mode & self.enum.hisdat_five_mode == self.enum.hisdat_five_mode: bars = self.panel_fiveminHisdat[self.codes[0]] bars['positions'] = 0 bars = bars.dropna() df = policy._getAccount().ChengJiao() df_zhijing = policy._getAccount().ZhiJing() init_money = df_zhijing.iloc[0]['资产'] df_zhijing = df_zhijing[bars.index[0]:] df_changwei = policy._getAccount().ChengJiao() cols = ['买卖标志', '委托数量'] df_flag = df_changwei[cols[0]].map(lambda x: x == '证券卖出' and -1 or 1) df_changwei[cols[1]] *= df_flag changwei = df_changwei[cols[1]].cumsum() if self.mode == self.enum.hisdat_mode: df.index = df.index.map(lambda x: agl.datetime_to_date(x)) #bars.is_copy = False for i in range(len(df)): index = df.index[i] bSell = bool(df.iloc[i]['买卖标志'] == '证券卖出') if index in bars.index: bars.at[index, 'positions'] = agl.where(bSell, -1, 1) #同步资金到bar #df_zhijing.is_copy = False df_zhijing = copy.deepcopy(df_zhijing) # 为了避免赋值警告 df_zhijing['changwei'] = changwei if self.mode == self.enum.hisdat_mode: df_zhijing.index = df_zhijing.index.map( lambda x: agl.datetime_to_date(x)) bars = bars.join(df_zhijing) bars = bars.fillna(method='pad') #同步价格的动态总资产 bars['资产'] = bars['可用'] + bars['changwei'] * bars['c'] zhican = (bars['资产'] - init_money) / init_money * 100 zhican = zhican.fillna(0) if sys.version > '3': title = '%s %s' % (self.codes[0], stock.GetCodeName(self.codes[0])) else: title = '%s %s' % (self.codes[0], stock.GetCodeName( self.codes[0]).decode('utf8')) ui.TradeResult_Boll(agl.where(policy.pl, policy.pl, pl), bars, \ stock.GuiYiHua(zhican),\ stock.GuiYiHua(bars['changwei']), title=title) if policy.pl is not None: #if policy.pl.explicit: policy.pl.publish()
def drawKline(df, df_trades=None): """画k线图, 异步模式 需要注意的是如果df比较大的话,那么速度是相当的慢, 一般5日线10天的数据较好 df : 日线或5分钟线, cols('ohlcv') df_trades : 交易点, 需要包含字段cols('trade_bSell', ['trade_price']), 见enum, []意思为不是必须 """ def df_to_matplotformat(df): """ return: list[turpl(t,o,h,l,c)] """ data_list = [] for dates,row in df.iterrows(): # 将时间转换为数字 #date_time = datetime.datetime.strptime(dates,'%Y-%m-%d') t = date2num(dates) open,high,low,close = row[:4] datas = (t,open,high,low,close) data_list.append(datas) return data_list quotes = df_to_matplotformat(df) plt.cla() # 创建一个子图 #fig, ax = plt.subplots(facecolor=(0.5, 0.5, 0.5)) #fig.subplots_adjust(bottom=0.2) ax = plt.gca() if 0: ax = matplotlib.axes.Axes(fig, rect) plt.subplots_adjust(bottom=0.2) ## 设置X轴刻度为日期时间 #ax.xaxis_date() ## X轴刻度文字倾斜45度 #plt.xticks(rotation=45) #plt.title("code") #plt.xlabel("time") #plt.ylabel("price") #mpf.candlestick_ohlc(ax,quotes,width=.001,colorup='r',colordown='green') #调整下面日期显示的密度 freq = len(quotes)/20 weekday_candlestick(quotes, ax, fmt='%b %d %H:%M', freq=freq, width=0.01, colorup='r',colordown='green') #plt.grid(True) #画交易点 if not agl.IsNone(df_trades): if 0:df_trades = pd.DataFrame() for index, row in df_trades.iterrows(): if AsynDrawKline.enum.trade_price in row.keys(): price = row[AsynDrawKline.enum.trade_price] else: price = row['c'] #交易点 trade_position = [] a = np.zeros(len(quotes)) a[:] = price index = len(df[:index]) a[:index] =np.nan bSell = int(row[AsynDrawKline.enum.trade_bSell]) clr = agl.where(bSell, 'g', 'r') plt.plot(a, color=clr, linewidth=0.25) plt.text(len(quotes),price, str(price), color=clr) #左右两边都有坐标 #ax.yaxis.set_ticks_position('both') #plt.tick_params(axis='y', which='both', labelleft='on', labelright='on') plt.draw() plt.pause(0.1)