def writeRSIToDB(period, stockCode, stockName, rsi_df): dataList = [] for index, rsi in rsi_df.iterrows(): rsiDate = rsi['date'] if period == "day": rsiObj = DayRSI(stockCode, stockName) elif period == "week": rsiObj = WeekRSI(stockCode, stockName) elif period == "month": rsiObj = MonthRSI(stockCode, stockName) elif period == "5m": rsiObj = FiveMinRSI(stockCode, stockName) elif period == "15m": rsiObj = FiftyMinRSI(stockCode, stockName) elif period == "30m": rsiObj = ThirtyMinRSI(stockCode, stockName) elif period == "60m": rsiObj = SixtyMinRSI(stockCode, stockName) rsiObj.date = rsiDate rsiObj.rsi_6 = rsi['rsi_6'] rsiObj.rsi_12 = rsi['rsi_12'] rsiObj.rsi_24 = rsi['rsi_24'] rsiObj.overBuy = rsi['overBuyFlag'] rsiObj.overSell = rsi['overSellFlag'] dataList.append(rsiObj.__dict__) mydb = dbutil.connectDB() collection = mydb[chooseRSICollection(period)] if len(dataList) > 0: collection.insert_many(dataList) else: raise RuntimeError("RSI数据为空")
def clearRSI(period): mydb = dbutil.connectDB() collection = mydb[chooseRSICollection(period)] collection.delete_many({}) indexes = collection.index_information() if "code_1_date_1" in indexes.keys(): collection.drop_index("code_1_date_1")
def findLatestRSIDate(period): mydb = dbutil.connectDB() collection = mydb[chooseRSICollection(period)] cursor = collection.find().sort("date", -1).limit(1) df = pd.DataFrame(list(cursor)) if df.empty: return "1970-01-01" return df["date"][0]
def clearKlineData(period, startDate): mydb = dbutil.connectDB() collection = mydb[chooseKlineCollection(period)] startDate = datetime.strptime(startDate + "T00:00:00.000Z", "%Y-%m-%dT%H:%M:%S.000Z") collection.delete_many({"date":{"$gte":startDate}}) indexes = collection.index_information() if "code_1_date_1" in indexes.keys(): collection.drop_index( "code_1_date_1" )
def allStocks(): global stocks if stocks != None: return stocks mydb = dbutil.connectDB() cursor = mydb["Stock"].find({}) df = pd.DataFrame(list(cursor)) df = df.set_index("code") # set_trace() stocks = df.to_dict('index') return stocks
def readStockKline(code, period, startDate, endDate): mydb = dbutil.connectDB() cursor = None periodCollection = chooseKlineCollection(period) startDate = datetime.strptime(startDate + "T00:00:00.000Z", "%Y-%m-%dT%H:%M:%S.000Z") endDate = datetime.strptime(endDate + "T23:59:59.000Z", "%Y-%m-%dT%H:%M:%S.000Z") query = {"date":{"$gte":startDate, "$lte":endDate}} if code != None and len(code) > 0: query["code"] = code cursor = mydb[chooseKlineCollection(period)].find(query) df = pd.DataFrame(list(cursor)) return df
def initAccount(acctCount, equity): if acctCount <= 0: raise RuntimeError("初始化账户数得大于0") dateStr = datetime.datetime.strftime(datetime.datetime.now(), "%m%d") mydb = dbutil.connectDB() collection = mydb["Account"] dataList = [] for i in range(0, acctCount): newAcct = Account( str(uuid.uuid1()).replace("-", ""), dateStr + "account" + str(i + 1)) newAcct.initiatedEquity = equity newAcct.equity = equity dataList.append(newAcct.__dict__) collection.insert_many(dataList) return True
def readRSI(period, stockCode, startDate, endDate): mydb = dbutil.connectDB() collection = mydb[chooseRSICollection(period)] if type(startDate) == str: startDate = datetime.datetime.strptime(startDate + "T00:00:00.000Z", "%Y-%m-%dT%H:%M:%S.000Z") endDate = datetime.datetime.strptime(endDate + "T23:59:59.000Z", "%Y-%m-%dT%H:%M:%S.000Z") cursor = collection.find({ "code": stockCode, "date": { "$gte": startDate, "$lte": endDate } }) df = pd.DataFrame(list(cursor)) return df
def downloadAllStocks(tradeDate): customLogin() # set_trace() # stock_rs = bs.query_all_stock(tradeDate) stock_rs = bs.query_stock_basic() stock_df = stock_rs.get_data() dataList = [] for index,stock in stock_df.iterrows(): stockObj = Stock(stock["code"], stock["code_name"]) stockObj.stockType = stock["type"] dataList.append(stockObj.__dict__) mydb = dbutil.connectDB() mydb["Stock"].delete_many({}) mydb["Stock"].insert_many(dataList) customLogout() return True
def loadAccounts(): mydb = dbutil.connectDB() collection = mydb["Account"] cursor = collection.find({}) df = pd.DataFrame(list(cursor)) return df
def createIndex(period): mydb = dbutil.connectDB() collection = mydb[chooseRSICollection(period)] collection.create_index([("code", 1), ("date", 1)])
import dbutil print('start') con = None cursor = None try: # 1. SQLite에 접속한다. dbutil.connectDB('addr.db') print('SQLite Connected') # 2. Table을 생성한다. dbutil.makeTable() print('Table created') # 3. 사용자 정보를 입력한다. user = ['id06', 'pwd06', '홍말숙', '01077776666', '경기', 20] dbutil.insertUser(user) # 4. 사용자 정보를 조회한다. allusers = dbutil.selectUser() for user in allusers: print('%s %s %s %s %s %d' % (user[0], user[1], user[2], user[3], user[4], user[5])) except: print('Error') finally: # 5. SQLite를 close 한다. dbutil.closeDB()
import sqlite3 import dbutil print('Start ....') while True: dbutil.connectDB('hb.db') try: menu = input('***DB만들기***\n' '테이블만들기(m)\n' '사용자정보추가(i)\n' '사용자전체정보조회(a)\n' '사용자정보조회(s)\n' '사용자정보삭제(d)\n' '사용자정보수정(u)\n' '나가기(q)') menu = menu.lower() if menu == 'q': print('Bye') break #테이블 만들기 if menu == 'm': name = input('만드실 테이블 명을 적어주십시오') dbutil.makeTable(name) #사용자정보추가 if menu == 'i': user = input('테이블이름과 추가할 사용자의 정보를 입력하세요\n' 'tableName,id,pwd,name,phone,addr,age\n' '(띄어쓰기기준)') user = user.split(' ') userdata = [] for u in user:
def writeKlineToDb(period, stockCode, stockName, resultSet): dataList = [] #分钟线多了个time字段,偏移量+1 offset = 1 if period.endswith("m") else 0 while (resultSet.error_code == '0') & resultSet.next(): # 获取一条记录,将记录合并在一起 # data_list.append(rs.get_row_data()) row = resultSet.get_row_data() kline = None recordDate = None if period == "day": kline = DayKline(stockCode, stockName) elif period == "week": kline = WeekKline(stockCode, stockName) elif period == "month": kline = MonthKline(stockCode, stockName) elif period == "5m": kline = FiveMinKline(stockCode, stockName) elif period == "15m": kline = FiftyMinKline(stockCode, stockName) elif period == "30m": kline = ThirtyMinKline(stockCode, stockName) elif period == "60m": kline = SixtyMinKline(stockCode, stockName) else: raise RuntimeError("还不支持这个周期:" + period) # recordDate = datetime.strptime(row[0], "%Y-%m-%d") kline.openPrice = row[1 + offset] kline.highPrice = row[2 + offset] kline.lowPrice = row[3 + offset] kline.closePrice = row[4 + offset] kline.volume = row[5 + offset] kline.amount = row[6 + offset] kline.adjustflag = row[7 + offset] # set_trace() # 日K、月K、周K有专有属性 if period == "day" or period == "week" or period == "month": recordDate = datetime.strptime(row[0 + offset], "%Y-%m-%d") kline.turn = row[8 + offset] kline.changePercent = row[9 + offset] else: recordDate = datetime.strptime(row[0 + offset], "%Y%m%d%H%M%S000") # 日K专有属性 if period == "day": kline.preClosePrice = row[10] kline.tradeStatus = row[11] kline.isST = row[12] kline.date = recordDate dataList.append(kline.__dict__) mydb = dbutil.connectDB() collection = mydb[chooseKlineCollection(period)] if len(dataList) > 0: collection.insert_many(dataList) if period == "day": latestKlineDay = dataList[len(dataList) - 1] query = {"code":latestKlineDay["code"]} newvalues = { "$set": { "isST": latestKlineDay["isST"] == "1"} } mydb["Stock"].update_one(query, newvalues) else: raise RuntimeError("数据为空")