def setStackCode(self): least = LeastSquare() draw = DrawPictureReal() loopBack = LoopBack() queryStock = QueryStock() queryStock.init(self.window) self.indexCloseDict = {}
def sendYouCanBuy(self, currentPath): query = QueryStock() codes = query.queryYouCanBuyStock() print(codes) self.tendown = [] self.other = [] for item in codes: temp = [] price = query.todayKlineByCode(item[0]) temp.append(item[0]) temp.append(item[1]) temp.append(item[4]) temp.append(item[5]) temp.append(price) if price <= 10: self.tendown.append(temp) else: self.other.append(temp) #主力、散户、反转信号 if item[5] == 1: self.Zsm.append(temp) if item[5] == 2: self.GSM.append(temp) self.tendown = sorted(self.tendown, key=lambda s: s[2], reverse=False) self.other = sorted(self.other, key=lambda s: s[2], reverse=False) self.Zsm = sorted(self.Zsm, key=lambda s: s[2], reverse=True) self.GSM = sorted(self.GSM, key=lambda s: s[2], reverse=True) self.doSendStockInfoBeautiful(self.Zsm, currentPath, "回踩反弹") self.doSendStockInfoBeautiful(self.GSM, currentPath, "底部吸筹") self.doSendStatisticForZsm() self.doSendStockInfoBeautiful(self.tendown, currentPath, " 10+元以内") self.doSendStockInfoBeautiful(self.other, currentPath, " 10-元以上") self.doSendStatisticPaper()
def scanStock(self): query = QueryStock() today = query.todayIsTrue()[0] connect = pymysql.Connect(host=self.connection.host, port=self.connection.port, user=self.connection.user, passwd=self.connection.passwd, db=self.connection.db, charset=self.connection.charset) # 获取游标 cursor = connect.cursor() tableCheckSql = "show tables like 'candidate_stock'" cursor.execute(tableCheckSql) if len(list(cursor)) == 0: createTable = "create table candidate_stock(id varchar(64) primary key not null,code varchar(64),name varchar(64),collect_date varchar(64),industry varchar(64),grad float,cv float,price float,now_price float,profit float,other varchar(45),is_down_line int)" cursor.execute(createTable) print( "-----------------------------scan stock------------------------------------" ) print("start time:" + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))) syn = StockInfoSyn() basicStock = syn.getBiscicStock() count = 0 for item in basicStock: count = count + 1 test = Application() print( str(count) + " " + item[0] + " " + item[1] + " " + item[2] + " " + item[3]) kk = test.execute(item[0]) if test.avgCostGrad < 0: candidateTemp = [] candidateTemp.append(item[0]) candidateTemp.append(item[1]) candidateTemp.append(item[3]) candidateTemp.append(test.avgCostGrad) self.candidate.append(candidateTemp) # 插入数据 sql = "select * from candidate_stock where code='%s' and collect_date='%s'" data = (item[0], today) cursor.execute(sql % data) if len(list(cursor)) == 0: print(item) sql = "INSERT INTO candidate_stock (id, code, name,collect_date,industry,grad,cv,is_down_line) VALUES ( '%s', '%s','%s', '%s','%s', %.8f, %.8f,%i)" data = (uuid.uuid1(), item[0], item[1], today, item[3], test.avgCostGrad, test.cvValue, test.isDownLine) cursor.execute(sql % data) connect.commit() # 垃圾回收 del kk, test if count == int(self.connection.scans): print("测试退出") break
def doSendStatisticPaper(self): query = QueryStock() successCount = 0 #暂时统计0.618以下的 result = query.queryStockYouBrought() htmls = "<table border='1'>" htmls = htmls + "<tr><td>代码</td><td>名称</td><td>买入时间</td><td>grad</td><td>cv</td><td>买入价格</td><td>当前价格</td><td>增长幅度100%</td></tr>" for item in result: htmls = htmls + "<tr>" if float(item[7]) > 0: successCount = successCount + 1 for vo in range(len(item)): if float(item[7]) > 0: htmls = htmls + "<td bgcolor='#FFCC66'><font color='red'>" + str( item[vo]) + "</font></td>" else: htmls = htmls + "<td bgcolor='#00FF00'><font color='blue'>" + str( item[vo]) + "</font></td>" htmls = htmls + "</tr>" htmls = htmls + "</table>" totalCount = len(result) endHtml = "增长个数:" + str( successCount) + "    总共个数:" + str( totalCount) + " </br> 百分比:" + str( successCount * 100 / totalCount) + "%" + htmls con = Connection() endDate = time.strftime('%Y-%m-%d', time.localtime(time.time())) my_pass = con.emailPass my_user = con.emaialUser sender = con.sender receivers = con.receivers msgRoot = MIMEMultipart('related') msgRoot['From'] = Header(str(endDate) + " 股票统计", 'utf-8') msgRoot['To'] = Header("测试", 'utf-8') subject = str(endDate) + ' 历史股票涨跌幅统计表' msgRoot['Subject'] = Header(subject, 'utf-8') msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) mail_msg = endHtml msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8')) try: smtpObj = smtplib.SMTP() smtpObj.connect('smtp.qq.com', 25) # 25 为 SMTP 端口号 smtpObj.login(my_user, my_pass) smtpObj.sendmail(sender, receivers, msgRoot.as_string()) print("邮件发送成功") except smtplib.SMTPException: print("Error: 无法发送邮件")
def sendYouCanBuy(self, currentPath): query = QueryStock() codes = query.queryYouCanBuyStock() print(codes) self.tendown = [] self.other = [] for item in codes: temp = [] price = query.todayKlineByCode(item[0]) temp.append(item[0]) temp.append(item[1]) temp.append(item[4]) temp.append(price) if price <= 10: self.tendown.append(temp) else: self.other.append(temp) self.tendown = sorted(self.tendown, key=lambda s: s[2], reverse=False) self.other = sorted(self.other, key=lambda s: s[2], reverse=False) # self.doSendStockInfoBeautiful(self.tendown,currentPath,"平民股票") # self.doSendStockInfoBeautiful(self.other,currentPath,"土豪股票") self.doSendStatisticPaper()
def fetchStocks(self): query = QueryStock() codeList = query.queryHistoryStock() for item in codeList: #拿到基期和当前时间的价格 priceList = query.fetchPriceList(item[1], item[3]) #利益差额的百分比 profit = (float(priceList[1][0]) - float(priceList[0][0])) * 100 / float(priceList[0][0]) #更新数据库 query.updateCandidate(item[0], priceList[0][0], priceList[1][0], profit, priceList[1][1])
class ApplicationWithDraw: window = 160 downlimit = -20 indexCloseDict = {} least = LeastSquare() draw = DrawPictureReal() loopBack = LoopBack() queryStock = QueryStock() avgCostGrad = 0 def setStackCode(self): least = LeastSquare() draw = DrawPictureReal() loopBack = LoopBack() queryStock = QueryStock() queryStock.init(self.window) self.indexCloseDict = {} # 筹码计算 def chipCalculate(self, result, start): chipCalculateList = [] for index, row in result.iterrows(): temp = [] currentIndex = index - start temp.append(currentIndex) temp.append(row['open']) temp.append(row['high']) temp.append(row['low']) temp.append(row['close']) temp.append(row['volume']) temp.append(row['tprice']) temp.append(row['turn']) temp.append(int(row['tradestatus'])) chipCalculateList.append(temp) calcualate = ChipCalculate() resultEnd = calcualate.getDataByShowLine(chipCalculateList, True) return resultEnd def executeForTest(self, code, savePath): result = self.queryStock.queryStock(code) if len(result[0]) < 200: return self return self.core(result[0], code, True, savePath, True) # 执行器 def execute(self, code, isShow, savePath): result = self.queryStock.queryStock(code) if len(result[0]) < 200: return self return self.core(result[0], code, isShow, savePath, False) # 核心调度器 def core(self, result, code, isShow, savePath, isTest): self.draw.showK(code, result, isShow, savePath) self.draw.isTest = isTest # 十四天 Kflag = self.least.everyErChengPrice(result, 14, True) # 三十天 erjieSlow = self.least.everyErChengPrice(result, 30, True) # 三天二阶导数 erjieK = self.least.doubleErJie(Kflag, 3, True) # 将收盘价转化为字典 testX = [] testY = [] H1 = [] H2 = [] H3 = [] for index, row in result.iterrows(): currentIndex = index - self.queryStock.start price = row['close'] testX.append(currentIndex) testY.append(price) tempH1 = row['h1'] tempH2 = row['h2'] tempH3 = row['h3'] if tempH1 == None: H1.append(0) else: H1.append(float(tempH1)) if tempH2 == None: H2.append(0) else: H2.append(float(tempH2)) if tempH3 == None: H3.append(0) else: H3.append(float(tempH3)) self.indexCloseDict = dict(zip(testX, testY)) self.draw.shenxianQS(testX, H1, H2, H3) # 一阶导数 wangX = [] wangY = [] for item in Kflag: kX = item[0] kk = item[1] wangX.append(kX) wangY.append(kk) self.draw.ax1Show(wangX, wangY) yijiedict = dict(zip(wangX, wangY)) # 二阶导数 wangX = [] wangY = [] for item in erjieK: kX = item[0] kk = item[1] wangX.append(kX) wangY.append(kk) self.draw.ax2Show(wangX, wangY) # 慢速一阶导数 wangXSlow = [] wangYSlow = [] for item in erjieSlow: kX1 = item[0] kk1 = item[1] wangXSlow.append(kX1) wangYSlow.append(kk1) self.draw.ax3showSlow(wangXSlow, wangYSlow) yijieSlowdict = dict(zip(wangXSlow, wangYSlow)) # 筹码计算 resultEnd = self.chipCalculate(result, self.queryStock.start) resultEnd.sort(key=lambda resultEnd: resultEnd[0]) resultEndLength = len(resultEnd) string = "" x = [] p = [] priceBigvolPriceIndexs = [] bigVolPrice = {} myUp = {} for i in range(len(resultEnd)): x.append(resultEnd[i][0]) string = string + "," + str(resultEnd[i][1]) p.append(resultEnd[i][1]) if i == resultEndLength - 1: priceJJJ = resultEnd[i][1] # 价格大于50%的筹码线 if resultEnd[i][5] == 1: priceBigvolPriceIndexs.append(resultEnd[i][0]) bigVolPrice[resultEnd[i][0]] = 1 if resultEnd[i][6] == 1: myUp[resultEnd[i][0]] = 1 # 主力散户反转信号 iList = [] zList = [] sList = [] fList = [] zsm = {} for index, row in result.iterrows(): iList.append(index - self.queryStock.start) z = float(row['z']) s = float(float(row['s'])) zList.append(z) sList.append(s) convert = int(row['m']) if convert == 1: fList.append(index - self.queryStock.start) if z > s and convert == 1: zsm[index - self.queryStock.start] = 1 myResult = pd.DataFrame() myResult['tprice'] = p tianjingle = self.least.everyErChengPriceForArray( np.array(x), np.array(p), 30) x1 = [] y1 = [] if tianjingle == None: return for item in tianjingle: kX = item[0] kk = item[1] x1.append(kX) y1.append(kk) pingjunchengbendic = dict(zip(x1, y1)) self.draw.ax3Show(x1, y1, 'r', '一阶导数') oldTwok = 0 oldOne = 0 # 牛顿策略 NewtonBuySall = [] downlimitTemp = 0 # 回测的缓存数据 buyList = [] sellList = [] total = len(result) for i in range(len(erjieK)): item = erjieK[i] currentx = item[0] twok = item[1] downParent = item[2] onek = yijiedict.get(currentx) onkslow = yijieSlowdict.get(currentx) onkchengben = pingjunchengbendic.get(currentx) buyTemp = [] sellTemp = [] if onek == None or onkslow == None or onkchengben == None: continue if onkslow < 0 and onkchengben < 0: onslowyestaday = yijieSlowdict.get(currentx - 1) chengbenyestaday = pingjunchengbendic.get(currentx - 1) if onslowyestaday == None or chengbenyestaday == None: continue if onslowyestaday < 0 and chengbenyestaday < 0 and onslowyestaday < onkslow and onkchengben < chengbenyestaday: buyTemp.append(currentx) buyTemp.append(twok) buyTemp.append("g") #筹码的上涨动力要足 if bigVolPrice.__contains__( currentx) and myUp.__contains__(currentx): buyTemp.append(1) else: buyTemp.append(0) buyList.append(buyTemp) if currentx == total - 1: self.avgCostGrad = onkchengben # 一阶导数大于0,二阶导数大于0,一阶导数大于二阶导数,二阶导数递减 if oldTwok > 0 and oldOne > 0 and oldTwok >= oldOne and onek > 0 and onek > twok: sellTemp.append(currentx) sellTemp.append(twok) sellTemp.append("r") sellList.append(sellTemp) if oldOne > 0 and onek > 0 and oldOne > onek and oldTwok > oldOne and onek > twok: # 添加历史回测里 sellTemp.append(currentx) sellTemp.append(twok) sellTemp.append("r") sellList.append(sellTemp) if onek > 0 and oldOne < 0: # 添加历史回测里 sellTemp.append(currentx) sellTemp.append(twok) sellTemp.append("orange") sellList.append(sellTemp) # 一阶导数小于0,二阶导数小于0,一阶导数小于二阶导数,二阶导数递增,并且在之前的三天都被一阶导数压制 if onek <= 0 and twok > onek and oldTwok < oldOne and downParent < self.downlimit and abs( twok - oldTwok) > abs(onek - oldOne): # 添加到历史回测里 buyTemp.append(currentx) buyTemp.append(twok) buyTemp.append("g") if bigVolPrice.__contains__(currentx): buyTemp.append(1) else: buyTemp.append(0) buyList.append(buyTemp) oldTwok = twok oldOne = onek # 画线条 self.draw.klineInfo(buyList, sellList) # 找到最小的那一个 for item in erjieK: if item[1] != None and item[1] < downlimitTemp: downlimitTemp = item[1] downlimitTemp = abs(downlimitTemp) self.draw.drawDownLine(abs(downlimitTemp) * (self.downlimit / 100)) for item in erjieK: item[2] = item[1] / downlimitTemp * 100 # self.loopBack.testNewTon(NewtonBuySall,self.indexCloseDict) # self.draw.ax5Show(self.loopBack.baseRmb,self.loopBack.buysell,self.loopBack.myRmb) self.draw.ax5ShowZsm(zsm, fList, priceBigvolPriceIndexs, iList, zList, sList) self.draw.savePng() return self
class Application: window = 160 downlimit = -20 indexCloseDict = {} least = LeastSquare() loopBack = LoopBack() queryStock = QueryStock() avgCostGrad = 0 cvValue = -1 maxPrice = 0 currentPrice = 0 isDownLine = 0 def setStackCode(self): least = LeastSquare() draw = DrawPicture() loopBack = LoopBack() queryStock = QueryStock() queryStock.init(self.window) self.indexCloseDict = {} return #筹码计算 def chipCalculate(self, result, start, isProd): chipCalculateList = [] for index, row in result.iterrows(): temp = [] currentIndex = index - start temp.append(currentIndex) temp.append(row['open']) temp.append(row['high']) temp.append(row['low']) temp.append(row['close']) temp.append(row['volume']) temp.append(row['tprice']) temp.append(row['turn']) temp.append(int(row['tradestatus'])) chipCalculateList.append(temp) if isProd == False: chipCalculateList = chipCalculateList[-112:] calcualate = ChipCalculate() resultEnd = calcualate.getDataByShowLine(chipCalculateList) del calcualate return resultEnd def cv(self, temp): # print(temp) # minTemp=temp[0][1] # for i in range(len(temp)): # if temp[i][1]!=0 and temp[i][1]<minTemp: # minTemp=temp[i][1] # print(minTemp) # temp[:,1]=temp[:,1]-minTemp sumF = np.sum(temp[:, 1]) sumfx = 0 sumfdoubleX = 0 for i in range(len(temp)): #次数 f = temp[i][1] price = (temp[i][0] / 100) sumfx = sumfx + f * price sumfdoubleX = sumfdoubleX + f * price * price sumfx = sumfx * sumfx rightup = sumfx / sumF result = math.sqrt((sumfdoubleX - rightup) / sumF) print("--方差" + str(result)) return result #执行器 def execute(self, code): result = self.queryStock.queryStock(code) if len(result[0]) < 200: return self return self.core(result[0], result[1]) #核心调度器 def core(self, result, maxPrice): self.maxPrice = maxPrice #十四天 Kflag = self.least.everyErChengPrice(result, 14, False) #三十天 erjieSlow = self.least.everyErChengPrice(result, 30, False) # 三天二阶导数 erjieK = self.least.doubleErJie(Kflag, 3, False) #慢速一阶导数 wangXSlow = [] wangYSlow = [] for item in erjieSlow: kX1 = item[0] kk1 = item[1] wangXSlow.append(kX1) wangYSlow.append(kk1) yijieSlowdict = dict(zip(wangXSlow, wangYSlow)) # 筹码计算 resultEnd = self.chipCalculate(result, self.queryStock.start, False) choumaList = np.array(resultEnd[2][2]) x = [] p = [] resultEnd.sort(key=lambda resultEnd: resultEnd[0]) for i in range(len(resultEnd)): x.append(resultEnd[i][0]) p.append(resultEnd[i][1]) myResult = pd.DataFrame() myResult['tprice'] = p tianjingle = self.least.everyErChengPriceForArray( np.array(x), np.array(p), 30) x1 = [] y1 = [] if tianjingle == None: return for item in tianjingle: kX = item[0] kk = item[1] x1.append(kX) y1.append(kk) pingjunchengbendic = dict(zip(x1, y1)) total = len(result) for i in range(len(erjieK)): item = erjieK[i] currentx = item[0] onkslow = yijieSlowdict.get(currentx) onkchengben = pingjunchengbendic.get(currentx) if onkslow == None or onkchengben == None: continue if onkslow < 0 and onkchengben < 0: onslowyestaday = yijieSlowdict.get(currentx - 1) chengbenyestaday = pingjunchengbendic.get(currentx - 1) if onslowyestaday == None or chengbenyestaday == None: continue if onslowyestaday < 0 and chengbenyestaday < 0 and onslowyestaday < onkslow and onkchengben < chengbenyestaday: if currentx == total - 1: self.avgCostGrad = onkchengben self.cvValue = self.cv(choumaList) self.currentPrice = float(result['close'][len(result) - 1]) if self.currentPrice <= self.maxPrice * 0.618: self.isDownLine = 1 else: self.isDownLine = 0 print(self.currentPrice) print(self.maxPrice) print(self.isDownLine) self.least = None self.loopBack = None self.queryStock = None return self
def doSendStatisticForZsm(self): query = QueryStock() result = query.queryStockYouBrought("zsm=1") self.sendStatistic(result, " 回踩反弹-统计") result = query.queryStockYouBrought("zsm=2") self.sendStatistic(result, " 底部吸筹-统计")
def doSendStatisticPaper(self): query = QueryStock() #暂时统计0.618以下的 result = query.queryStockYouBrought( "is_down_line=1 and profit!=0 and price<=10 and price>3") self.sendStatistic(result, " zMain吸筹统计")