def subprocess(code, sYear, eYear): print("*******checking reports*******") try: sT.checkStockReport(code, sYear, eYear) except Exception as e: print(e) print("*******checking asset_debt*******") try: sT.checkStockAssetDebt(code, sYear, eYear) except Exception as e: print(e) print("*******checking distrib*******") try: sT.checkDistrib(code, sYear, eYear) except Exception as e: print(e) print("*******checking price*******") try: sT.checkStockPrice(code, sT.getDateString(sYear,1,1), sT.getDateString(eYear,12,31)) except Exception as e: print(e) print("*******checking DONE*******")
print "checking reports..." found, YEARSTART = sT.checkStockReport(code, YEARSTART, reportYearLast) if found == False: exit(1) print "checking distrib..." if sT.checkDistrib(code, YEARSTART, reportYearLast) == False: exit(1) print "checking DONE!" YEARList = [0] * (YEAREND - YEARSTART + 1) DividenRateList = [0] * (YEAREND - YEARSTART + 1) conn = sT.createDBConnection() i = 0 for year in range(YEARSTART, YEAREND + 1): YEARList[i] = year if year != yearNow: found, price, m, d = sT.getClosePriceForward( code, sT.getDateString(year, 12, 31)) else: found, price, m, d = sT.getClosePriceForward( code, time.strftime('%Y-%m-%d', time.localtime(time.time()))) if found: nStock = moneyInvest / price print code, name, year, "年,nStock=", nStock, "Price=", price else: print code, name, year, "年,价格获取失败!" try: sqlString = "select distrib from stockreport_" sqlString += "%s" % (year) sqlString += "_4 where code=" sqlString += code ret = conn.execute(sqlString) except Exception, e:
ndividend += nStockTotal * r # 送转增加股本计算 nStockTotal += nStockTotal * s # print( year, "年,每10股分红:", 10*r, "送转股数:", 10*s nStockThisMonth = int(moneyLimit/closePrice/100)*100 #买入股数,如结果为560股则买入500股 nStockInvest += nStockThisMonth #总计购入股本 if nStockThisMonth==0: nStockThisMonth = 100 #至少保证买入100股 nCapitalInvestThisMonth = nStockThisMonth*closePrice+5 #5元为买入手续费 if nMaxInvPerMonth<nCapitalInvestThisMonth: nMaxInvPerMonth = nCapitalInvestThisMonth if nMinInvPerMonth>nCapitalInvestThisMonth: nMinInvPerMonth = nCapitalInvestThisMonth #print( year,month,actualDay,closePrice,nStockTotal,nCapitalInvest nStockTotal += nStockThisMonth #本年总计股数 nCapitalInvest += nCapitalInvestThisMonth #本月投入成本 profit = nStockTotal*closePrice+ndividend-nCapitalInvest rate = profit/nCapitalInvest tradeDate = sT.getDateString(year, month, actualDay) if lostMoneyMax>profit:#由于计算时只计算检查日时的最大回撤,可能有比检查日回撤更大的时候,尤其是最后卖出时。 lostMoneyMax = profit lostMoneyMaxCaption = nCapitalInvest lostMoneyMaxTime = tradeDate if earnMoneyMax<profit:#由于计算时只计算检查日时的最大收益,可能有比检查日收益更大的时候,尤其是最后卖出时。 earnMoneyMax = profit earnMoneyMaxCaption = nCapitalInvest earnMoneyMaxTime = tradeDate if rate<worstRate: worstRate = rate worstRateTime = tradeDate worstLost = profit if rate>bestRate: bestRate = rate bestRateTime = tradeDate
if str == "c": stype = BONUS_CASH #现金分红 str = input("如不进行分红检查请按'回车',如需检查请按'c',退出请按'q': ") if str == "q": exit(0) if str == "c": print("开始检查基金分红数据......") for i in range(count): if code[i] == u'': continue sT.checkFundDistrib(code[i]) print("基金分红数据检查完成!") print(u"定投计算时间段为:", STARTYEAR, u"年", STARTMONTH, u"月", STARTDAY, u"日\ ---", ENDYEAR, u"年", ENDMONTH, u"月", ENDDAY, u"日") startDate = sT.getDateString(STARTYEAR, STARTMONTH, STARTDAY) endDate = sT.getDateString(ENDYEAR, ENDMONTH, ENDDAY) dataList = [] for i in range(count): url = "http://fund.eastmoney.com/data/FundInvestCaculator_AIPDatas.aspx?fcode=" + code[ i] url = url + "&sdate=" + startDate + "&edate=" + endDate + "&shdate=" + endDate url = url + "&round=" + "%s" % (INTERVAL) + "&dtr=" + "%s" % ( BUYDAY) + "&p=" + "0" + "&je=" + INVESTMONEY url = url + "&stype=" + stype + "&needfirst=" + "2" + "&jsoncallback=FundDTSY.result" response = urllib.request.urlopen(url=url) data = response.read().decode("utf8") time.sleep(randint(1, 3)) infoStr = data.split('|') name[i] = infoStr[1]
foundData, EPS = sT.getStockEPSTTM(code, year - 1, 3) _, epsdic = sT.getStockEPSdiscountTTM( code, year - 1, 3) totalStock = sT.getStockCountQuarter( code, year - 1, 3) # 得到总市值 EPSTTMList.append(EPS) EPSTTMdiscountList.append(epsdic) print(strInfo) if year > LASTYEAR: _, closePrice, _, _ = sT.getClosePriceForward(code, date) else: _, closePrice, m2, d2 = sT.getClosePriceForward(code, year, 12, 31) PEList.append(0 if EPS <= 0 else closePrice / EPS) PEDiscList.append(0 if epsdic <= 0 else closePrice / epsdic) PriceList.append(closePrice * totalStock) # 得到当年总市值 print( sT.getDateString(year,m2,d2),",BasicPETTM=",PEList[-1],", ","discountPETTM=",PEDiscList[-1],\ "stockcount=",totalStock,"priceTotal=", round(PriceList[-1]/10**4,0), ",EPSTTM=",EPS,\ ",EPSDicountTTM=",epsdic) drawPE = PEList[-1] for dt in DATA2WATCH: y1, m1, d1 = sT.splitDateString(dt) if y1 == year: foundData = False qt = sT.createCalender().getQuarter(m1) if qt == 1: foundData, EPSTTM = sT.getStockEPSTTM(code, y1 - 1, 4) _, EPSdiscountTTM = sT.getStockEPSdiscountTTM(code, y1 - 1, 4) #totalStock = sT.getStockCountQuarter(code, y1 - 1, 4) totalStock = sT.getStockCount(code, y1, m1, d1) else: qt = qt - 1 #本季度报表没有出来,因此使用上季度报表
engine = create_engine( 'mysql://*****:*****@127.0.0.1:3306/stockdatabase?charset=utf8', encoding='utf-8') conn = engine.connect() for i in range(count): if code[i] == "" or code[i] == '0.0': worksheet.write(i + 1, 0, "") continue foundData = False foundData, closePrice, tm, actualbuyDay = sT.getClosePriceForward( code[i], STARTYEAR, STARTMONTH, buyDay) if foundData: nCapitalInvest = closePrice * nStockInvest else: print("ERROR:", code[i], name[i], sT.getDateString(STARTYEAR, STARTMONTH, actualbuyDay), "未找到该股交易信息") continue ndividend = 0.0 # 总分红 nStockTotal = nStockInvest # 最终获得股数,初始为购买的股数 lostMoneyMax = 0 lostMoneyMaxCaption = nCapitalInvest lostMoneyMaxTime = "" dictColumnValues = {} print(code[i], name[i]) for year in range(STARTYEAR, ENDYEAR + 1): distribYear = year - 1 bDividen = True try: sqlString = "select distrib from stockreport_" sqlString += "%s" % (distribYear)
i] url = url + "&page=1&per=20&sdate=" url = url + dateToSearch url = url + "&edate=" url = url + dateToSearch url = url + "&rt=0.19110643402290917" data = urllib.urlopen(url).read() bs = bs4.BeautifulSoup(data, "html.parser") try: closePrice = float(bs.find_all("td")[2].get_text()) foundData = 1 except Exception, e: print code[i], name[i], u"没有今日数据!", dateToSearch y, m, d = sT.splitDateString(dateToSearch) y, m, d = sT.createCalender().getPrevWorkday(y, m, d) dateToSearch = sT.getDateString(y, m, d) elif market[i] != "fund": found, closePrice, am, actualDay = sT.getClosePriceForward(code[i], date, autp=None) dateToSearch = sT.getDateString(y, am, actualDay) if found == True: foundData = 1 else: foundData = 0 if foundData == 1: print code[i], name[i], closePrice, dateToSearch #如果中间有既不是股票也不是基金的行,i值也会+1,就相当于在excel中插入不是股票和基金的空行 worksheet.write(i, 0, code[i]) worksheet.write(i, 1, name[i])
except Exception, e: print "获取" + p[0] + ":" + p[1] + "数据失败!" continue data = response.read() bs = bs4.BeautifulSoup(data, "html.parser") jsonStr = bs.get_text().replace("\r", "").replace("\n", "")[14:-1] jsPair = json.loads(jsonStr) if not jsPair['ProdList']: print "获取" + p[0] + ":" + p[1] + "当前净值数据失败!" continue jsInfo = jsPair['ProdList'][0] if jsInfo['netval'] is None: print "获取" + p[0] + ":" + p[1] + "当前净值数据失败!" continue dateStr = jsInfo['netvalDate'] date = sT.getDateString(dateStr[:4], dateStr[4:6], dateStr[6:]) sqlString = "select * from bankproductprice where " sqlString += "code='%s' and " % (p[0]) sqlString += "date='%s'" % (date) try: ret = conn.execute(sqlString) result = ret.first() if result is not None: print date, p[1], ":数据已经存在,无需更新!" continue else: sqlString = "insert into bankproductprice(code,price,date) values(" sqlString += "'%s'," % (p[0]) sqlString += "%s," % (jsInfo['netval']) sqlString += "'%s')" % (date)
STARTMONTH = 2 #投资起始月份 startDay = 26 #投资起始日期 ENDYEAR = 2021 #投资结束年 ENDMONTH = 3 #投资结束月份 endDay = 31 #投资结束日 print u"WARNING:请注意基金历史分红情况,默认以现金分红为准!" str = raw_input("默认红利再投进行计算请按'回车',如需以现金分红进行计算请按'c',退出请按'q': ") if str=="q" : exit(0) stype = "1" #红利再投 if str=="c" : stype = "2" #现金分红 print u"一次性投资计算时间段为:",STARTYEAR,u"年",STARTMONTH,u"月", startDay,u"日\ ---",ENDYEAR,u"年",ENDMONTH,u"月", endDay,u"日" startDate = sT.getDateString(STARTYEAR, STARTMONTH, startDay) saleDate = sT.getDateString(ENDYEAR, ENDMONTH, endDay) data = xlrd.open_workbook('.\\data\\fundata.xls') table = data.sheets()[0] nrows = table.nrows-1 a = np.zeros([nrows]) code = np.array(a, dtype=np.unicode) name = np.array(a, dtype=np.unicode) count = 0 for i in range(nrows): if table.cell(i + 1, 1).value != "": code[i] = table.cell(i + 1, 0).value name[i] = table.cell(i + 1, 1).value count += 1 workbook = xlwt.Workbook(encoding = 'ascii')