def getStockGoodBadfromHK(stock_code): count_good = 0 count_bad = 0 try: driver = Preference.getWebDriver() today = date.today() pre_1month = today - timedelta(30) today_str = today.strftime('%Y-%m-%d') pre_1month_str = pre_1month.strftime('%Y-%m-%d') #목표상향 갯수 추출 request_url = 'http://consensus.hankyung.com/apps.analysis/analysis.list?skinType=stock_good&search_text=' + stock_code + '&sdate=' + pre_1month_str + '&edate=' + today_str #print request_url driver.get(request_url) table_element = driver.find_element_by_xpath( '//*[@id="contents"]/div[2]/table/tbody') tablebody_html = table_element.get_attribute('innerHTML') soup = BeautifulSoup(tablebody_html, "html.parser") stock_element_list = soup.find_all('tr') for stock_element in stock_element_list: result_msg = stock_element.find('td').text #print result_msg #if(result_msg.find("결과가".decode('UTF-8'))): if "결과가".decode('UTF-8') in result_msg: print("None") else: count_good = count_good + 1 #목표하향 갯수 추출 request_url = 'http://consensus.hankyung.com/apps.analysis/analysis.list?skinType=stock_bad&search_text=' + stock_code + '&sdate=' + pre_1month_str + '&edate=' + today_str #print request_url driver.get(request_url) table_element = driver.find_element_by_xpath( '//*[@id="contents"]/div[2]/table/tbody') tablebody_html = table_element.get_attribute('innerHTML') soup = BeautifulSoup(tablebody_html, "html.parser") stock_element_list = soup.find_all('tr') for stock_element in stock_element_list: result_msg = stock_element.find('td').text #print result_msg #if(result_msg.find("결과가".decode('UTF-8'))): if "결과가".decode('UTF-8') in result_msg: print("None") else: count_bad = count_bad + 1 except Exception as e: print(e) return count_good, count_bad
def tester(): today = date.today() yesterday = today - timedelta(1) yesterday_str = yesterday.strftime('%Y-%m-%d') today_str = datetime.today().strftime('%Y-%m-%d') request_url = 'http://hkconsensus.hankyung.com/apps.analysis/analysis.list?skinType=stock_good&sdate=' + yesterday_str + '&edate=' + today_str + '&order_type=10010000&pagenum=150' print(request_url) driver = Preference.getWebDriver() driver.get(request_url) report_index_element = driver.find_element_by_xpath( '//*[@id="contents"]/div[2]/table/tbody/tr/td[2]/div') report_index_html = report_index_element.get_attribute('innerHTML') spl = report_index_html.split("\"") spl2 = spl[1].split("_") report_index = spl2[1] ''' soup = BeautifulSoup(tablebody_html, "html.parser") div_list = soup.find_all('div') for _div in div_list: print _div print '---' ''' #print tablebody_html return True
def makeSTOCKHtml(stock_dic_list): KST=datetime.now(timezone('Asia/Seoul')) time_info = KST.strftime('%Y-%m-%d %H:%M') stock_html = "<span style=\"font-size: 10pt;\">금일의 상승여력 랭킹</span><br>"\ "<span style=\"font-size: 10pt;\">"+time_info+"기준 발행된 증권사 리서치 보고서 중 목표가와 현 주가의 괴리율이 큰 기업순위입니다.</span><br>"\ "<br/>"\ " " pre_stockconsen_html ="" count = 1 for stock_dic in stock_dic_list: stock_html += \ "<hr style=\"border: double 1px black;\">"\ "<span style=\"font-size: 10pt;\"><span style=\"font-size: 18pt;\"><strong><a href=\"https://finance.naver.com/item/main.nhn?code="+stock_dic['stock_code'].encode('UTF-8')+"\" target=\"_blank\">" +stock_dic['stock_name'].encode('UTF-8')+"</a></strong></span>("+stock_dic['stock_code'].encode('UTF-8')+") 현재가 : "+ stock_dic['now_price'].encode('UTF-8')+"("+stock_dic['now_updown_rate'].encode('UTF-8')+")</br>"\ "<a href=\""+stock_dic['companyinfo_url'].encode('UTF-8')+"\">[기업]</a><a href=\""+stock_dic['report_url'].encode('UTF-8')+"\">[report]</a></span><br>" stock_html += "<span style=\"font-size: 10pt;\"><span style=\"font-size: 12pt;\"><strong>목표가 대비 현재가 : "+stock_dic['diff_rate'].encode('UTF-8')+"%</strong></span> (현재 "+stock_dic['now_price'].encode('UTF-8')+" / <strong>목표"+stock_dic['new_price'].encode('UTF-8')+"</strong>)</span><br>"\ "<span style=\"font-size: 10pt;\">"+stock_dic['analyst_company'].encode('UTF-8')+"("+stock_dic['analyst_name'].encode('UTF-8')+") : "+stock_dic['update_date'].encode('UTF-8')+"</span><br>"\ "<span style=\"font-size: 10pt;\"> - "+stock_dic['title'].encode('UTF-8')+"</span>" try: print stock_dic['stock_code'] volume_ratio, detail_html = makeStockDetailHtml(stock_dic['stock_code']) stock_html += detail_html #print "." except Exception as e: print '--- stack ---' traceback.print_stack() print '--- exec ---' traceback.print_exc() print 'makestockdetail exception' try: pre_stockconsen_html=makePreSTOCKHtml(stock_dic['stock_code']) except Exception as e: print '--- stack ---' traceback.print_stack() print '--- exec ---' traceback.print_exc() print 'prestockhtml exception' count = count+1 stock_html += pre_stockconsen_html + '<br>' if (count > Preference.getStockRankCount()): break stock_html += \ "<br><br>"\ "<hr style=\"border: double 1px black;\">"\ "<span style=\"font-size: 10pt;\">증권 투자는 원금손실의 가능성에 유의하시고, 투자자 본인의 판단과 책임하에 최종 결정을 하셔야 합니다. </span><br>"\ "<span style=\"font-size: 10pt;\">본 자료는 어떠한 경우에도 증권투자 결과에 대한 법적 책임소재의 증빙자료로 사용될 수 없습니다.</span><br>" return stock_html
def makeSTOCKHtml(stock_dic_list): KST=datetime.now(timezone('Asia/Seoul')) time_info = KST.strftime('%Y-%m-%d %H:%M') stock_html = "<span style=\"font-size: 10pt;\">금일의 특징주</span><br>"\ "<span style=\"font-size: 10pt;\">"+time_info+" 특징주 목록입니다.</span><br>"\ "<br/>"\ " " pre_stockconsen_html ="" count = 1 for stock_dic in stock_dic_list: stock_html = stock_html + "<hr style=\"border: double 1px black;\">" \ "<span style=\"font-size: 10pt;\"><span style=\"font-size: 18pt;\"><strong><a href=\"https://finance.naver.com/item/main.nhn?code="+str(stock_dic['stock_code'])+"\" target=\"_blank\">" +stock_dic['stock_name']+"</a></strong></span>("+str(stock_dic['stock_code'])+") 현재가 : "+ str(stock_dic['now_price'])+"(" + str(stock_dic['now_updown_rate'])+ ")</br>" \ "<a href=\""+stock_dic['companyinfo_url']+"\">[기업]</a></span><br>" try: print(stock_dic['stock_code']) volume_ratio, detail_html = makeStockDetailHtml(stock_dic['stock_code'], stock_dic) stock_html = stock_html + detail_html #print "." except Exception as e: print('--- stack ---') traceback.print_stack() print('--- exec ---') traceback.print_exc() print('makestockdetail exception') try: pre_stockconsen_html=makePreSTOCKHtml(stock_dic['stock_code']) except Exception as e: print('--- stack ---') traceback.print_stack() print('--- exec ---') traceback.print_exc() print('prestockhtml exception') count = count+1 stock_html = stock_html + pre_stockconsen_html + '<br>' if (count > Preference.getStockRankCount()): break stock_html += \ "<br><br>"\ "<hr style=\"border: double 1px black;\">"\ "<span style=\"font-size: 10pt;\">증권 투자는 원금손실의 가능성에 유의하시고, 투자자 본인의 판단과 책임하에 최종 결정을 하셔야 합니다. </span><br>"\ "<span style=\"font-size: 10pt;\">본 자료는 어떠한 경우에도 증권투자 결과에 대한 법적 책임소재의 증빙자료로 사용될 수 없습니다.</span><br>" return stock_html
def getCurrentStockPriceNaver(stock_code): stock_price = {} if stock_code == '130960': stock_code = '035760' request_url = 'https://finance.naver.com/item/main.nhn?code=' + stock_code driver = Preference.getWebDriver() try: driver.get(request_url) #print request_url + "aaa" stock_price_info_element = driver.find_element_by_xpath( '//*[@id="middle"]/dl/dd[4]') stock_price_info = stock_price_info_element.get_attribute('innerHTML') #print stock_price_info stock_price_info_array = stock_price_info.split(' ') #print stock_price_info_array[1] #print stock_price_info_array[5] #print stock_price_info_array[6] #stock_updown_rate = driver.find_element_by_xpath('//*[@id="disArr[0]"]/span') #print stock_updown_rate.text plusminus = stock_price_info_array[5] if (plusminus == '플러스'): plusminus = '+' #print '+' elif (plusminus == '마이너스'): plusminus = '-' #print '-' #stock_price['now_price'] = stock_price_info_array[1].encode('utf-8') stock_price['now_price'] = stock_price_info_array[1] #stock_price['updown_rate'] = plusminus.encode('utf-8')+stock_price_info_array[6].encode('utf-8')+'%'.encode('utf-8') stock_price[ 'updown_rate'] = plusminus + stock_price_info_array[6] + '%' except Exception as e: print(e) stock_price['now_price'] = "0" stock_price['updown_rate'] = "0" #print stock_code #print stock_now_price.text #print stock_updown_rate.text #print stock_now_price.text+' ('+stock_updown_rate+')' return stock_price
def getCommpanyInfo(stock_code): stock_info = {} request_url = 'https://navercomp.wisereport.co.kr/v2/company/c1010001.aspx?cmp_cd=' + stock_code print(request_url) driver = Preference.getWebDriver() driver.get(request_url) company_info = driver.find_element_by_xpath( '/html/body/div/form/div[1]/div/div[2]/div[3]/div/div/div[5]/div[2]/ul' ) company_info_html = company_info.get_attribute('innerHTML') print(company_info_html) soup = BeautifulSoup(company_info_html, "html.parser") company_info_list = soup.find_all('li') for a_company_info in company_info_list: print(a_company_info) return 0
def getUpturnStockFromHK(): #한경 컨세서스 연결. stock_dic_list = [] today = date.today() today_str = datetime.today().strftime('%Y-%m-%d') yesterday = today - timedelta(Preference.getStockDaysCount()) yesterday_str = yesterday.strftime('%Y-%m-%d') request_url = 'http://hkconsensus.hankyung.com/apps.analysis/analysis.list?skinType=stock_good&sdate='+yesterday_str+'&edate='+today_str+'&order_type=10010000&pagenum=150' print(request_url) driver = Preference.getWebDriver() driver.get(request_url) table_element = driver.find_element_by_xpath('//*[@id="contents"]/div[2]/table/tbody') tablebody_html = table_element.get_attribute('innerHTML') soup = BeautifulSoup(tablebody_html, "html.parser") stock_element_list = soup.find_all('tr') for stock_element in stock_element_list: #DATE upload_date=stock_element.td.string stock_data = stock_element.find_all('td') stock_dic ={} i = 1 for astock_data in stock_data: if(i==1): #print astock_data.text stock_dic['update_date']=astock_data.text if(i==2): #print '---' stock_dic['report_url']='' try: spl1 = str(astock_data).split("\n") #print spl1 spl2 = spl1[3].split("\"") #print spl2 spl3 = spl2[3].split("_") #print spl3 report_index = spl3[1] #print report_index stock_dic['report_url']='http://hkconsensus.hankyung.com/apps.analysis/analysis.downpdf?report_idx='+report_index except: stock_dic['report_url']='' stock_dic['all_title'] = astock_data.find('strong').text all_title = stock_dic['all_title'] start = all_title.find('(')+1 end = start+6 stock_code = all_title[start:end] stock_dic['stock_code']=stock_code stock_name = all_title[0:all_title.find('(')] stock_dic['stock_name']=stock_name title = all_title[end+1:len(all_title)] stock_dic['title']=title #print stock_dic['all_title'] #print stock_dic['stock_code'] #print stock_dic['stock_name'] #print stock_dic['title'] if(i==3): #print astock_data.text stock_dic['analyst_name']=astock_data.text if(i==4): #print astock_data.text stock_dic['analyst_company']=astock_data.text if(i==5): #print astock_data.text stock_dic['new_price']=astock_data.text if(i==6): #print astock_data.text stock_dic['old_price']=astock_data.text continue i=i+1 #print "." stock_dic['companyinfo_url']='http://media.kisline.com/highlight/mainHighlight.nice?paper_stock='+stock_code+'&nav=1' #print stock_dic['companyinfo_url'] upper_rate=float(stock_dic['new_price'].replace(',',''))/float(stock_dic['old_price'].replace(',','')) upper_rate=int((upper_rate-1)*100) stock_dic['upper_rate']=str(upper_rate) if(stock_dic['new_price'] != "0" ): now_stock_price = GetStockPrice.getCurrentStockPriceNaver(stock_dic['stock_code']) stock_dic['now_price']=now_stock_price['now_price'] stock_dic['now_updown_rate']=now_stock_price['updown_rate'] print((stock_dic['stock_name'])) print((stock_dic['new_price'])) print((stock_dic['now_price'])) diff_rate=float(stock_dic['now_price'].replace(',',''))/float(stock_dic['new_price'].replace(',','')) diff_rate=int(diff_rate*100) stock_dic['diff_rate']=str(diff_rate) print((stock_dic['diff_rate'])) if(diff_rate > 20 and diff_rate < 100): stock_dic_list.append(stock_dic) #print stock_dic #다 뽑아와서 차이나는 순대로 정렬 stock_dic_list_sorted = sorted(stock_dic_list, key=lambda k: k['diff_rate'], reverse=False) return stock_dic_list_sorted
def getCurrentStockConsenFromHK(): #한경 컨세서스 연결. stock_dic_list = [] KST = datetime.now(timezone('Asia/Seoul')) today_str = KST.strftime('%Y-%m-%d') #몇일전까지 : days=0 은 오늘 startday_str = ( datetime.today() - timedelta(days=Preference.getStockDaysCount())).strftime('%Y-%m-%d') #몇개 분석할 것이냐? stock_count = Preference.getStockLoadCount() #request_url = 'http://hkconsensus.hankyung.com/apps.analysis/analysis.list?skinType=stock_good&sdate='+today_str+'&edate='+today_str+'&order_type=10010000&pagenum=150' #http://hkconsensus.hankyung.com/apps.analysis/analysis.list?skinType=business&sdate=2019-04-03&edate=2019-04-09&pagenum=1000&order_type=12000001&now_page=1 request_url = 'http://hkconsensus.hankyung.com/apps.analysis/analysis.list?skinType=business&sdate=' + startday_str + '&edate=' + today_str + '&pagenum=' + stock_count + '&order_type=12000001&now_page=1' print(request_url) driver = Preference.getWebDriver() driver.get(request_url) #html = driver.page_source table_element = driver.find_element_by_xpath( '//*[@id="contents"]/div[2]/table/tbody') tablebody_html = table_element.get_attribute('innerHTML') #print tablebody_html soup = BeautifulSoup(tablebody_html, "html.parser") stock_element_list = soup.find_all('tr') for stock_element in stock_element_list: #DATE upload_date = stock_element.td.string stock_data = stock_element.find_all('td') stock_dic = {} stockcode = '000000' i = 1 for astock_data in stock_data: if (i == 1): #print astock_data.text stock_dic['update_date'] = astock_data.text if (i == 2): #print astock_data.find('strong').text stock_dic['all_title'] = astock_data.find('strong').text all_title = stock_dic['all_title'] start = all_title.find('(') + 1 end = start + 6 stock_code = all_title[start:end] stock_dic['stock_code'] = stock_code stockcode = stock_code stock_name = all_title[0:all_title.find('(')] stock_dic['stock_name'] = stock_name title = all_title[end + 1:len(all_title)] stock_dic['title'] = title #print stock_dic['all_title'] #print stock_dic['stock_code'] #print stock_dic['stock_name'] #print stock_dic['title'] if (i == 3): #적정가격 #print astock_data.text stock_dic['new_price'] = astock_data.text if (i == 4): #print astock_data.text stock_dic['opinion'] = astock_data.text if (i == 5): #print astock_data.text stock_dic['analyst_name'] = astock_data.text if (i == 6): #print "####a####" #print astock_data.text stock_dic['analyst_company'] = astock_data.text if (i == 9): for link in astock_data.find_all('a', href=True): url = link['href'] stock_dic[ 'report_url'] = 'http://hkconsensus.hankyung.com/' + url #print stock_dic['report_url'] break i = i + 1 #print "." stock_dic[ 'companyinfo_url'] = 'http://media.kisline.com/highlight/mainHighlight.nice?paper_stock=' + stockcode + '&nav=1' #print stock_dic['companyinfo_url'] if (stock_dic['new_price'] != "0"): now_stock_price = GetStockPrice.getCurrentStockPriceNaver( stock_dic['stock_code']) stock_dic['now_price'] = now_stock_price['now_price'] stock_dic['now_updown_rate'] = now_stock_price['updown_rate'] print((stock_dic['stock_name'])) print((stock_dic['new_price'])) print((stock_dic['now_price'])) diff_rate = float(stock_dic['now_price'].replace(',', '')) / float( stock_dic['new_price'].replace(',', '')) diff_rate = int(diff_rate * 100) stock_dic['diff_rate'] = str(diff_rate) print((stock_dic['diff_rate'])) if (diff_rate > 20 and diff_rate < 100): stock_dic_list.append(stock_dic) #print stock_dic stock_dic_list_sorted = sorted(stock_dic_list, key=lambda k: k['diff_rate'], reverse=False) return stock_dic_list_sorted
from src.util import Preference from src.get import GetStockListfromHK a = ' \n AAAAAA \n ' print a temp = a.splitlines() a = "".join(temp) print '--------' a = a.replace(' ', '') print a print '-----' a = a.rstrip('\n') print a print '----' ''' #환경세팅 Preference.setPhantomjsPath() Preference.setChromedriverPath() Preference.setWebDriverInit() try: #최근 몇개 주식을 가지고 올것이냐(250) Preference.setStockLoadCount("250") #250 #괴리율 랭킹 몇등까지 표출 Preference.setStockRankCount(30) #20 #이전목표주가는 몇개까지 표출 Preference.setPrePriceCount(7) #7
def main(login_pw, mail_pw): #환경세팅 Preference.setPhantomjsPath() Preference.setChromedriverPath() Preference.setWebDriverInit() try: #최근 몇개 주식을 가지고 올것이냐(250) Preference.setStockLoadCount("250") #250 #괴리율 랭킹 몇등까지 표출 Preference.setStockRankCount(50) #20 #이전목표주가는 몇개까지 표출 Preference.setPrePriceCount(7) #7 #몇일전 보고서 까지 찾을꺼냐 Preference.setStockDaysCount(14) #14 stock_dic_list = GetStockListfromHK.getCurrentStockConsenFromHK() count, result_html = HtmlMaker.makeVolumeUpHtml(stock_dic_list) print " " print "--------------------------------" print " " #print result_html print "--------------------------------" KST = datetime.now(timezone('Asia/Seoul')) title_name = KST.strftime('%Y년 %m월 %d일 %H시 '), ' 저평가 거래 폭증종목 Catcher' driver = Preference.getWebDriver() if (count > 1): if (Preference.isLinux()): SendEmail.sendMailtoGmail(title_name, result_html, mail_pw) time.sleep(10) #WriteWordPress.write_post(WriteWordPress.write_init(driver,login_pw), Preference.getCategory("거래폭발"), title_name, "", result_html) else: print "Nothing Catched" print "--------------------------------" except Exception as e: print e traceback.print_stack() traceback.print_exc() print "exception" finally: #Driver 닫기 Preference.setWebDriverClose()
def main(login_pw): #환경세팅 Preference.setPhantomjsPath() Preference.setChromedriverPath() Preference.setWebDriverInit() try: #이전목표주가는 몇개까지 표출 Preference.setPrePriceCount(7) Preference.setStockRankCount(20) #GetStockInfoDetail.getCommpanyInfo('054950') #exit(0) stock_dic_list = GetStockListfromMaster.getStockListfromCreonPlus() for astock in stock_dic_list: print(astock['stock_code'], " : ", astock['stock_name']) Preference.setStockRankCount(len(stock_dic_list)) result_html = HtmlMaker.makeSTOCKHtml(stock_dic_list) print("############################################") print("############################################") print("############################################") print(result_html) print("--------------------------------") KST = datetime.now(timezone('Asia/Seoul')) title_name = KST.strftime('%Y년 %m월 %d일 %H시 '), ' 오늘의 특징 주 ' driver = Preference.getWebDriver() WriteWordPress.write_post(WriteWordPress.write_init(driver, login_pw), Preference.getCategory("오늘의특징주"), title_name, "", result_html) print("--------------------------------") ''' print "--------------------------------" KST=datetime.now(timezone('Asia/Seoul')) title_name = KST.strftime('%Y년 %m월 %d일 %H시 '),' 상승여력 랭킹 ' driver = Preference.getWebDriver() WriteWordPress.write_post(WriteWordPress.write_init(driver,login_pw), Preference.getCategory("상승여력"), title_name, "", result_html) print "--------------------------------" ''' except Exception as e: print('--- stack ---') traceback.print_stack() print('--- exec ---') traceback.print_exc() print('--- e ---') print(e) print("exception") finally: #Driver 닫기 Preference.setWebDriverClose()
def getStockListfromCreonPlus(): ''' 1 전략 목록 가져오기 ''' ## 8357 종목검색Master 전략목록 Object cpsysdiblist = win32com.client.Dispatch("CpSysDib.CssStgList") ## 전략을 가져올 Type 세팅(나의전략:ord('1') cpsysdiblist.SetInputValue(0, ord('1')) # '0' : 예제전략, '1': 나의전략 ##Block모드로 cpsysdiblist.BlockRequest() ##불러오기 count = cpsysdiblist.GetHeaderValue(0) #0 : (long) 전략목록수 flag = cpsysdiblist.GetHeaderValue(1) #1 : (char) 요청구분 st_items = {} strategy_id = '' for i in range(count): st_items['전략명'] = cpsysdiblist.GetDataValue(0,i); st_items['전략ID'] = cpsysdiblist.GetDataValue(1,i); #시간에 맞는 해당전략 ID를 가져옴 st_name = Preference.getRSIVolAgainstTime() if(st_items['전략명']==st_name): strategy_id = st_items['전략ID'] #print(strategy_id) ''' 2 전략 검색종목 가져오기 ''' ## 8357 종목검색Master 전략조회 Object cpsysdibfind = win32com.client.Dispatch("CpSysDib.CssStgFind") #매집후 거래상승 ID 요청 cpsysdibfind.SetInputValue(0,strategy_id) cpsysdibfind.BlockRequest() #검색된 결과 종목 수 cnt = cpsysdibfind.GetHeaderValue(0) # 총 검색 종목 수 totcnt = cpsysdibfind.GetHeaderValue(1) # 종목코드(종목명) 가져오기용 Object instCpStockCode = win32com.client.Dispatch("CpUtil.CpStockCode") item_list = [] for i in range(cnt): item={} #종목코드 item['code'] = cpsysdibfind.GetDataValue(0,i) item['종목명'] = instCpStockCode.CodeToName(item['code']) item_list.append(item) #추출된 종목 보기 print(item_list) stock_dic_list = [] ''' 3. 종목 현재가 가져오기 ''' # 주식 종목 현재가 가져오기용 Object now_price = win32com.client.Dispatch("Dscbo1.StockMst") # 매매 입체분석(투자주체별 현황) -> 수급조회용 supplydemand = win32com.client.Dispatch("CpSysDib.CpSvr7254") # 마켓아이 -> 체결강도 marketeye = win32com.client.Dispatch("CpSysDib.MarketEye") for i in range(len(item_list)): try: #print(item_list[i]) #print(item_list[i]['code']) stock_dic = {} ## 현재가 조회 now_price.SetInputValue(0,item_list[i]['code']) now_price.BlockRequest() ## 수급현황 조회 ## supplydemand.SetInputValue(0,item_list[i]['code']) # 종목코드 supplydemand.SetInputValue(1,6) # 일자별 조회 supplydemand.SetInputValue(4,ord('0')) #순매수량 (1:매매비중) supplydemand.SetInputValue(5,0) #전체투자자 조회 supplydemand.SetInputValue(6,ord('1')) # 순매수량 supplydemand.BlockRequest() stockcode = item_list[i]['code'] stockcode = stockcode[1:len(stockcode)] stockname = item_list[i]['종목명'] stockprice = now_price.GetHeaderValue(11) # organ = supplydemand.GetDataValue(3,0) #기관 foriegner = supplydemand.GetDataValue(2,0) #외국인 stock_dic['stock_code']=stockcode print("A") print(stockcode) stock_dic['stock_name']=stockname print("B") print(stockname) stock_dic['now_price']=stockprice print("C") print(stockprice) #현재가 #print('종목코드 : ', now_price.GetHeaderValue(0), ' | 종목명 : ' , item_list[i]['종목명'], ' | 현재가 : ', now_price.GetHeaderValue(11), ' | 전일대비 : ',now_price.GetHeaderValue(12) ) #print('기관 : ', supplydemand.GetDataValue(3,0), '외국인 : ', supplydemand.GetDataValue(2,0), '개인 : ', supplydemand.GetDataValue(1,0)) ## 마켓아이 종목정보 조회 ## # 10(거래량) , 24(체결강도),67(PER), 96(분기BPS), 110(분기부채비율), 116(프로그램순매수), 117(잠정외국인), 119(잠정기관) marketeye.SetInputValue(0, [10, 24, 67, 96, 110, 116, 117, 119 ]) marketeye.SetInputValue(1, item_list[i]['code']) marketeye.Blockrequest() ## 마켓아이 # 종목 리턴 갯수 #cnt = marketeye.GetHeaderValue(2) volume = marketeye.GetDataValue(0,0) # 거래량 power = round(marketeye.GetDataValue(1,0),2) # 체결강도 per = round(marketeye.GetDataValue(2,0),2) # PER bps = marketeye.GetDataValue(3,0) # 분기BPS if(bps == 0): pbr = 0.0 else: pbr = round(now_price.GetHeaderValue(11)/bps,2) #PBR debt_rate = round(marketeye.GetDataValue(4,0),2) # 분기부채비율 program_buy = marketeye.GetDataValue(5,0) # 프로그램 stock_dic['power']=power #체결강도 stock_dic['pbr']=pbr #PBR stock_dic['per']=per stock_dic['debt_rate'] = debt_rate stock_dic['companyinfo_url']='http://media.kisline.com/highlight/mainHighlight.nice?paper_stock='+stockcode+'&nav=1' print(('거래량 : ', volume, ' | 체결강도 : ', power, ' | PER : ', per, ' | PBR : ', pbr)) print(('분기부채비율 : ', debt_rate, ' | 프로그램 : ', program_buy)) print ('-----') ### 최근 6개월 종목리포트 조회 #stock_pre_consen_list = GetStockListfromHK.getPreStockConsenFromHK(stockcode) #print(stock_pre_consen_list) ## 귀찮으니 대비율은 NAVER에서 가져오는걸로 now_stock_price = GetStockPrice.getCurrentStockPriceNaver(stock_dic['stock_code']) stock_dic['now_updown_rate']=now_stock_price['updown_rate'] stock_dic_list.append(stock_dic) except Exception as E: print("Exception : " + str(stock_dic['stock_code'])) return stock_dic_list
def main(login_pw, mail_pw): #환경세팅 Preference.setPhantomjsPath() Preference.setChromedriverPath() Preference.setWebDriverInit() try: #몇일 전 목표가 상향보고서까지 가지고 올건지 Preference.setStockDaysCount(14) #이전목표주가는 몇개까지 표출 Preference.setPrePriceCount(7) ### RSI과매도 종목을 몇개까지? Preference.setStockRankCount(20) ### 목표가 상향 종목 가져오기 stock_dic_list = GetStockListfromHK.getUpturnStockFromHK() ### 크레온 Plus에서 수급정보 가져오기 stock_dic_list = GetDetailInfoFromPlus.getPlusStockInfo(stock_dic_list) ### result_html = HtmlMaker.makeUpturnStockHtml(stock_dic_list) try: ### 과매도 종목 가져오기 ### print("RSI 과매도 종목 가져오기") stock_dic_list2 = GetStockListfromMaster.getStockListfromCreonPlus( ) stock_dic_list2 = GetDetailInfoFromPlus.getPlusStockInfo( stock_dic_list2) result_html += HtmlMaker.makeRSIdownSTOCKHtml(stock_dic_list2) except Exception as E: print("RSI과매도 가져오기 실패") print(E) traceback.print_exc() result_html += HtmlMaker.getPostScript() print(result_html) KST = datetime.now(timezone('Asia/Seoul')) title_name = KST.strftime('%Y년 %m월 %d일 %H시 '), ' CHOICESTOCK ' #if(ResultVO.getIsCatched()): print("WordPress Write Start") driver = Preference.getWebDriver() #WriteWordPress.write_post(WriteWordPress.write_init(driver,login_pw), Preference.getCategory("목표상향"), title_name, "", result_html) print("WordPress Write Complete") print("Send Email Start") SendEmail.sendMailtoGmail(title_name, result_html, mail_pw) #else: #print("CHOICESTOCK Didn't Catch Any Stock") except Exception as e: print('--- stack ---') traceback.print_stack() print('--- exec ---') traceback.print_exc() print(e) print("exception") finally: #Driver 닫기 Preference.setWebDriverClose()
def main(login_pw): #환경세팅 Preference.setPhantomjsPath() Preference.setChromedriverPath() Preference.setWebDriverInit() try: #이전목표주가는 몇개까지 표출 Preference.setPrePriceCount(7) stock_dic_list = GetStockListfromHK.getUpturnStockFromHK() result_html = HtmlMaker.makeUpturnStockHtml(stock_dic_list) print " " print "--------------------------------" print " " print result_html print "--------------------------------" KST = datetime.now(timezone('Asia/Seoul')) title_name = KST.strftime('%Y년 %m월 %d일 %H시 '), ' 목표가 상향기업 ' driver = Preference.getWebDriver() WriteWordPress.write_post(WriteWordPress.write_init(driver, login_pw), Preference.getCategory("목표상향"), title_name, "", result_html) print "--------------------------------" except Exception as e: print '--- stack ---' traceback.print_stack() print '--- exec ---' traceback.print_exc() print '--- e ---' print e print "exception" finally: #Driver 닫기 Preference.setWebDriverClose()
def main(login_pw, mail_pw): #환경세팅 Preference.setPhantomjsPath() Preference.setChromedriverPath() Preference.setWebDriverInit() try: #몇일간 리포트 확인, 최근 1주리포트 Preference.setStockDaysCount(7) #이전목표주가는 몇개까지 표출 Preference.setPrePriceCount(7) ##목표주가 상향 리포트 확인 stock_dic_list = GetStockListfromHK.getUpturnStockFromHK() ### 크레온 Plus에서 수급정보 가져오기 stock_dic_list = GetDetailInfoFromPlus.getPlusStockInfo(stock_dic_list) ### result_html = HtmlMaker.makeUpturnAllStockHtml(stock_dic_list) print("--------------------------------") print(result_html) print("--------------------------------") KST = datetime.now(timezone('Asia/Seoul')) title_name = KST.strftime('%Y년 %m월 %d일 %H시 '), ' 목표가 상향기업 ' print("WordPress Write Start") driver = Preference.getWebDriver() #WriteWordPress.write_post(WriteWordPress.write_init(driver,login_pw), Preference.getCategory("목표상향"), title_name, "", result_html) print("WordPress Write Complete") print("--------------------------------") print("Send Email Start") SendEmail.sendMailtoGmail(title_name, result_html, mail_pw) except Exception as e: traceback.print_stack() traceback.print_exc() print(e) print("exception") finally: #Driver 닫기 Preference.setWebDriverClose()
def getPreStockConsenFromHK(stock_code): try: stock_pre_consen_list = [] today = date.today() yesterday = today - timedelta(1) pre_2month = today - timedelta(90) yesterday_str = yesterday.strftime('%Y-%m-%d') pre_2month_str = pre_2month.strftime('%Y-%m-%d') request_url = 'http://hkconsensus.hankyung.com/apps.analysis/analysis.list?sdate='+pre_2month_str+'&edate='+yesterday_str+'&now_page=1&search_value=&report_type=CO&pagenum=50&search_text='+stock_code+'&business_code=' print(request_url) driver=Preference.getWebDriver() driver.get(request_url) table_element = driver.find_element_by_xpath('//*[@id="contents"]/div[2]/table/tbody') tablebody_html = table_element.get_attribute('innerHTML') #print tablebody_html soup = BeautifulSoup(tablebody_html, "html.parser") stock_element_list = soup.find_all('tr') count = 1 for stock_element in stock_element_list: #DATE upload_date=stock_element.td.string stock_data = stock_element.find_all('td') stock_pre_consen ={} i = 1 for astock_data in stock_data: if(i==1): #print astock_data.text stock_pre_consen['update_date']=astock_data.text if(stock_pre_consen['update_date']=='결과가 없습니다.'): break if(i==2): #print astock_data.find('strong').text stock_pre_consen['all_title'] = astock_data.find('strong').text all_title = stock_pre_consen['all_title'] start = all_title.find('(')+1 end = start+6 stock_code = all_title[start:end] stock_pre_consen['stock_code']=stock_code #stockcode=stock_code stock_name = all_title[0:all_title.find('(')] stock_pre_consen['stock_name']=stock_name title = all_title[end+1:len(all_title)] stock_pre_consen['title']=title if(i==3): #print astock_data.text stock_pre_consen['consen_price']=astock_data.text print('###'+stock_pre_consen['consen_price']) if(i==4): #print astock_data.text stock_pre_consen['opinion']=astock_data.text if(i==6): #print astock_data.text stock_pre_consen['analyst_company']=astock_data.text if(i==9): for link in astock_data.find_all('a', href=True): url = link['href'] stock_pre_consen['report_url'] = 'http://hkconsensus.hankyung.com/'+ url #print stock_dic['report_url'] break i=i+1 #print "." #if(stock_pre_consen['consen_price']=='0'): if(stock_pre_consen['update_date']=='결과가 없습니다.'): print('NONE A') elif(stock_pre_consen['stock_code']==''): print('NONE B') else: stock_pre_consen_list.append(stock_pre_consen) count+=1 ''' stock_pre_consen_list.append(stock_pre_consen) count+=1 ''' #print '####'+count #print 'debug4' #print count if (count > Preference.getPrePriceCount()): print(Preference.getPrePriceCount() + ' line limited') break except Exception as e: print('No Pre Consen') print(str(e)) print(stock_pre_consen_list) return stock_pre_consen_list
def getStockDeatilInfofromPaxnet(stock_code): stock_info = {} request_url = 'http://www.paxnet.co.kr/stock/analysis/presentValue?abbrSymbol=' + stock_code print(request_url) driver = Preference.getWebDriver() try: driver.get(request_url) #시가총액 stock_info_element = driver.find_element_by_xpath( '//*[@id="contents"]/div[1]/div[2]/div[1]/div/table/tbody/tr[8]/td[1]' ) stock_info['total_cap'] = stock_info_element.get_attribute('innerHTML') print(stock_info['total_cap']) #당일 거래량 stock_info_element = driver.find_element_by_xpath( '//*[@id="contents"]/div[1]/div[2]/div[1]/div/table/tbody/tr[4]/td[1]' ) stock_info['today_volume'] = stock_info_element.get_attribute( 'innerHTML') print(stock_info['today_volume']) #전일 거래량 -> 5일평균으로 변경 #stock_info_element = driver.find_element_by_xpath('//*[@id="contents"]/div[1]/div[2]/div[1]/div/table/tbody/tr[8]/td[2]') #stock_info['everage_5day_volume']= stock_info_element.get_attribute('innerHTML') #print stock_info['everage_5day_volume'] # 5일평균 거래량 volume_bf_days_element = driver.find_element_by_xpath( '//*[@id="viewHtml2"]/tr[1]/td[8]') volume_bf_1day = float( volume_bf_days_element.get_attribute('innerHTML').replace(',', '')) volume_bf_days_element = driver.find_element_by_xpath( '//*[@id="viewHtml2"]/tr[2]/td[8]') volume_bf_2day = float( volume_bf_days_element.get_attribute('innerHTML').replace(',', '')) volume_bf_days_element = driver.find_element_by_xpath( '//*[@id="viewHtml2"]/tr[3]/td[8]') volume_bf_3day = float( volume_bf_days_element.get_attribute('innerHTML').replace(',', '')) volume_bf_days_element = driver.find_element_by_xpath( '//*[@id="viewHtml2"]/tr[4]/td[8]') volume_bf_4day = float( volume_bf_days_element.get_attribute('innerHTML').replace(',', '')) volume_bf_days_element = driver.find_element_by_xpath( '//*[@id="viewHtml2"]/tr[5]/td[8]') volume_bf_5day = float( volume_bf_days_element.get_attribute('innerHTML').replace(',', '')) everage_5day_volume = float( (volume_bf_1day + volume_bf_2day + volume_bf_3day + volume_bf_4day + volume_bf_5day) / 5) #거래량 5일평균 대비 volume_ratio = float(stock_info['today_volume'].replace( ',', '')) / everage_5day_volume volume_ratio = int(volume_ratio * 100) stock_info['volume_ratio'] = str(volume_ratio) print(stock_info['volume_ratio']) #PER #stock_info_element = driver.find_element_by_xpath('//*[@id="contents"]/div[1]/div[2]/div[1]/div/table/tbody/tr[12]/td[1]') #stock_info_element = driver.find_element_by_xpath('//*[@id="contents"]/div[1]/div[2]/div[1]/div/table/tbody/tr[12]/td[1]') stock_info_element = driver.find_element_by_xpath( '//*[@id="contents"]/div[1]/div[2]/div[1]/div/table/tbody/tr[13]/td[1]' ) stock_info['PER'] = stock_info_element.get_attribute('innerHTML') stock_info['PER'] = stock_info['PER'].replace('\ubc30', '') temp = stock_info['PER'].splitlines() stock_info['PER'] = "".join(temp) stock_info['PER'] = stock_info['PER'].replace('-', '0.0') print(stock_info['PER']) #PBR #stock_info_element = driver.find_element_by_xpath('//*[@id="contents"]/div[1]/div[2]/div[1]/div/table/tbody/tr[13]/td[2]') #stock_info_element = driver.find_element_by_xpath('//*[@id="contents"]/div[1]/div[2]/div[1]/div/table/tbody/tr[13]/td[1]') stock_info_element = driver.find_element_by_xpath( '//*[@id="contents"]/div[1]/div[2]/div[1]/div/table/tbody/tr[14]/td[1]' ) stock_info['PBR'] = stock_info_element.get_attribute('innerHTML') stock_info['PBR'] = stock_info['PBR'].replace('\ubc30', '') temp = stock_info['PBR'].splitlines() stock_info['PBR'] = "".join(temp) stock_info['PBR'] = stock_info['PBR'].replace('-', '0.0') print(stock_info['PBR']) good_count = 0 bad_count = 0 good_count, bad_count = getStockGoodBadfromHK(stock_code) stock_info['GOOD'] = str(good_count) stock_info['BAD'] = str(bad_count) except Exception as e: print(e) return stock_info
def makeUpturnStockHtml(stock_dic_list): KST = datetime.now(timezone('Asia/Seoul')) time_info = str(KST.strftime('%Y-%m-%d %H:%M')) stock_html = "<span style=\"font-size: 11pt;\">"+time_info+" 목표가 상향 특징주.</span><br>"\ "<br/>"\ " " pre_stockconsen_html = "" count = 1 for stock_dic in stock_dic_list: stock_html_head = "" stock_html_head += ""\ "<hr style=\"border: double 1px black;\">"\ "<span style=\"font-size: 10pt;\"><span style=\"font-size: 18pt;\"><strong><a href=\"https://finance.naver.com/item/main.nhn?code="+stock_dic['stock_code']+"\" target=\"_blank\">" +stock_dic['stock_name']+"</a></strong></span>("+stock_dic['stock_code']+") 현재가 : "+ stock_dic['now_price']+"("+stock_dic['now_updown_rate']+")<br>"\ "<a href=\""+stock_dic['companyinfo_url']+"\"> [기업]</a><a href=\""+stock_dic['report_url']+"\">[report]</a></span><br>" stock_html_head += "<strong>상승률 : " + stock_dic[ 'upper_rate'] + "%</strong> (<strong>신규" + stock_dic[ 'new_price'] + "</strong> / 이전 " + stock_dic[ 'old_price'] + ")</span><br>" stock_html_head += "<strong>목표가 대비 현재가 : " stock_html_head += makeMarkTagStart('70', stock_dic['diff_rate'], 'DIFF_RATE', '') stock_html_head += stock_dic['diff_rate'] + "%</strong>" stock_html_head += makeMarkTagEnd() stock_html_head += "(현재 "+stock_dic['now_price']+" / <strong>목표"+stock_dic['new_price']+"</strong>)</span><br>"\ "<span style=\"font-size: 10pt;\">"+stock_dic['analyst_company']+"("+stock_dic['analyst_name']+") : "+stock_dic['update_date']+"</span><br>"\ "<span style=\"font-size: 10pt;\"> - "+stock_dic['title']+"</span>" try: volume_ratio, detail_html = makeStockDetailHtml( stock_dic['stock_code'], stock_dic) if (Preference.getVolAgainstTime(volume_ratio)): #종목이 하나라도 잡히면 True로 세팅. ResultVO.setIsCatched(True) stock_html += stock_html_head stock_html += detail_html ##이전 목표주가 가져오기 pre_stockconsen_html = makePreSTOCKHtml( stock_dic['stock_code']) stock_html += pre_stockconsen_html + '<br>' else: print("거래량 미달로 PASS") except Exception as e: print('--- stack ---') traceback.print_stack() print('--- exec ---') traceback.print_exc() print('prestockhtml exception') #print "." print('Making Upturn HTML Complete') count = count + 1 return stock_html
def main(login_pw): #환경세팅 Preference.setPhantomjsPath() Preference.setChromedriverPath() Preference.setWebDriverInit() try: #최근 몇개 주식을 가지고 올것이냐(250) Preference.setStockLoadCount("250") #250 #괴리율 랭킹 몇등까지 표출 Preference.setStockRankCount(30) #20 #이전목표주가는 몇개까지 표출 Preference.setPrePriceCount(7) #7 #몇일전 보고서 까지 찾을꺼냐 Preference.setStockDaysCount(14) #14 stock_dic_list = GetStockListfromHK.getCurrentStockConsenFromHK() result_html = HtmlMaker.makeSTOCKHtml(stock_dic_list) #print result_html print "--------------------------------" KST=datetime.now(timezone('Asia/Seoul')) title_name = KST.strftime('%Y년 %m월 %d일 %H시 '),' 상승여력 랭킹 ' driver = Preference.getWebDriver() WriteWordPress.write_post(WriteWordPress.write_init(driver,login_pw), Preference.getCategory("상승여력"), title_name, "", result_html) print "--------------------------------" except Exception as e: print '--- stack ---' traceback.print_stack() print '--- exec ---' traceback.print_exc() print '--- e ---' print e print "exception" finally: #Driver 닫기 Preference.setWebDriverClose()
def getPreStockConsenFromHK(stock_code): #driver = webdriver.PhantomJS(phantomjs, service_args=['--cookies-file=/tmp/cookies.txt']) #driver.delete_all_cookies() ''' opt = webdriver.ChromeOptions() opt.add_argument('headless') opt.add_argument("--disable-gpu") driver = webdriver.Chrome(chromedrive, chrome_options=opt) ''' try: stock_pre_consen_list = [] today = date.today() yesterday = today - timedelta(1) pre_2month = today - timedelta(60) yesterday_str = yesterday.strftime('%Y-%m-%d') pre_2month_str = pre_2month.strftime('%Y-%m-%d') request_url = 'http://hkconsensus.hankyung.com/apps.analysis/analysis.list?sdate=' + pre_2month_str + '&edate=' + yesterday_str + '&now_page=1&search_value=&report_type=CO&pagenum=50&search_text=' + stock_code + '&business_code=' print request_url #driver = webdriver.PhantomJS(phantomjs) driver = Preference.getWebDriver() driver.get(request_url) table_element = driver.find_element_by_xpath( '//*[@id="contents"]/div[2]/table/tbody') tablebody_html = table_element.get_attribute('innerHTML') #print tablebody_html soup = BeautifulSoup(tablebody_html, "html.parser") stock_element_list = soup.find_all('tr') count = 1 for stock_element in stock_element_list: #DATE upload_date = stock_element.td.string stock_data = stock_element.find_all('td') stock_pre_consen = {} i = 1 for astock_data in stock_data: if (i == 1): #print astock_data.text stock_pre_consen['update_date'] = astock_data.text if (i == 3): #print astock_data.text stock_pre_consen['consen_price'] = astock_data.text print '###' + stock_pre_consen['consen_price'] if (i == 4): #print astock_data.text stock_pre_consen['opinion'] = astock_data.text if (i == 6): #print astock_data.text stock_pre_consen['analyst_company'] = astock_data.text if (i == 9): stock_pre_consen['report_url'] = astock_data.text print stock_pre_consen['report_url'] i = i + 1 #print "." if (stock_pre_consen['consen_price'] == '0'): print 'Not Rated' else: stock_pre_consen_list.append(stock_pre_consen) count += 1 #print '####'+count #print 'debug4' #print count if (count > Preference.getPrePriceCount()): print Preference.getPrePriceCount() + ' line limited' break except Exception, e: print 'No Pre Consen' print str(e)