프로그래밍

PYGT5를 통한 GUI 구현

독서와 여행 2020. 6. 5. 11:27

코드가 정리가 안 되어서 너무 더럽다.

click 버튼 활성화가 지금 per 이랑 roe 쪽이 안된다. 아오

고쳐야 할 것이 많다.

그래도 GUI랑 다운은 되는데 편리하지가 않다.

일단 제대로 구성하고 편리하게 바꿔 봐야지

import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
from stock_content import Financial_Statements
import webbrowser
import re
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from PyQt5.QtGui import QTextCursor
from PyQt5 import QtCore
from pandas.io.json import json_normalize
import pandas as pd
from urllib.request import urlopen,Request
from bs4 import BeautifulSoup
import requests
import json


# 다른 방법을 생각해보고 공부해보자 아오
form_class = uic.loadUiType(r'untitled.ui')[0]
# class findWindow(QDialog):
#     def __init__(self, parent):
#         super(findWindow, self).__init__(parent)
#         uic.loadUi("C:\\PyQT Tutorial\\9. Notepad-FInd\\find.ui", self)
#         self.show()
class WindowClass(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.action_download.triggered.connect(self.downloadFuntion)
        # self.action_open.triggered.connect(self.openFunction)
        # self.action_save.triggered.connect(self.saveFunction)
        # self.action_saveas.triggered.connect(self.saveAsFunction)
        # self.action_open_2.triggered.connect(self.openFunction)
        # self.action_close.triggered.connect(self.close)
        #self.pushButton_find_company_code.clicked.connect(self.search_company_code(self.find_company_code))
        self.opened = False
        self.open_file_path = '제목 없음'
        self.API_KEY = "개인키"
        self.company_code = '0000'
        self.year = None
        self.report_sort = None
        self.data = None
        self.open = False
        self.pushButton_find_company_code.clicked.connect(self.search_company_code)
        self.pushButton_input.clicked.connect(self.get_information)
        self.pushButton_download.clicked.connect(self.download_linked_financial_statement_to_cvs)
        #self.pushButton_help.clicked.connect(self.print_)
        self.pushButton_naver_finance.clicked.connect(self.naver_finance)
    
    
    #def print_(self):

 
    
    def keyReleaseEvent(self, event):
        if self.lineEdit_companycode.text() and self.lineEdit_year.text() and self.lineEdit_reportnum.text():
            self.pushButton_input.setEnabled(True)
        else:
            self.pushButton_input.setEnabled(False)
        if self.lineEdit_companyname.text():
            self.pushButton_find_company_code.setEnabled(True)
        else:
            self.pushButton_find_company_code.setEnabled(False)
        if self.open:
            self.pushButton_download.setEnabled(True)
            self.pushButton_per_roe.setEnabled(True)
        else:
            self.pushButton_download.setEnabled(False)
            self.pushButton_per_roe.setEnabled(False)
    

    
    def download_linked_financial_statement_to_cvs(self):  
        if self.open == True:
            data = self.data
            # if data == None:
                
            #     msgBox = QMessageBox()
            #     msgBox.setText("기업 정보를 입력하고 클릭해 주세요")    
            #     ret = msgBox.exec_() 
            # else:
            fname = QFileDialog.getOpenFileName(self)
            linked_data = data[data['fs_nm'] == '연결재무제표']
            linked_data.to_csv(str(self.company_code)+'.csv',encoding = 'utf-8')
            msgBox = QMessageBox()
            msgBox.setText(fname+"\n 위 경로에 다운 되었습니다.")
            msgBox = msgBox.exec_() 
        else:
            msgBox = QMessageBox()
            msgBox.setText("올바른 기업코드, 연도, 코드를 입력하고 눌러주세요")
            msgBox = msgBox.exec_() 



    # def get_financial_stock_price(self,stock_num, wanting_revenue): # ROE알고 싶으면 reo에 인자 입력하면 됨, 안하면 그냥 가격만 알려줌 주식 발행 량이랑 원하는 수익률도 인자로 받음
    #                                                                 #왜 클릭 안 해도 실행되는거지..??
    #     data =self.data
    #     if data == None:
    #         pass
    #         # msgBox = QMessageBox()
    #         # msgBox.setText("기업 정보를 입력하고 클릭해 주세요")   
    #         # msgBox = msgBox.exec_() 
    #     else:
    #         linked_data = data[data['fs_nm'] == '연결재무제표'].set_index('fs_nm') #일단 인덱스를 0123에서 없애버림, 필요하면 바꾸자 정규식 이용하면 인덱스 있어도 사용가능임

    #         during_year_capital = linked_data[linked_data['account_nm'] == '자본총계']['thstrm_amount']

    #         during_year_capital =  float(re.sub('[^0-9]', '',str(during_year_capital)))#해당년도 자본

    #         during_year_debt = linked_data[linked_data['account_nm'] == '부채총계']['thstrm_amount']
    #         during_year_debt =  float(re.sub('[^0-9]', '',str(during_year_debt)))

    #         during_year_protit = linked_data[linked_data['account_nm'] == '당기순이익']['thstrm_amount']
    #         during_year_protit = float(re.sub('[^0-9]', '',str(during_year_protit)))
            

    #         during_year_roe = during_year_protit / during_year_capital * 100 #해당년도 roe 



    #         stock_num =  float(re.sub('[^0-9]', '',stock_num))
    #         wanting_revenue = float(input("원하는 수익률을 입력하세요 \n"))

    #         stock_price = (during_year_capital + (during_year_capital * (during_year_roe - wanting_revenue)/wanting_revenue)) / stock_num 

    #         return stock_price

    
    
    def get_information(self): #재무제표 가저오는 함수 
        try:
            self.company_code = re.sub('[^0-9]', '',str(self.lineEdit_companycode.text()))

            self.year = re.sub('[^0-9]', '',str(self.lineEdit_year.text()))
            self.report_sort =  re.sub('[^0-9]', '',str(self.lineEdit_reportnum.text()))
        
            self.data = self.get_request()
           
        
            self.open = True
            msgBox = QMessageBox()
            msgBox.setText("정상적으로 입력되었습니다.")
            msgBox = msgBox.exec_() 
        except KeyError:
            self.open = False
            msgBox = QMessageBox()
            msgBox.setText("올바른 정보를 입력하세요.")
            msgBox = msgBox.exec_() 
       


    def naver_finance(self):
        url = "https://finance.naver.com/"
        webbrowser.open(url)
    def find_company_code(self):
        name = lineEdit_companyname.text()
        return str(code)
    def downloadFuntion(self):
        print("download!")
    def get_request(self):
        request= Request('https://opendart.fss.or.kr/api/fnlttSinglAcnt.json?crtfc_key='+self.API_KEY+'&corp_code='+self.company_code+'&bsns_year='+self.year+'&reprt_code='+self.report_sort)
        
        response = urlopen(request)
        elevations = response.read()
        data = json.loads(elevations)
        data = json_normalize(data['list']) ##--- json to dataframe
        data = data.loc[:,['fs_nm','sj_nm','account_nm','thstrm_dt','thstrm_nm','thstrm_amount','frmtrm_nm','frmtrm_amount','bfefrmtrm_nm','bfefrmtrm_amount']] 
       
        return data
    # def save_changeed_data(self):
    #     msgBox = QMessageBox()
    #     msgBox.setText("변경 내용을 {}에 저장하시겠습니까?".format(self.open_file_path))
        
    #     msgBox.addButton('저장',QMessageBox.YesRole)
    #     msgBox.addButton('저장 안 함', QMessageBox.NoRole)  
    #     msgBox.addButton('취소', QMessageBox.RejectRole) 
    #     ret = msgBox.exec_()
    #     if ret == 2:
    #         return ret
    # def closeEvent(self,event):
    #     ret = self.save_changeed_data()
    #     if ret ==2:
    #         event.ignore()
    

    # def save_file(self, fname):
    #     data = self.plainTextEdit.toPlainText()


    #     with open(fname, 'w', encoding='UTF8') as f:
    #         f.write(data)
    
    #     self.opened = True
    #     self.opened_file_path = fname
                    
    #     print("save {}!!".format(fname))


    # def open_file(self, fname):
    #     with open(fname, encoding='UTF8') as f:
    #         data = f.read()
    #     self.plainTextEdit.setPlainText(data)

    #     self.opened = True
    #     self.opened_file_path = fname

    #     print("open {}!!".format(fname))

    # def openFunction(self):
        
    #     fname = QFileDialog.getOpenFileName(self)
    #     if fname[0]:
    #         self.open_file(fname[0])

    # def saveFunction(self):
    #     if self.opened:
    #         self.save_file(self.opened_file_path)
    #     else:
    #         self.saveAsFunction()

    # def saveAsFunction(self):
    #     fname = QFileDialog.getSaveFileName(self)
    #     if fname[0]:
    #         self.save_file(fname[0])
    def search_company_code(self):
        company_name = self.lineEdit_companyname.text()
           
        
        options = webdriver.ChromeOptions()
   
        driver = webdriver.Chrome(r'C:\Users\Hello world\Desktop\python\chromedriver.exe',chrome_options=options)

        driver.get('https://dart.fss.or.kr/dsae001/main.do')


        driver.find_element_by_name('textCrpNm').send_keys(company_name)

        options = webdriver.ChromeOptions()
        msgBox = QMessageBox()
        msgBox.setText("종목을 클릭 하시고 rss를 눌러서 기업 코드를 복사하세요\n10초 후 창이 자동적으로 꺼집니다.")
        msgBox.exec_() 
        msgBox.done(3)
        driver = webdriver.Chrome(r'C:\Users\Hello world\Desktop\python\chromedriver.exe',chrome_options=options)
    
        driver.get('https://dart.fss.or.kr/dsae001/main.do')
    
        
        driver.find_element_by_name('textCrpNm').send_keys(company_name)
        
        
            
    #         driver.find_element_by_xpath('//*[@id="searchForm"]/fieldset/p[5]/input').click()
    #         driver.implicitly_wait(10)

        

app = QApplication(sys.argv)
mainwindow = WindowClass()
mainwindow.show()
app.exec_()