def updateStockOtherInfo(): sql = unicode("select code,name from s_stock_info order by code asc") stockList = select(sql) for stock in stockList: code = stock[0] if int(code) < 601126: continue selectInfoSql = unicode( "select date,closePrice from s_stock where code='{0}' order by date asc" ).format(code) data = select(selectInfoSql) writeLog(unicode("更新股票其他指标数据: code: {0}").format(code)) updataStockBias(code, data, 6) updataStockBias(code, data, 12) updataStockBias(code, data, 24) updateStockMA(code, data, 5) updateStockMA(code, data, 10) updateStockMA(code, data, 20) updateStockMA(code, data, 30) updateStockMA(code, data, 60) updateStockMA(code, data, 120) updateStockMA(code, data, 250) updateStockChangePercent(code, data)
def getStockHistoryInfo(): stockList = loadJsonConfig( os.path.abspath( os.path.join(os.getcwd(), "../config/newStockList.json"))) startDate = '2014-07-01' endDate = '2017-07-06' writeLog(unicode("开始查询股票历史行情数据,股票池:{0}").format(stockList)) for stock in stockList: code = stock[0] data = getHistoryData(code, startDate, endDate) insertSql = unicode( "INSERT INTO s_stock VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" ) parameters = [] for i in range(0, len(data)): date = data.index[i] open = data.iloc[i]['open'] close = data.iloc[i]['close'] high = data.iloc[i]['high'] low = data.iloc[i]['low'] volume = data.iloc[i]['volume'] changePercent = data.iloc[i]['p_change'] turnover = data.iloc[i]['turnover'] parameters.append([ code, date, -1, -1, -1, volume, -1, high, low, open, close, changePercent, -1, turnover, -1, -1, -1, -1, -1, -1, -1, int(time.mktime(time.strptime(date, '%Y-%m-%d'))), -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ]) batchInsert(insertSql, parameters) writeLog(unicode("查询股票历史行情数据完成"))
def updateBiasData(startDate): stockList = select( unicode("SELECT code,name from s_stock_info") ) # loadJsonConfig(os.path.abspath(os.path.join(os.getcwd(), "../config/goodStockList.json"))) for stock in stockList: code = stock[0] writeLog(unicode("开始更新股票:{0},名称:{1}的Bias数据").format(code, stock[1])) sql = unicode( "SELECT code,date,closePrice from s_stock where code='{0}' and date>'{1}' ORDER BY timestamp asc" ).format(code, startDate) data = select(sql) MA6 = calculateMA(6, data) MA12 = calculateMA(12, data) MA24 = calculateMA(24, data) for i in range(0, len(data)): date = data[i][1] closePrice = float(data[i][2]) MA6data = float(MA6.get(date)) MA12data = float(MA12.get(date)) MA24data = float(MA24.get(date)) bias1 = 0 if MA6data == 0 else round( (closePrice - MA6data) * 100 / MA6data, 2) bias2 = 0 if MA12data == 0 else round( (closePrice - MA12data) * 100 / MA12data, 2) bias3 = 0 if MA24data == 0 else round( (closePrice - MA24data) * 100 / MA24data, 2) updateSql = unicode( "update s_stock set bias1={0},bias2={1},bias3={2} where code='{3}' and date='{4}'" ).format(bias1, bias2, bias3, code, date) execute(updateSql)
def updateEXPMA(): sql = unicode( "select code,date from s_stock_tech where EXPMA1=0 and EXPMA2=0 ORDER by code,date asc") data = select(sql) if len(data) <= 0: writeLog(unicode("没有获取到无效EXPMA指标数据")) return for item in data: code = item[0] date = item[1] try: data = getEXPMA(code, date) if data is None: continue updateSql = unicode( "update s_stock_tech set EXPMA1={0},EXPMA2={1} where code='{2}' and date='{3}'").format( data[0], data[1], code, date) execute(updateSql) except Exception, e: writeErrorLog(unicode("更新EXPMA指标数据异常,code:{0}, date:{1}, e:{2}").format(code, date, str(e)))
def updateTodayBiasData(): stockList = select( unicode("SELECT code,name from s_stock_info") ) # loadJsonConfig(os.path.abspath(os.path.join(os.getcwd(), "../config/goodStockList.json"))) today = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d') for stock in stockList: code = stock[0] writeLog(unicode("开始更新股票:{0},名称:{1} 今日的Bias数据").format(code, stock[1])) sql = unicode( "select code,closePrice from s_stock where code='{0}' and date='{1}'" ).format(code, today) data = select(sql) if (len(data) <= 0): writeLog( unicode("没有获取到今日的收盘价数据, code: {0}, date: {1}").format( code, today)) continue closePrice = float(data[0][1]) MA6 = float(getMAData(6, code, today)) MA12 = float(getMAData(12, code, today)) MA24 = float(getMAData(24, code, today)) bias1 = 0 if MA6 == 0 else round((closePrice - MA6) * 100 / MA6, 2) bias2 = 0 if MA12 == 0 else round((closePrice - MA12) * 100 / MA12, 2) bias3 = 0 if MA24 == 0 else round((closePrice - MA24) * 100 / MA24, 2) updateSql = unicode( "update s_stock set bias1={0},bias2={1},bias3={2} where code='{3}' and date='{4}'" ).format(bias1, bias2, bias3, code, today) execute(updateSql)
def getHighLowData(code): today = datetime.now() threeYearsAgo = today - timedelta(days=365 * 5) data = getHistoryData(code, threeYearsAgo.strftime('%Y-%m-%d'), today.strftime('%Y-%m-%d')) totalHigh = 0 maxHigh = 0 for date in data[0]: totalHigh = totalHigh + data[0][date] if (data[0][date] > maxHigh): maxHigh = data[0][date] totalLow = 0 minLow = 9999999 for date in data[1]: totalLow = totalLow + data[1][date] if (data[1][date] < minLow): minLow = data[1][date] avg = (totalHigh + totalLow) / (2 * len(data[0])) avg = round(float(avg), 2) writeLog( unicode( "股票代码:{5},三年最高价:{0},最低价:{1},均价:{2},最高价均价:{3},最低价均价:{4}").format( maxHigh, minLow, avg, round(float(totalHigh / len(data[0])), 2), round(float(totalLow / len(data[1])), 2), code)) # totalHigh,maxHigh,len(data[0]),totalLow,minLow,len(data[1]) return StockData(maxHigh, minLow, avg)
def getStockInfo(code): bit = 1 if code.startswith("6") else 2 url = 'http://nuff.eastmoney.com/EM_Finance2015TradeInterface/JS.ashx?id=' + code + str( bit) + '&_=149941' + str(random.randint(1000000, 9999999)) res = httpGet(url) res = res[9:-1] writeLog(unicode("getStockInfo, url:{0}, resule:{1} ").format(url, res)) jo = json.loads(res) data = jo['Value'] result = {} result['limitUp'] = data[23] result['limitDown'] = data[24] result['avgPrice'] = data[26] result['volume'] = data[31] result['amount'] = data[35] result['highPrice'] = data[30] result['lowPrice'] = data[32] result['openPrice'] = data[28] result['closePrice'] = data[25] result['changePercent'] = data[29] result['changeAmount'] = data[27] result['turnOverRatio'] = data[37] result['QRR'] = data[36] result['totalValue'] = data[46] result['circulatedValue'] = data[45] result['PE'] = 0 if data[38] == '-' else data[38] result['PTB'] = 0 if data[43] == '-' else data[43] result['internalPan'] = data[40] result['externalPan'] = data[39] result['code'] = code return None if float(result['closePrice']) == 0 else result
def updateMAData(startDate): stockList = select( unicode("SELECT code,name from s_stock_info") ) # loadJsonConfig(os.path.abspath(os.path.join(os.getcwd(), "../config/goodStockList.json"))) for stock in stockList: code = stock[0] writeLog(unicode("开始更新股票:{0},名称:{1}的均线数据").format(code, stock[1])) sql = unicode( "SELECT code,date,closePrice from s_stock where code='{0}' and date>'{1}' ORDER BY timestamp asc" ).format(code, startDate) data = select(sql) MA5 = calculateMA(5, data) MA10 = calculateMA(10, data) MA20 = calculateMA(20, data) MA30 = calculateMA(30, data) MA60 = calculateMA(60, data) MA120 = calculateMA(120, data) MA250 = calculateMA(250, data) for i in range(0, len(data)): date = data[i][1] updateSql = unicode( "update s_stock set MA5={0},MA10={1},MA20={2},MA30={3},MA60={4},MA120={5},MA250={6} where code='{7}' and date='{8}'" ).format(MA5.get(date), MA10.get(date), MA20.get(date), MA30.get(date), MA60.get(date), MA120.get(date), MA250.get(date), code, date) execute(updateSql)
def updateMACD(): sql = unicode( "select code,date,macd,dif,dea from s_stock_tech where MACD=0 and dif=0 and dea=0 ORDER by code,date asc") data = select(sql) if len(data) <= 0: writeLog(unicode("没有获取到无效MACD指标数据")) return for item in data: code = item[0] date = item[1] try: data = getMACD(code, date) if data is None: continue updateSql = unicode( "update s_stock_tech set macd={0},dif={1},dea={2} where code='{3}' and date='{4}'").format( data[0], data[1], data[2], code, date) execute(updateSql) except Exception, e: writeErrorLog(unicode("更新MACD指标数据异常,code:{0}, date:{1}, e:{2}").format(code, date, str(e)))
def checkMACD(code, tomorrow): sql = unicode( "SELECT dif,macd,dea,date from s_stock_tech where code='{0}' and date<'{1}' ORDER by date desc limit 5" ).format(code, tomorrow) data = select(sql) if data is None or len(data) < 5: return isGoldFork = isMACDGoldFork(data) # 黄金叉 isBottomFallAway = isMACDBottomFallAway(data) # 底背离 needBuy = isGoldFork or isBottomFallAway buyRemark = unicode("可以考虑买入,原因:{0},{1}").format( "出现黄金叉" if isGoldFork else "", "出现底背离" if isBottomFallAway else "") isDeadFork = isMACDDeadFork(data) # 死叉 isTopFallAway = isMACDTopFallAway(data) # 顶背离 needSell = isDeadFork or isTopFallAway sellRemark = unicode("可以考虑卖出,原因:{0},{1}").format( "出现死叉" if isDeadFork else "", "出现顶背离" if isTopFallAway else "") writeLog( unicode("[买入卖出信号] code:{0}, date:{1}, remark:{2}").format( code, tomorrow, buyRemark if needBuy else (sellRemark if needSell else "")))
def getMACD(code, date): techSql = unicode( "SELECT DIF,EXPMA1,DEA from s_stock_tech where code='{0}' and date<'{1}' ORDER by date desc limit 1").format( code, date) data = select(techSql) if len(data) <= 0: return None yesterdayDIF = data[0][0] yesterdayEMA12 = data[0][1] yesterdayDEA = data[0][2] yesterdayEMA26 = yesterdayEMA12 - yesterdayDIF todayClosePrice = getTodayClosePrice(code, date) if todayClosePrice is None: return None todayEMA12 = round((2 * todayClosePrice + 11 * yesterdayEMA12) / 13, 2) todayEMA26 = round(2 * float(todayClosePrice) / 27, 2) + round(25 * float(yesterdayEMA26) / 27, 2) todayDIF = round(todayEMA12 - todayEMA26, 2) todayDEA = round((8 * float(yesterdayDEA) + todayDIF * 2) / 10, 2) todayMACD = (todayDIF - todayDEA) * 2 writeLog(unicode("更新MACD指标数据,code:{0},date:{1},todayDIF:{2},todayDEA:{3},todayMACD:{4}").format(code, date, todayDIF, todayDEA, todayMACD)) print code, date, todayDIF, todayDEA, todayMACD return (todayMACD, todayDIF, todayDEA)
def startServer(): try: bot = Bot('bot.pkl', console_qr=True) master = ensure_one(bot.friends().search(unicode('踏雪'))) log_group = ensure_one(bot.friends().search(unicode('期待'))) token = '295cc3d8-c977-11e6-a341-0090f5f61084' writeLog(unicode("receiver: {0}, {1}").format(master, log_group)) listen(bot, [master, log_group], token=token, port=9090, status_report=True, status_receiver=master) except Exception, e: writeErrorLog(unicode("receive message error: {0}").format(str(e)))
def runTask(): if datetime.today().weekday() < 5 and datetime.now().hour >= 23 and datetime.now().hour < 24 and datetime.now().minute < 20: sendMessageToMySelf(unicode("开始计算今日技术指标数据")) begin = datetime.now() initMysql() updateKDJ() disconnect() end = datetime.now() message = unicode("计算今日技术指标数据的任务执行完毕,当前时间:{0},执行用时:{1}").format(datetime.now(), end - begin) writeLog(message) sendMessageToMySelf(message) t = Timer(900, runTask) t.start()
def updateKDJ(): sql = unicode("SELECT code,date,k,d,j from s_stock_tech where K=0 and d=0 and j=0 ORDER by code,date asc") data = select(sql) if len(data) <= 0: writeLog(unicode("没有获取到无效KDJ指标数据")) return for item in data: code = item[0] date = item[1] try: rsv = getRSV(code, date) if rsv is None: continue techSql = unicode( "SELECT k,d,j from s_stock_tech where code='{0}' and date<'{1}' ORDER by date desc limit 1").format( code, date) data = select(techSql) yesterdayK = 50 yesterdayD = 50 if len(data) > 0: yesterdayK = data[0][0] yesterdayD = data[0][1] todayK = getFloat((rsv + 2 * float(yesterdayK)) / 3) todayD = getFloat((todayK + 2 * float(yesterdayD)) / 3) todayJ = getFloat(3 * todayK - 2 * todayD) writeLog(unicode("更新KDJ指标数据,code:{0},date:{1},todayK:{2},todayD:{3},todayJ:{4},rsv:{5}").format(code, date, todayK, todayD, todayJ, rsv)) print code, date, todayK, todayD, todayJ, rsv updateSql = unicode("update s_stock_tech set k={0},d={1},j={2} where code='{3}' and date='{4}'").format( todayK, todayD, todayJ, code, date) execute(updateSql) except Exception, e: writeErrorLog(unicode("更新KDJ指标数据异常,code:{0}, date:{1}, e:{2}").format(code, date, str(e)))
def updateTodayMAData(): stockList = select( unicode("SELECT code,name from s_stock_info") ) # loadJsonConfig(os.path.abspath(os.path.join(os.getcwd(), "../config/goodStockList.json"))) for stock in stockList: code = stock[0] writeLog(unicode("开始更新股票:{0},名称:{1} 今日的均线数据").format(code, stock[1])) MA5 = getMAData(5, code) MA10 = getMAData(10, code) MA20 = getMAData(20, code) MA30 = getMAData(30, code) MA60 = getMAData(60, code) MA120 = getMAData(120, code) MA250 = getMAData(250, code) updateSql = unicode( "update s_stock set MA5={0},MA10={1},MA20={2},MA30={3},MA60={4},MA120={5},MA250={6} where code='{7}' and date='{8}'" ).format(MA5, MA10, MA20, MA30, MA60, MA120, MA250, code, datetime.now().strftime('%Y-%m-%d')) execute(updateSql)
def main(argv): try: reload(sys) sys.setdefaultencoding('utf-8') # sendMessageToMySelf(unicode("开始查询股票历史行情数据")) begin = datetime.now() initMysql() # getStockHistoryInfoFromDb() # getStockHistoryInfoFromConfig() updateStockOtherInfo() disconnect() end = datetime.now() message = unicode("查询股票历史行情数据的任务执行完毕,当前时间:{0},执行用时:{1}").format( datetime.now(), end - begin) writeLog(message) sendMessageToMySelf(message) except: writeExceptionLog('RealTimeRemindTask Error.')
def getTechParamter(code): sys.setdefaultencoding('gbk') url = 'http://stock.quote.stockstar.com/tech_' + code + '.shtml' res = httpGet(url) pattern = re.compile(r'<div class=\"listInfo\">([\s\S]*)</table>') tableData = pattern.search(res) pattern = re.compile(r'<td.*?>(.*?)</td>') tdData = pattern.findall(tableData.group()) dictData = {} dictStatus = {} writeLog(unicode("getTech: code: {0}, url:{1}").format(code, url)) for i in range(0, len(tdData) - 2): key = tdData[i].strip() data = tdData[i + 1] dictData[key] = 0 if '--' in data else data dictStatus[key] = unicode(tdData[i + 2]) # print code, dictData stockTechInfo = StockTechInfo(code, dictData) pattern = re.compile(r'<p class=\"lf\">(.*?)</p>') techStatus = pattern.search(res) bulls = 0 bears = 0 notsure = 0 if techStatus is not None: pattern = re.compile(r'\d+') numbers = pattern.findall(techStatus.group()) if numbers is not None: bulls = numbers[1] bears = numbers[2] notsure = numbers[3] stockTechStatus = StockTechStatus(code, dictStatus, bulls, bears, notsure) forecastInfo = getGainForecast(stockTechStatus) return (stockTechInfo, stockTechStatus, forecastInfo)
def getStockInfos(code, year): try: url = "http://d.10jqka.com.cn/v2/line/hs_{0}/01/{1}.js".format( code, year) res = httpGet(url).decode("utf-8") index = res.find("(") if (index < 0): writeErrorLog( unicode("解析行情失败: code:{0}, year:{1}, res:{2}").format( code, year, res)) return [] res = res[index + 1:-1] writeLog(unicode("获取股票历史行情: code: {0}, year:{1}").format(code, year)) jo = json.loads(res) dataInfo = jo['data'].split(';') result = {} for item in dataInfo: infos = item.split(',') dic = {} dic['open'] = infos[1] dic['high'] = infos[2] dic['low'] = infos[3] dic['close'] = infos[4] dic['volume'] = infos[5] dic['amount'] = "{0}亿".format(round( float(infos[6]) / 100000000, 1)) result[datetime.strptime(infos[0], '%Y%m%d').strftime('%Y-%m-%d')] = dic return result except Exception, e: writeErrorLog( unicode("解析行情失败: code:{0}, year:{1}, e:{2}").format( code, year, str(e))) if "404" in str(e): return [] else: return None
def getEXPMA(code, date): techSql = unicode( "SELECT EXPMA1,EXPMA2 from s_stock_tech where code='{0}' and date<'{1}' ORDER by date desc limit 1").format( code, date) data = select(techSql) if len(data) <= 0: return None yesterdayEXPMA1 = data[0][0] yesterdayEXPMA2 = data[0][1] todayClosePrice = getTodayClosePrice(code, date) if todayClosePrice is None: return None todayEXPMA1 = getRound((2 * todayClosePrice + 11 * yesterdayEXPMA1) / 13) todayEXPMA2 = getRound((2 * todayClosePrice + 49 * yesterdayEXPMA2) / 51) writeLog(unicode("更新EXPMA指标数据,code:{0},date:{1},todayEXPMA1:{2},todayEXPMA1:{3}").format(code, date, todayEXPMA1, todayEXPMA2)) return (todayEXPMA1, todayEXPMA2)
def main(argv): reload(sys) sys.setdefaultencoding('utf-8') initWeChat() codeList = [ '601318', '601939', '600282', '601166', '601633', '000002', '600104', '600393', '600029', '600971', '600581', '600758' ] boughtList = { '601318': 49.101, '600393': 7.493, '600282': 3.65, '600029': 8.91 } stockDatas = {} for code in codeList: stockData = getHighLowData(code) stockDatas[code] = stockData # print '\n' sendAlready = {} while 1 == 1: importantData = [] for code in codeList: df = ts.get_realtime_quotes(code) writeLog( unicode( "代码:{0},名称:{1},三年最高价:{2},最低价:{3},均价:{4},当前价格:{5},竞买价:{6},竞卖价:{7},成交量:{8},成交金额:{9} " ).format(code, df['name'].values[0], stockDatas[code].maxHigh, stockDatas[code].minLow, stockDatas[code].avg, df['price'].values[0], df['bid'].values[0], df['ask'].values[0], df['volume'].values[0], df['amount'].values[0])) canBuyPrice = float(stockDatas[code].avg * 0.8) canSellPrice = float(stockDatas[code].avg * 1.5) if (float(df['bid'].values[0]) <= canBuyPrice): msg = unicode( '代码:{2},名称:{3},当前买入价为: {0}, 历史均价为:{1}, 买入价小于均价的80%,可以考虑买入\n' ).format(df['bid'].values[0], stockDatas[code].avg, code, df['name'].values[0]) importantData.append(msg) if (float(df['ask'].values[0]) >= canSellPrice): msg = unicode( '代码:{2},名称:{3},当前卖出价为: {0}, 历史均价为:{1}, 卖出价大于均价的150%,可以考虑卖出\n' ).format(df['ask'].values[0], stockDatas[code].avg, code, df['name'].values[0]) importantData.append(msg) if boughtList.has_key(code): # print float(df['ask'].values[0]),float(boughtList[code]) if (float(df['ask'].values[0]) >= float(boughtList[code])): msg = unicode( '代码:{2},名称:{3},当前卖出价为: {0}, 成本为:{1}, 可以考虑卖出\n').format( df['ask'].values[0], boughtList[code], code, df['name'].values[0]) importantData.append(msg) sendWeChatMessage('\n'.join(importantData)) time.sleep(30)
def reminder(): reminderCodeList = open( os.path.abspath(os.path.join(os.getcwd(), "../config/reminder.csv")), 'r').readlines() dictReminder = {} for i in range(1, len(reminderCodeList)): infos = reminderCodeList[i].split(',') code = infos[0].strip().zfill(6) name = getPE(code)[0] maxPrice = float(infos[1]) minPrice = float(infos[2]) upPercent = float(infos[3]) downPercent = float(infos[4]) receiver = int(infos[5]) dictReminder[code] = ReminderInfo(maxPrice, minPrice, upPercent, downPercent, receiver, code, name) checkDict = {} # 用于检查今天是否已经发送过某类信息 date = datetime.now().strftime('%Y-%m-%d') result = [] result.append( unicode("{0},{1},{2},{3},{4},{5}\n").format( '股票代码', '股票涨到多少元', '股票跌到多少元', '股票涨幅超过多少(%)', '股票跌幅超过多少(%)', '发给谁(0:期待,1:踏雪)').encode('gbk')) while 1 == 1: if datetime.now().hour >= 16: # 更新提醒数据 for i in range(1, len(reminderCodeList)): infos = reminderCodeList[i].split(',') code = infos[0].strip().zfill(6) name = getPE(code)[0] maxPrice = float(infos[1]) minPrice = float(infos[2]) upPercent = float(infos[3]) downPercent = float(infos[4]) receiver = int(infos[5]) stockInfo = getStockInfo(code) if stockInfo is None: continue highPrice = float(stockInfo['highPrice']) closePrice = float(stockInfo['closePrice']) changePercent = float(stockInfo['changePercent']) newMinPrice = getAboveNumber(closePrice * 0.97) minPrice = minPrice if minPrice == -1 or changePercent <= 0 or newMinPrice <= minPrice else newMinPrice maxPrice = maxPrice if maxPrice == -1 or changePercent <= 0 else getAboveNumber( highPrice * 1.03) result.append( unicode("{0},{1},{2},{3},{4},{5}\n").format( code, maxPrice, minPrice, upPercent, downPercent, receiver).encode('gbk')) saveFileName = os.path.abspath( os.path.join(os.getcwd(), "../config/reminder.csv")) writeFile(saveFileName, result) writeLog(unicode("止损表已经修正为以下值:{0}").format(result)) sendMessageToMySelf(unicode("止损表已经修正为以下值:{0}").format(result)) break for key in dictReminder: df = ts.get_realtime_quotes(key) reminderInfo = dictReminder[key] price = float(df['price'].values[0]) pre_close = float(df['pre_close'].values[0]) currentUpPercent = 0 if price <= pre_close else round( (price - pre_close) * 100 / pre_close, 2) currentDownPercent = 0 if price >= pre_close else round( (price - pre_close) * 100 / pre_close, 2) print key, price, reminderInfo.maxPrice, reminderInfo.minPrice, currentUpPercent, currentDownPercent if (price != 0 and reminderInfo.maxPrice != -1 and price >= reminderInfo.maxPrice): checkKey = unicode('{0}_{1}_{2}').format(date, key, 'max') if checkDict.has_key(checkKey) == False: message = unicode( '股票代码:{0},名称:{3},当前价格为:{1},已经超过您预设的{2}').format( key, price, reminderInfo.maxPrice, reminderInfo.name) writeInfoLog(message) sendMessageToMySelf( message ) if reminderInfo.receiver == 1 else sendMessageToBaby( message) checkDict[checkKey] = True if (price != 0 and reminderInfo.minPrice != -1 and price <= reminderInfo.minPrice): checkKey = unicode('{0}_{1}_{2}').format(date, key, 'min') if checkDict.has_key(checkKey) == False: message = unicode( '股票代码:{0},名称:{3},当前价格为:{1},已经低于您预设的{2}').format( key, price, reminderInfo.minPrice, reminderInfo.name) writeInfoLog(message) sendMessageToMySelf( message ) if reminderInfo.receiver == 1 else sendMessageToBaby( message) checkDict[checkKey] = True if (price != 0 and reminderInfo.upPercent != -1 and currentUpPercent >= reminderInfo.upPercent): checkKey = unicode('{0}_{1}_{2}').format(date, key, 'up') if checkDict.has_key(checkKey) == False: message = unicode( '股票代码:{0},名称:{4},当前价格为:{1},涨幅为:{2}%,已经超过您预设的{3}%' ).format(key, price, currentUpPercent, reminderInfo.upPercent, reminderInfo.name) writeInfoLog(message) sendMessageToMySelf( message ) if reminderInfo.receiver == 1 else sendMessageToBaby( message) checkDict[checkKey] = True if (price != 0 and reminderInfo.downPercent != -1 and currentDownPercent <= -reminderInfo.downPercent): checkKey = unicode('{0}_{1}_{2}').format(date, key, 'down') if checkDict.has_key(checkKey) == False: message = unicode( '股票代码:{0},名称:{4},当前价格为:{1},跌幅为:{2}%,已经低于您预设的{3}%' ).format(key, price, currentDownPercent, -reminderInfo.downPercent, reminderInfo.name) writeInfoLog(message) sendMessageToMySelf( message ) if reminderInfo.receiver == 1 else sendMessageToBaby( message) checkDict[checkKey] = True time.sleep(1)
import sys import os sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), ".."))) from wxpy import * from wechat_sender import * from common.LoggerHelper import writeLog, writeErrorLog reload(sys) sys.setdefaultencoding('utf-8') try: bot = Bot('bot.pkl', console_qr=True) master = ensure_one(bot.friends().search(unicode('踏雪'))) log_group = ensure_one(bot.friends().search(unicode('期待'))) token = '295cc3d8-c977-11e6-a341-0090f5f61084' writeLog(unicode("receiver: {0}, {1}").format(master, log_group)) listen(bot, [master, log_group], token=token, port=9090, status_report=True, status_receiver=master) except Exception, e: writeErrorLog(unicode("receive message error: {0}").format(str(e)))
def checkAvgLine(fileName, stockList, needSaveToDb=True): result = [] result.append( unicode("{0},{5},{1},{2},{3},{4}\n").format("代码", "类别", "昨日最高价", "今日最高价", "MaN", "名称").encode('gbk')) i = 0 weekday = datetime.today().weekday() datediff = 3 if weekday == 0 else (weekday - 4 if weekday == 6 else 1) date = (datetime.now() - timedelta(days=datediff)).strftime('%Y-%m-%d') while i < len(stockList): code = stockList[i][0] name = stockList[i][1] try: sql = unicode( "SELECT code,date,MA5,MA10,MA20,MA30,MA60,MA120,MA250 from s_stock where code='{0}' and date='{1}'" ).format(code, date) data = select(sql) if (len(data) <= 0): writeLog( unicode("没有获取到均值数据, code: {0}, date: {1}").format( code, date)) i = i + 1 continue ma5 = data[0][2] ma10 = data[0][3] ma30 = data[0][5] ma60 = data[0][6] ma120 = data[0][7] ma250 = data[0][8] yesterdayPrice = StockInfo.getNPrice(code, 1, 'high') realTimePrice = float(getRealTimeData(code)) if (yesterdayPrice != 0 and realTimePrice != 0 and yesterdayPrice <= ma5 and realTimePrice >= ma5): # 击穿5日均线,并上涨 result.append( unicode("{0},{5},{1},{2},{3},{4}\n").format( code, '5up', yesterdayPrice, realTimePrice, ma5, name).encode('gbk')) writeLog( unicode( "[5up] code:{0}, yesterdayPrice: {1}, realTimePrice: {2}, ma5: {3}" ).format(code, yesterdayPrice, realTimePrice, ma5)) if (yesterdayPrice != 0 and realTimePrice != 0 and yesterdayPrice <= ma10 and realTimePrice >= ma10): # 击穿10日均线,并上涨 result.append( unicode("{0},{5},{1},{2},{3},{4}\n").format( code, '10up', yesterdayPrice, realTimePrice, ma10, name).encode('gbk')) writeLog( unicode( "[10up] code:{0}, yesterdayPrice: {1}, realTimePrice: {2}, ma10: {3}" ).format(code, yesterdayPrice, realTimePrice, ma10)) if (yesterdayPrice != 0 and realTimePrice != 0 and yesterdayPrice <= ma30 and realTimePrice >= ma30): # 击穿30日均线,并上涨 result.append( unicode("{0},{5},{1},{2},{3},{4}\n").format( code, '30up', yesterdayPrice, realTimePrice, ma30, name).encode('gbk')) writeLog( unicode( "[30up] code:{0}, yesterdayPrice: {1}, realTimePrice: {2}, ma30: {3}" ).format(code, yesterdayPrice, realTimePrice, ma30)) if (yesterdayPrice != 0 and realTimePrice != 0 and yesterdayPrice <= ma60 and realTimePrice >= ma60): # 击穿60日均线,并上涨 result.append( unicode("{0},{5},{1},{2},{3},{4}\n").format( code, '60up', yesterdayPrice, realTimePrice, ma60, name).encode('gbk')) writeLog( unicode( "[60up] code:{0}, yesterdayPrice: {1}, realTimePrice: {2}, ma60: {3}" ).format(code, yesterdayPrice, realTimePrice, ma60)) if (yesterdayPrice != 0 and realTimePrice != 0 and yesterdayPrice <= ma120 and realTimePrice >= ma120): # 击穿120日均线,并上涨 result.append( unicode("{0},{5},{1},{2},{3},{4}\n").format( code, '120up', yesterdayPrice, realTimePrice, ma120, name).encode('gbk')) writeLog( unicode( "[120up] code:{0}, yesterdayPrice: {1}, realTimePrice: {2}, ma120: {3}" ).format(code, yesterdayPrice, realTimePrice, ma120)) if (yesterdayPrice != 0 and realTimePrice != 0 and yesterdayPrice <= ma250 and realTimePrice >= ma250): # 击穿250日均线,并上涨 result.append( unicode("{0},{5},{1},{2},{3},{4}\n").format( code, '250up', yesterdayPrice, realTimePrice, ma250, name).encode('gbk')) writeLog( unicode( "[250up] code:{0}, yesterdayPrice: {1}, realTimePrice: {2}, ma250: {3}" ).format(code, yesterdayPrice, realTimePrice, ma250)) if (yesterdayPrice != 0 and realTimePrice != 0 and yesterdayPrice >= ma5 and realTimePrice <= ma5): # 击穿5日均线,并下跌 result.append( unicode("{0},{5},{1},{2},{3},{4}\n").format( code, '5down', yesterdayPrice, realTimePrice, ma5, name).encode('gbk')) writeLog( unicode( "[5down] code:{0}, yesterdayPrice: {1}, realTimePrice: {2}, ma5: {3}" ).format(code, yesterdayPrice, realTimePrice, ma5)) if (yesterdayPrice != 0 and realTimePrice != 0 and yesterdayPrice >= ma10 and realTimePrice <= ma10): # 击穿10日均线,并下跌 result.append( unicode("{0},{5},{1},{2},{3},{4}\n").format( code, '10down', yesterdayPrice, realTimePrice, ma10, name).encode('gbk')) writeLog( unicode( "[10down] code:{0}, yesterdayPrice: {1}, realTimePrice: {2}, ma10: {3}" ).format(code, yesterdayPrice, realTimePrice, ma10)) if (yesterdayPrice != 0 and realTimePrice != 0 and yesterdayPrice >= ma30 and realTimePrice <= ma30): # 击穿30日均线,并下跌 result.append( unicode("{0},{5},{1},{2},{3},{4}\n").format( code, '30down', yesterdayPrice, realTimePrice, ma30, name).encode('gbk')) writeLog( unicode( "[30down] code:{0}, yesterdayPrice: {1}, realTimePrice: {2}, ma30: {3}" ).format(code, yesterdayPrice, realTimePrice, ma30)) if (yesterdayPrice != 0 and realTimePrice != 0 and yesterdayPrice >= ma60 and realTimePrice <= ma60): # 击穿60日均线,并下跌 result.append( unicode("{0},{5},{1},{2},{3},{4}\n").format( code, '60down', yesterdayPrice, realTimePrice, ma60, name).encode('gbk')) writeLog( unicode( "[60down] code:{0}, yesterdayPrice: {1}, realTimePrice: {2}, ma60: {3}" ).format(code, yesterdayPrice, realTimePrice, ma60)) if (yesterdayPrice != 0 and realTimePrice != 0 and yesterdayPrice >= ma120 and realTimePrice <= ma120): # 击穿120日均线,并下跌 result.append( unicode("{0},{5},{1},{2},{3},{4}\n").format( code, '120down', yesterdayPrice, realTimePrice, ma120, name).encode('gbk')) writeLog( unicode( "[120down] code:{0}, yesterdayPrice: {1}, realTimePrice: {2}, ma120: {3}" ).format(code, yesterdayPrice, realTimePrice, ma120)) if (yesterdayPrice != 0 and realTimePrice != 0 and yesterdayPrice >= ma250 and realTimePrice <= ma250): # 击穿250日均线,并下跌 result.append( unicode("{0},{5},{1},{2},{3},{4}\n").format( code, '250down', yesterdayPrice, realTimePrice, ma250, name).encode('gbk')) writeLog( unicode( "[250down] code:{0}, yesterdayPrice: {1}, realTimePrice: {2}, ma250: {3}" ).format(code, yesterdayPrice, realTimePrice, ma250)) i = i + 1 except Exception, e: writeErrorLog( unicode("checkAvgLineFailed, code:{0}, i:{1}, e:{2}").format( code, i, str(e))) i = i + 1 time.sleep(0.5)
def updateForecastResult(date): writeLog(unicode("beginUpdateForecastResult, date:{0}").format(date)) selectSql = unicode( "select f.*,s.changePercent from s_stock_forecast as f INNER JOIN s_stock as s ON (s.code=f.code and s.date=f.date) where f.date='{0}'" ).format(date) data = select(selectSql) weekday = datetime.today().weekday() diff = 1 if weekday >= 1 and weekday <= 4 else ( 3 if weekday == 0 else weekday - 3) lastDay = (datetime.now() - timedelta(days=diff)).strftime('%Y-%m-%d') indexType = [ '', '', 'MACD', 'DMI', 'DMA', 'EXPMA', 'EMV', 'TRIX', 'WVAD', 'VR', 'CR', 'AR', 'PSY', 'KDJ', 'RSI', 'MTM', 'WR', 'CCI', 'OBV', '', '', '', '', 'BGB' ] upIndexType = [ 'BGB_DIFF4', 'TrendMax', 'EnergyMax', 'OBOSMax', 'TrendEnergyShow', 'TrendOBOSShow', 'EnergyOBOSShow', 'TrendEnergyOBOSShow', 'TEOBOS_BGBShow', 'TE_BGBShow', 'EOBOS_BGBShow', 'TOBOS_BGBShow', 'AllBulls', 'AllBulls_DIFF4' ] forecastCountField = '' forecastCountValue = '' dictCount = {} for row in data: dictIndex = {} upDictIndex = {} changePercent = row[len(row) - 1] for i in range(0, 24): if (indexType[i] == ''): continue if (row[i] == 0): if (changePercent > 0): # 预测上涨,实际上涨 dictIndex[indexType[i]] = 1 elif (changePercent < 0): # 预测上涨,实际下跌 dictIndex[indexType[i]] = 2 else: # 预测上涨,实际持平 dictIndex[indexType[i]] = 3 elif (row[i] == 1): if (changePercent > 0): # 预测下跌,实际上涨 dictIndex[indexType[i]] = 4 elif (changePercent < 0): # 预测下跌,实际下跌 dictIndex[indexType[i]] = 5 else: # 预测下跌,实际持平 dictIndex[indexType[i]] = 6 for i in range(24, len(row) - 1): if (row[i] == 0): j = i - 24 if (changePercent > 0): # 预测上涨,实际上涨 upDictIndex[upIndexType[j]] = 1 elif (changePercent < 0): # 预测上涨,实际下跌 upDictIndex[upIndexType[j]] = 2 else: # 预测上涨,实际持平 upDictIndex[upIndexType[j]] = 3 forecastResultField = '' forecastResultValue = '' stockForecastCountField = '' stockForecastCountValue = '' lastDayStockForecastCountData = select( unicode( "select * from s_stock_forecast_count where code='{0}' and date='{1}'" ).format(row[0], lastDay)) i = 1 for index in indexType: if (index == ''): continue forecastResultField = forecastResultField + index + ',' forecastResultValue = forecastResultValue + str( dictIndex[index] if dictIndex.has_key(index) else -1) + ',' stockForecastCountField = "{0}{1}_up_right,{1}_up_total,{1}_down_right,{1}_down_total,".format( stockForecastCountField, index) if len(lastDayStockForecastCountData) > 0: up_right = lastDayStockForecastCountData[0][ 3 + (i - 1) * 4 + 1] + (1 if dictIndex.has_key(index) and dictIndex.get(index) == 1 else 0) up_total = lastDayStockForecastCountData[0][ 3 + (i - 1) * 4 + 2] + (1 if dictIndex.has_key(index) and dictIndex.get(index) <= 3 else 0) down_right = lastDayStockForecastCountData[0][ 3 + (i - 1) * 4 + 3] + (1 if dictIndex.has_key(index) and dictIndex.get(index) == 5 else 0) down_total = lastDayStockForecastCountData[0][ 3 + (i - 1) * 4 + 4] + (1 if dictIndex.has_key(index) and dictIndex.get(index) > 3 else 0) stockForecastCountValue = "{0}{1},{2},{3},{4},".format( stockForecastCountValue, up_right, up_total, down_right, down_total) else: up_right = (1 if dictIndex.has_key(index) and dictIndex.get(index) == 1 else 0) up_total = (1 if dictIndex.has_key(index) and dictIndex.get(index) <= 3 else 0) down_right = (1 if dictIndex.has_key(index) and dictIndex.get(index) == 5 else 0) down_total = (1 if dictIndex.has_key(index) and dictIndex.get(index) > 3 else 0) stockForecastCountValue = "{0}{1},{2},{3},{4},".format( stockForecastCountValue, up_right, up_total, down_right, down_total) forecastCount_up_right = (1 if dictIndex.has_key(index) and dictIndex.get(index) == 1 else 0) forecastCount_up_total = (1 if dictIndex.has_key(index) and dictIndex.get(index) <= 3 else 0) forecastCount_down_right = (1 if dictIndex.has_key(index) and dictIndex.get(index) == 5 else 0) forecastCount_down_total = (1 if dictIndex.has_key(index) and dictIndex.get(index) > 3 else 0) if (dictCount.has_key(index)): dictCount[index].up_right = dictCount[ index].up_right + forecastCount_up_right dictCount[index].up_total = dictCount[ index].up_total + forecastCount_up_total dictCount[index].down_right = dictCount[ index].down_right + forecastCount_down_right dictCount[index].down_total = dictCount[ index].down_total + forecastCount_down_total else: dictCount[index] = IndexResult(forecastCount_up_right, forecastCount_up_total, forecastCount_down_right, forecastCount_down_total) i = i + 1 j = 1 for index in upIndexType: if (index == ''): continue forecastResultField = forecastResultField + index + ',' forecastResultValue = forecastResultValue + str( upDictIndex[index] if upDictIndex.has_key(index) else -1) + ',' stockForecastCountField = "{0}{1}_up_right,{1}_up_total,".format( stockForecastCountField, index) if len(lastDayStockForecastCountData) > 0: up_right = lastDayStockForecastCountData[0][ 75 + (j - 1) * 2 + 1] + (1 if upDictIndex.has_key(index) and upDictIndex.get(index) == 1 else 0) up_total = lastDayStockForecastCountData[0][ 75 + (j - 1) * 2 + 2] + (1 if upDictIndex.has_key(index) else 0) stockForecastCountValue = "{0}{1},{2},".format( stockForecastCountValue, up_right, up_total) else: up_right = (1 if upDictIndex.has_key(index) and upDictIndex.get(index) == 1 else 0) up_total = (1 if upDictIndex.has_key(index) else 0) stockForecastCountValue = "{0}{1},{2},".format( stockForecastCountValue, up_right, up_total) forecastCount_up_right = (1 if upDictIndex.has_key(index) and upDictIndex.get(index) == 1 else 0) forecastCount_up_total = (1 if upDictIndex.has_key(index) else 0) if (dictCount.has_key(index)): dictCount[index].up_right = dictCount[ index].up_right + forecastCount_up_right dictCount[index].up_total = dictCount[ index].up_total + forecastCount_up_total else: dictCount[index] = IndexResult(forecastCount_up_right, forecastCount_up_total, 0, 0) j = j + 1 forecastResultSql = unicode( "insert into s_stock_forecast_result(code,date,timestamp,{0}) values('{1}','{2}',{3},{4})" ).format(forecastResultField[:-1], row[0], row[1], row[22], forecastResultValue[:-1]) stockForecastCountSql = unicode( "insert into s_stock_forecast_count(code,date,timestamp,updateTS,{0}) values('{1}','{2}',{3},{4},{5})" ).format(stockForecastCountField[:-1], row[0], row[1], row[22], int(time.time()), stockForecastCountValue[:-1]) execute(forecastResultSql) execute(stockForecastCountSql) lastDayForecastCountData = select( unicode("select * from s_forecast_count where date='{0}'").format( lastDay)) i = 1 for index in indexType: if (index == ''): continue forecastCountField = "{0}{1}_up_right,{1}_up_total,{1}_down_right,{1}_down_total,".format( forecastCountField, index) if len(lastDayForecastCountData) > 0: forecastCount_up_right = lastDayForecastCountData[0][ 2 + (i - 1) * 4 + 1] + (dictCount.get(index).up_right if dictCount.has_key(index) else 0) forecastCount_up_total = lastDayForecastCountData[0][ 2 + (i - 1) * 4 + 2] + (dictCount.get(index).up_total if dictCount.has_key(index) else 0) forecastCount_down_right = lastDayForecastCountData[0][ 2 + (i - 1) * 4 + 3] + (dictCount.get(index).down_right if dictCount.has_key(index) else 0) forecastCount_down_total = lastDayForecastCountData[0][ 2 + (i - 1) * 4 + 4] + (dictCount.get(index).down_total if dictCount.has_key(index) else 0) forecastCountValue = "{0}{1},{2},{3},{4},".format( forecastCountValue, forecastCount_up_right, forecastCount_up_total, forecastCount_down_right, forecastCount_down_total) else: forecastCount_up_right = (dictCount.get(index).up_right if dictCount.has_key(index) else 0) forecastCount_up_total = (dictCount.get(index).up_total if dictCount.has_key(index) else 0) forecastCount_down_right = (dictCount.get(index).down_right if dictCount.has_key(index) else 0) forecastCount_down_total = (dictCount.get(index).down_total if dictCount.has_key(index) else 0) forecastCountValue = "{0}{1},{2},{3},{4},".format( forecastCountValue, forecastCount_up_right, forecastCount_up_total, forecastCount_down_right, forecastCount_down_total) i = i + 1 j = 1 for index in upIndexType: if (index == ''): continue forecastCountField = "{0}{1}_up_right,{1}_up_total,".format( forecastCountField, index) if len(lastDayForecastCountData) > 0: forecastCount_up_right = lastDayForecastCountData[0][ 74 + (j - 1) * 2 + 1] + (dictCount.get(index).up_right if dictCount.has_key(index) else 0) forecastCount_up_total = lastDayForecastCountData[0][ 74 + (j - 1) * 2 + 2] + (dictCount.get(index).up_total if dictCount.has_key(index) else 0) forecastCountValue = "{0}{1},{2},".format(forecastCountValue, forecastCount_up_right, forecastCount_up_total) else: forecastCount_up_right = (dictCount.get(index).up_right if dictCount.has_key(index) else 0) forecastCount_up_total = (dictCount.get(index).up_total if dictCount.has_key(index) else 0) forecastCountValue = "{0}{1},{2},".format(forecastCountValue, forecastCount_up_right, forecastCount_up_total) j = j + 1 forecastCountSql = unicode( "insert into s_forecast_count(date,timestamp,updateTs,{0}) values('{1}',{2},{3},{4})" ).format(forecastCountField[:-1], date, int(time.mktime(time.strptime(date, '%Y-%m-%d'))), int(time.time()), forecastCountValue[:-1]) execute(forecastCountSql) writeLog(unicode("endUpdateForecastResult, date:{0}").format(date))
def checkAvgline(stockList): date = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d') dictLastRemindPrice = {} while 1 == 1: if datetime.now().hour >= 16: # 今日提醒程序结束 return for stock in stockList: code = stock[0] name = stock[1] try: sql = unicode( "SELECT code,date,MA5,MA10,MA20,MA30,MA60,MA120,MA250 from s_stock where code='{0}' and date='{1}'" ).format(code, date) data = select(sql) if (len(data) <= 0): writeLog( unicode("没有获取到均值数据, code: {0}, date: {1}").format( code, date)) continue ma5 = data[0][2] ma10 = data[0][3] ma30 = data[0][5] ma60 = data[0][6] ma120 = data[0][7] ma250 = data[0][8] lastPrice = getNPrice( code, 1, 'high') if not dictLastRemindPrice.has_key( code) else dictLastRemindPrice.get(code) realTimePrice = float(getRealTimeData(code)) print name, lastPrice, realTimePrice if (lastPrice != 0 and realTimePrice != 0 and lastPrice <= ma5 and realTimePrice >= ma5): # 击穿5日均线,并上涨 sendMessageToMySelf( unicode("{0},{5},{1},{2},{3},{4}\n").format( code, '5up', lastPrice, realTimePrice, ma5, name)) writeLog( unicode( "[remind_5up] code:{0}, yesterdayPrice: {1}, realTimePrice: {2}, ma5: {3}" ).format(code, lastPrice, realTimePrice, ma5)) if (lastPrice != 0 and realTimePrice != 0 and lastPrice <= ma10 and lastPrice >= ma10): # 击穿10日均线,并上涨 sendMessageToMySelf( unicode("{0},{5},{1},{2},{3},{4}\n").format( code, '10up', lastPrice, realTimePrice, ma10, name)) writeLog( unicode( "[remind_10up] code:{0}, yesterdayPrice: {1}, realTimePrice: {2}, ma10: {3}" ).format(code, lastPrice, realTimePrice, ma10)) if (lastPrice != 0 and realTimePrice != 0 and lastPrice <= ma30 and realTimePrice >= ma30): # 击穿30日均线,并上涨 sendMessageToMySelf( unicode("{0},{5},{1},{2},{3},{4}\n").format( code, '30up', lastPrice, realTimePrice, ma30, name)) writeLog( unicode( "[remind_30up] code:{0}, yesterdayPrice: {1}, realTimePrice: {2}, ma30: {3}" ).format(code, lastPrice, realTimePrice, ma30)) if (lastPrice != 0 and realTimePrice != 0 and lastPrice <= ma60 and realTimePrice >= ma60): # 击穿60日均线,并上涨 sendMessageToMySelf( unicode("{0},{5},{1},{2},{3},{4}\n").format( code, '60up', lastPrice, realTimePrice, ma60, name)) writeLog( unicode( "[remind_60up] code:{0}, yesterdayPrice: {1}, realTimePrice: {2}, ma60: {3}" ).format(code, lastPrice, realTimePrice, ma60)) if (lastPrice != 0 and realTimePrice != 0 and lastPrice <= ma120 and realTimePrice >= ma120): # 击穿120日均线,并上涨 sendMessageToMySelf( unicode("{0},{5},{1},{2},{3},{4}\n").format( code, '120up', lastPrice, realTimePrice, ma120, name)) writeLog( unicode( "[remind_120up] code:{0}, yesterdayPrice: {1}, realTimePrice: {2}, ma120: {3}" ).format(code, lastPrice, realTimePrice, ma120)) if (lastPrice != 0 and realTimePrice != 0 and lastPrice <= ma250 and realTimePrice >= ma250): # 击穿250日均线,并上涨 sendMessageToMySelf( unicode("{0},{5},{1},{2},{3},{4}\n").format( code, '250up', lastPrice, realTimePrice, ma250, name)) writeLog( unicode( "[remind_250up] code:{0}, yesterdayPrice: {1}, realTimePrice: {2}, ma250: {3}" ).format(code, lastPrice, realTimePrice, ma250)) if (lastPrice != 0 and realTimePrice != 0 and lastPrice >= ma5 and realTimePrice <= ma5): # 击穿5日均线,并下跌 sendMessageToMySelf( unicode("{0},{5},{1},{2},{3},{4}\n").format( code, '5down', lastPrice, realTimePrice, ma5, name)) writeLog( unicode( "[remind_5down] code:{0}, yesterdayPrice: {1}, realTimePrice: {2}, ma5: {3}" ).format(code, lastPrice, realTimePrice, ma5)) if (lastPrice != 0 and realTimePrice != 0 and lastPrice >= ma10 and realTimePrice <= ma10): # 击穿10日均线,并下跌 sendMessageToMySelf( unicode("{0},{5},{1},{2},{3},{4}\n").format( code, '10down', lastPrice, realTimePrice, ma10, name)) writeLog( unicode( "[remind_10down] code:{0}, yesterdayPrice: {1}, realTimePrice: {2}, ma10: {3}" ).format(code, lastPrice, realTimePrice, ma10)) if (lastPrice != 0 and realTimePrice != 0 and lastPrice >= ma30 and realTimePrice <= ma30): # 击穿30日均线,并下跌 sendMessageToMySelf( unicode("{0},{5},{1},{2},{3},{4}\n").format( code, '30down', lastPrice, realTimePrice, ma30, name)) writeLog( unicode( "[remind_30down] code:{0}, yesterdayPrice: {1}, realTimePrice: {2}, ma30: {3}" ).format(code, lastPrice, realTimePrice, ma30)) if (lastPrice != 0 and realTimePrice != 0 and lastPrice >= ma60 and realTimePrice <= ma60): # 击穿60日均线,并下跌 sendMessageToMySelf( unicode("{0},{5},{1},{2},{3},{4}\n").format( code, '60down', lastPrice, realTimePrice, ma60, name)) writeLog( unicode( "[remind_60down] code:{0}, yesterdayPrice: {1}, realTimePrice: {2}, ma60: {3}" ).format(code, lastPrice, realTimePrice, ma60)) if (lastPrice != 0 and realTimePrice != 0 and lastPrice >= ma120 and realTimePrice <= ma120): # 击穿120日均线,并下跌 sendMessageToMySelf( unicode("{0},{5},{1},{2},{3},{4}\n").format( code, '120down', lastPrice, realTimePrice, ma120, name)) writeLog( unicode( "[remind_120down] code:{0}, yesterdayPrice: {1}, realTimePrice: {2}, ma120: {3}" ).format(code, lastPrice, realTimePrice, ma120)) if (lastPrice != 0 and realTimePrice != 0 and lastPrice >= ma250 and realTimePrice <= ma250): # 击穿250日均线,并下跌 sendMessageToMySelf( unicode("{0},{5},{1},{2},{3},{4}\n").format( code, '250down', lastPrice, realTimePrice, ma250, name)) writeLog( unicode( "[remind_250down] code:{0}, yesterdayPrice: {1}, realTimePrice: {2}, ma250: {3}" ).format(code, lastPrice, realTimePrice, ma250)) dictLastRemindPrice[code] = realTimePrice except Exception, e: writeErrorLog( unicode( "remind_checkAvgLineFailed, code:{0}, e:{1}").format( code, str(e))) time.sleep(1)