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 updateNewGoodList(): weekday = datetime.now().weekday() lastSaturday = (datetime.now() + timedelta(days=(-2 - weekday))).strftime('%Y-%m-%d') saturday = (datetime.now() + timedelta(days=(5 - weekday))).strftime('%Y-%m-%d') for i in range(1, 9): lastWeekSql = unicode( "select code from b_peg where dataType={0} and date='{1}'").format( i, lastSaturday) oldData = select(lastWeekSql) dic = {} for item in oldData: dic[item[0]] = 1 newList = select( unicode( "select code,name,pe,peg from b_peg where dataType={0} and date='{1}'" ).format(i, saturday)) result = [] result.append( unicode("{0},{1},{2},{3}\n").format("代码", "名称", "PE", "PEG").encode('gbk')) for item in newList: if item[0] not in dic: result.append( unicode("{0},{1},{2},{3}\n").format( item[0], item[1], item[2], item[3]).encode('gbk')) saveFile("newGoodList_{0}.csv".format(i), result)
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 saveStockTech(): date = datetime.now().strftime('%Y-%m-%d') weekday = datetime.today().weekday() if weekday == 5 or weekday == 6: return tomorrow = ( datetime.now() + timedelta(days=(3 if weekday == 4 else 1))).strftime('%Y-%m-%d') stockList = select( unicode("SELECT code,name from s_stock_info") ) # loadJsonConfig(os.path.abspath(os.path.join(os.getcwd(), "../config/goodStockList.json"))) i = 0 while i < len(stockList): code = stockList[i][0] checkExistSql = unicode( "select count(*) from s_stock_tech where code='{0}' and date='{1}'" ).format(code, date) count = select(checkExistSql, False)[0] if count > 0: i = i + 1 continue try: info = getTechParamter(code) saveStockTechToDb(info[0], date, count > 0) saveStockTechForecastToDb(info[1], info[2], tomorrow) i = i + 1 except Exception, e: writeErrorLog( unicode("getTechFailed, code: {0}, e: {1}").format(code, e)) time.sleep(1)
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 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 updateAllMACD(): sql = unicode("select code from s_stock_info order by code asc") stockList = select(sql) if stockList is None: return for stock in stockList: sql = unicode( "select code,date,macd,dif,dea from s_stock_tech where code='{0}' ORDER by code,date asc limit 1,60000").format( stock[0]) data = select(sql) if len(data) <= 0: # writeLog(unicode("没有获取到无效MACD指标数据,code:{0}").format(stock[0])) continue 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 saveStockIndexToDb(stockIndexInfo, date): checkExistSql = unicode( "select count(*) from s_index where code='{0}' and date='{1}'").format( stockIndexInfo.code, date) count = select(checkExistSql, False)[0] if count > 0: updateSql = unicode( "update s_index set name='{0}',`index`={1},upNumber={2},downNumber={3},equalNumber={4},highIndex={7},lowIndex={8},openIndex={9},changePercent={10},changeAmount={11},volume={12},amount='{13}',turnOverRatio={14},internalPan={15},externalPan={16},upDownPercent={17},avgPE={18} where code='{5}' and date='{6}'" ).format(stockIndexInfo.name, stockIndexInfo.index, stockIndexInfo.upNumber, stockIndexInfo.downNumber, stockIndexInfo.equalNumber, stockIndexInfo.code, date, stockIndexInfo.high, stockIndexInfo.low, stockIndexInfo.open, stockIndexInfo.changePercent, stockIndexInfo.changeAmount, stockIndexInfo.volume, stockIndexInfo.amount, stockIndexInfo.turnOverRatio, stockIndexInfo.internalPan, stockIndexInfo.externalPan, stockIndexInfo.upDownPercent, stockIndexInfo.avgPE) execute(updateSql) else: insertSql = unicode( "insert into s_index(code,date,name,`index`,upNumber,downNumber,equalNumber,highIndex,lowIndex,openIndex,changePercent,changeAmount,volume,amount,turnOverRatio,internalPan,externalPan,upDownPercent,avgPE,timestamp) VALUES (\'{0}\',\'{1}\',\'{2}\',{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},\'{13}\',{14},{15},{16},{17},{18},{19})" ).format(stockIndexInfo.code, date, stockIndexInfo.name, stockIndexInfo.index, stockIndexInfo.upNumber, stockIndexInfo.downNumber, stockIndexInfo.equalNumber, stockIndexInfo.high, stockIndexInfo.low, stockIndexInfo.open, stockIndexInfo.changePercent, stockIndexInfo.changeAmount, stockIndexInfo.volume, stockIndexInfo.amount, stockIndexInfo.turnOverRatio, stockIndexInfo.internalPan, stockIndexInfo.externalPan, stockIndexInfo.upDownPercent, stockIndexInfo.avgPE, int(time.mktime(time.strptime(date, '%Y-%m-%d')))) execute(insertSql)
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 checkHighChangePercentStockForcase(): date = datetime.now().strftime('%Y-%m-%d') timestamp = int(time.mktime(time.strptime(date, '%Y-%m-%d'))) stockList = select( unicode( "SELECT s.changePercent,f.* FROM s_stock_forecast as f INNER JOIN (SELECT * FROM s_stock where timestamp={0} and changePercent>=5) as s on (f.code=s.code and f.date=s.date)").format( timestamp)) # 指标列表 indexList = ['', '', '', 'MACD', 'DMI', 'DMA', 'EXPMA', 'EMV', 'TRIX', 'WVAD', 'VR', 'CR', 'AR', 'PSY', 'KDJ', 'RSI', 'MTM', 'WR', 'CCI', 'OBV', '', '', '', '', 'BGB', 'BGB_DIFF4', 'TrendMax', 'EnergyMax', 'OBOSMax', 'TrendEnergyShow', 'TrendOBOSShow', 'EnergyOBOSShow', 'TrendEnergyOBOSShow', 'TEOBOS_BGBShow', 'TE_BGBShow', 'EOBOS_BGBShow', 'TOBOS_BGBShow', 'AllBulls', 'AllBulls_DIFF4'] insertSql = unicode("INSERT INTO s_high_result VALUES(%s,%s,%s,%s)") parameters = [] for row in stockList: changePercent = row[0] code = row[1] date = row[2] list = [] for i in range(3, len(row)): indexName = indexList[i] # 指标名称 if (indexName == ''): # 过滤掉不是指标的列 continue if (row[i] == 0): list.append(indexName) parameters.append([code, date, changePercent, json.dumps(list)]) batchInsert(insertSql, parameters)
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 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 saveStockInfoToDb(info, date): checkExistSql = unicode( "select count(*) from s_stock where code='{0}' and date='{1}'").format( info['code'], date) count = select(checkExistSql, False)[0] if count > 0: updateSql = unicode( "update s_stock set limitUp={2},limitDown={3},avgPrice={4},volume={5},amount='{6}',highPrice={7},lowPrice={8},openPrice={9},closePrice={10},changePercent={11},changeAmount={12},turnOverRatio={13},QRR={14}, totalValue={15},circulatedValue={16},PE={17},PTB={18},internalPan={19},externalPan={20} where code='{0}' and date='{1}'" ).format(info['code'], date, info['limitUp'], info['limitDown'], info['avgPrice'], info['volume'], info['amount'], info['highPrice'], info['lowPrice'], info['openPrice'], info['closePrice'], info['changePercent'], info['changeAmount'], info['turnOverRatio'], info['QRR'], info['totalValue'], info['circulatedValue'], info['PE'], info['PTB'], info['internalPan'], info['externalPan']) execute(updateSql) else: insertSql = unicode( "insert into s_stock(code,date,timestamp,limitUp,limitDown,avgPrice,volume,amount,highPrice,lowPrice,openPrice,closePrice,changePercent,changeAmount,turnOverRatio,QRR,totalValue,circulatedValue,PE,PTB,internalPan,externalPan) VALUES ('{0}','{1}',{2},{3},{4},{5},{6},'{7}',{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21})" ).format(info['code'], date, int(time.mktime(time.strptime(date, '%Y-%m-%d'))), info['limitUp'], info['limitDown'], info['avgPrice'], info['volume'], info['amount'], info['highPrice'], info['lowPrice'], info['openPrice'], info['closePrice'], info['changePercent'], info['changeAmount'], info['turnOverRatio'], info['QRR'], info['totalValue'], info['circulatedValue'], info['PE'], info['PTB'], info['internalPan'], info['externalPan']) execute(insertSql)
def saveStockInfo(): date = datetime.now() weekday = datetime.today().weekday() diff = 0 if weekday < 5 else weekday - 4 date = (date - timedelta(days=diff)).strftime('%Y-%m-%d') stockList = select( unicode("SELECT code,name from s_stock_info") ) # loadJsonConfig(os.path.abspath(os.path.join(os.getcwd(), "../config/goodStockList.json"))) i = 0 while i < len(stockList): code = stockList[i][0] try: info = getStockInfo(code) if info is None: i = i + 1 continue saveStockInfoToDb(info, date) i = i + 1 except Exception, e: writeErrorLog( unicode("getStockInfoFailed, code:{0}, e:{1}").format( code, str(e))) time.sleep(0.2)
def updateForecast(): forecastData = select(unicode("select * from s_stock_forecast")) for item in forecastData: dictStatus = {} code = item[0] date = item[1] dictStatus['MACD'] = toString(item[2]) dictStatus['ADX'] = toString(item[3]) dictStatus['DMA'] = toString(item[4]) dictStatus['EXPMA1'] = toString(item[5]) dictStatus['EMV'] = toString(item[6]) dictStatus['TRIX'] = toString(item[7]) dictStatus['WVAD'] = toString(item[8]) dictStatus['VR'] = toString(item[9]) dictStatus['CR'] = toString(item[10]) dictStatus['AR'] = toString(item[11]) dictStatus['PSY'] = toString(item[12]) dictStatus['K'] = toString(item[13]) dictStatus['RSI1'] = toString(item[14]) dictStatus['MTM'] = toString(item[15]) dictStatus['W&R'] = toString(item[16]) dictStatus['CCI'] = toString(item[17]) dictStatus['OBV'] = toString(item[18]) bulls = item[19] bears = item[20] notsure = item[21] stockTechStatus = StockTechStatus(code, dictStatus, bulls, bears, notsure) forecastInfo = getGainForecast(stockTechStatus) saveStockTechForecastToDb(stockTechStatus, forecastInfo, date)
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 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 getTodayClosePrice(code, date): sql = unicode("SELECT closePrice from s_stock where code='{0}' and date='{1}'").format(code, date) data = select(sql) if len(data) <= 0: return None return data[0][0]
def getMAData(dayCount, code, date): sql = unicode( "select if(count(*)<{0},0,sum(closePrice)/{0}) from ( select closePrice from s_stock where code='{1}' and date<='{2}' order by timestamp desc limit {0}) as t").format( dayCount, code, date) data = select(sql) if len(data) <= 0: return 0 else: return float(data[0][0])
def saveStockTechForecastToDb(stockTechStatus, forecastInfo, date): checkExistSql = unicode( "select count(*) from s_stock_forecast where code='{0}' and date='{1}'" ).format(stockTechStatus.code, date) count = select(checkExistSql, False)[0] if count > 0: updateSql = unicode( "update s_stock_forecast set MACD={2},DMI={3},DMA={4},EXPMA={5},EMV={6},TRIX={7},WVAD={8},VR={9},CR={10},AR={11},PSY={12},KDJ={13},RSI={14}, MTM={15},WR={16},CCI={17},OBV={18},bulls={19},bears={20},notsure={21},BGB={22},BGB_DIFF4={23},TrendMax={24},EnergyMax={25},OBOSMax={26},TrendEnergyShow={27},TrendOBOSShow={28},EnergyOBOSShow={29},TrendEnergyOBOSShow={30},TEOBOS_BGBShow={31},TE_BGBShow={32},EOBOS_BGBShow={33},TOBOS_BGBShow={34},AllBulls={35},AllBulls_DIFF4={36} where code='{0}' and date='{1}'" ).format( stockTechStatus.code, date, stockTechStatus.MACD, stockTechStatus.DMI, stockTechStatus.DMA, stockTechStatus.EXPMA, stockTechStatus.EMV, stockTechStatus.TRIX, stockTechStatus.WVAD, stockTechStatus.VR, stockTechStatus.CR, stockTechStatus.AR, stockTechStatus.PSY, stockTechStatus.KDJ, stockTechStatus.RSI, stockTechStatus.MTM, stockTechStatus.WR, stockTechStatus.CCI, stockTechStatus.OBV, stockTechStatus.bulls, stockTechStatus.bears, stockTechStatus.notsure, forecastInfo.BGB, forecastInfo.BGB_DIFF4, forecastInfo.TrendMax, forecastInfo.EnergyMax, forecastInfo.OBOSMax, forecastInfo.TrendEnergyShow, forecastInfo.TrendOBOSShow, forecastInfo.EnergyOBOSShow, forecastInfo.TrendEnergyOBOSShow, forecastInfo.TEOBOS_BGBShow, forecastInfo.TE_BGBShow, forecastInfo.EOBOS_BGBShow, forecastInfo.TOBOS_BGBShow, forecastInfo.AllBulls, forecastInfo.AllBulls_DIFF4) execute(updateSql) else: insertSql = unicode( "insert into s_stock_forecast(code,date,timestamp,MACD,DMI,DMA,EXPMA,EMV,TRIX,WVAD,VR,CR,AR,PSY,KDJ,RSI,MTM,WR,CCI,OBV,bulls,bears,notsure,BGB,BGB_DIFF4,TrendMax,EnergyMax,OBOSMax,TrendEnergyShow,TrendOBOSShow,EnergyOBOSShow,TrendEnergyOBOSShow,TEOBOS_BGBShow,TE_BGBShow,EOBOS_BGBShow,TOBOS_BGBShow,AllBulls,AllBulls_DIFF4) VALUES (\'{0}\',\'{1}\',{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21},{22},{23},{24},{25},{26},{27},{28},{29},{30},{31},{32},{33},{34},{35},{36},{37})" ).format( stockTechStatus.code, date, int(time.mktime(time.strptime(date, '%Y-%m-%d'))), stockTechStatus.MACD, stockTechStatus.DMI, stockTechStatus.DMA, stockTechStatus.EXPMA, stockTechStatus.EMV, stockTechStatus.TRIX, stockTechStatus.WVAD, stockTechStatus.VR, stockTechStatus.CR, stockTechStatus.AR, stockTechStatus.PSY, stockTechStatus.KDJ, stockTechStatus.RSI, stockTechStatus.MTM, stockTechStatus.WR, stockTechStatus.CCI, stockTechStatus.OBV, stockTechStatus.bulls, stockTechStatus.bears, stockTechStatus.notsure, forecastInfo.BGB, forecastInfo.BGB_DIFF4, forecastInfo.TrendMax, forecastInfo.EnergyMax, forecastInfo.OBOSMax, forecastInfo.TrendEnergyShow, forecastInfo.TrendOBOSShow, forecastInfo.EnergyOBOSShow, forecastInfo.TrendEnergyOBOSShow, forecastInfo.TEOBOS_BGBShow, forecastInfo.TE_BGBShow, forecastInfo.EOBOS_BGBShow, forecastInfo.TOBOS_BGBShow, forecastInfo.AllBulls, forecastInfo.AllBulls_DIFF4) execute(insertSql)
def main(argv): reload(sys) sys.setdefaultencoding('utf-8') initMysql() codeList = ['600758', '600393', '601318', '600282', '600029'] result = [] result.append( unicode("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13}\n").format("代码", "名称", "ma5", "ma10", "ma20", "ma30", "ma60", "ma120", "ma200", "ma240", "BIAS1(6日)", "BIAS2(12日)", "BIAS3(24日)", "10收盘价").encode( 'gbk')) date = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d') for code in codeList: sql = unicode( "SELECT code,date,MA5,MA10,MA20,MA30,MA60,MA120,MA250,closePrice from s_stock where code='{0}' and date='{1}'").format( code, date) data = select(sql) if (len(data) <= 0): (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] closePrice = float(data[0][9]) nvg6 = getMAData(6, code, date) nvg12 = getMAData(12, code, date) nvg24 = getMAData(24, code, date) bias1 = round((closePrice - nvg6) * 100 / nvg6, 2) bias2 = round((closePrice - nvg12) * 100 / nvg12, 2) bias3 = round((closePrice - nvg24) * 100 / nvg24, 2) peInfo = getPE(code)
def startForecast(): date = datetime.now().strftime('%Y-%m-%d') weekday = datetime.today().weekday() if weekday == 5 or weekday == 6: return tomorrow = ( datetime.now() + timedelta(days=(3 if weekday == 4 else 1))).strftime('%Y-%m-%d') stockList = select( unicode("SELECT code,name from s_stock_info") ) # loadJsonConfig(os.path.abspath(os.path.join(os.getcwd(), "../config/goodStockList.json"))) i = 0 while i < len(stockList): code = stockList[i][0] checkMACD(code, tomorrow) i = i + 1
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 getRSV(code, date): sql = unicode( "select min(lowPrice),max(highPrice) from (SELECT * from s_stock where code='{0}' and date<='{1}' ORDER by date desc limit 9) as t").format( code, date) data = select(sql) if len(data) <= 0: return None minLow = data[0][0] maxHigh = data[0][1] todayClosePrice = getTodayClosePrice(code, date) if todayClosePrice is None: return None if (maxHigh - minLow == 0): return None return round((todayClosePrice - minLow) * 100 / (maxHigh - minLow), 2)
def updateNewList(): oldList = loadJsonConfig( os.path.abspath( os.path.join( os.getcwd(), "../backup/goodStockList_" + datetime.now().strftime('%Y-%m-%d') + ".json"))) dic = {} for item in oldList: dic[item[0]] = 1 stockList = select( unicode("SELECT code,name from s_stock_info") ) # loadJsonConfig(os.path.abspath(os.path.join(os.getcwd(), "../config/goodStockList.json"))) newList = [] for item in stockList: if item[0] not in dic: newList.append([item[0], item[1]]) saveFileName = os.path.abspath( os.path.join(os.getcwd(), "../config/newStockList.json")) writeFile(saveFileName, json.dumps(newList))
def updateStockHistoryInfoByTHS(stockList): for stock in stockList: code = stock[0] i = 2010 thisYear = datetime.now().year while (i <= thisYear): # time.sleep(1) infos = getStockInfos(code, i) if infos is None: continue for date in infos: open = infos.get(date).get('open') close = infos.get(date).get('close') high = infos.get(date).get('high') low = infos.get(date).get('low') volume = infos.get(date).get('volume') amount = infos.get(date).get('amount') checkExistSql = unicode( "select count(*) from s_stock where code='{0}' and date='{1}'" ).format(code, date) count = select(checkExistSql, False)[0] if count > 0: updateSql = unicode( "update s_stock set volume={2},highPrice={3},lowPrice={4},openPrice={5},closePrice={6},amount='{7}' where code='{0}' and date='{1}'" ).format(code, date, volume, high, low, open, close, amount) execute(updateSql) print code, date, updateSql else: insertSql = unicode( "insert into s_stock(code,date,timestamp,volume,highPrice,lowPrice,openPrice,closePrice,amount) VALUES ('{0}','{1}',{2},{3},{4},{5},{6},{7},'{8}')" ).format(code, date, int(time.mktime(time.strptime(date, '%Y-%m-%d'))), volume, high, low, open, close, amount) execute(insertSql) print code, date, insertSql i = i + 1
def runTask(): if datetime.today().weekday() < 5 and datetime.now( ).hour >= 20 and datetime.now().hour < 21 and datetime.now().minute < 20: sendMessageToMySelf(unicode("开始获取AvgLine数据")) begin = datetime.now() initMysql() stockList = getCodeList() checkAvgLine("avgline.csv", stockList, False) stockList = select( unicode("SELECT code,name from s_stock_info") ) # loadJsonConfig(os.path.abspath(os.path.join(os.getcwd(), "../config/goodStockList.json"))) checkAvgLine("avgline_all.csv", stockList) disconnect() end = datetime.now() sendMessageToMySelf( unicode("今日获取AvgLine的任务执行完毕,当前时间:{0},执行用时:{1}").format( datetime.now(), end - begin)) t = Timer(900, runTask) t.start()
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 updateLatestGoodStockListToConfig(): selectSql = unicode( "SELECT DISTINCT code,name from b_peg where date=(SELECT max(date) FROM b_peg)" ) result = select(selectSql) dictData = {} data = [] for row in result: code = row[0].zfill(6) if code not in dictData: dictData[code] = 1 data.append([code, row[1]]) saveFileName = os.path.abspath( os.path.join(os.getcwd(), "../config/goodStockList.json")) backupFileName = os.path.abspath( os.path.join( os.getcwd(), "../backup/goodStockList_" + datetime.now().strftime('%Y-%m-%d') + ".json")) if os.path.exists(saveFileName): shutil.move(saveFileName, backupFileName) writeFile(saveFileName, json.dumps(data))
import os sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), ".."))) from db.MysqlUtil import select, initMysql, execute from stock.StockInfo import getPE '''os.system("python AvgLinePriceCheckTask.py &") # 获取每日均线数据,工作日20点以后获取 os.system("python StockIndexTask.py &") # 获取每日各个主要指数数据,工作日19点以后获取 os.system("python StockTechTask.py &") # 获取每日各个股票的技术指标数据,工作日22点以后获取 os.system("python StockInfoTask.py &") # 获取每日各个股票的行情数据,工作日19点以后获取 os.system("python UpdateMADataTask.py &") #更新今日均线数据,工作日21点以后获取 os.system("python UpdateBiasDataTask.py &") #更新今日bias数据,工作日21点以后获取 os.system("python RealTimeRemindTask.py &") #启动每日提醒任务,工作日9点以后启动 os.system("python DownPercentRemindTask.py &") #启动每日涨跌幅提醒任务,工作日9点以后启动 os.system("python StockChooseTask.py &") # 每周更新PEG数据 ''' # 更新股票名称 initMysql() sql = unicode("SELECT code from s_stock_tech GROUP by code order by code asc") data = select(sql) for item in data: code = item[0] name = getPE(code)[0] print code, name addSql = unicode( "insert into s_stock_info(code,name) values('{0}','{1}')").format( code, name) execute(addSql)