상세 컨텐츠

본문 제목

재무제표 다운과 적정주가 구하기

카테고리 없음

by 독서와 여행 2020. 6. 7. 17:58

본문

이정도면 대충은 했다. 문제는 어떤식으로 프로그램을 가꿔 나가야할지 구성을 또 해야한다는 것이다.

내 자산관리 해주는 프로그램에 대한 방향 잡기가 어렵다.

공부를 하다보면 할 수 있는 것과 할 수 없는 것의 구분이 되어서 아이디어를 얻기 좋다.

더 공부를 해야지

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
import os
#C:\Users\Hello world\AppData\Local\Programs\Python\Python37\Lib\site-packages\QtDesigner

# show하는 부분 해야함
form_class = uic.loadUiType(r'untitled.ui')[0]
class financail_show_window(QDialog):
    def __init__(self, parent):
        super(financail_show_window, self).__init__(parent)
        uic.loadUi(r"financial_show.ui", self)
        self.show()
        self.parent = parent
        data = parent.get_request()
        self.plainTextEdit.setPlainText(str(data))
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)
        self.pushButton_check_stock_price.clicked.connect(self.show_price)
        self.pushButton_show_financal_data.clicked.connect(self.show_financial_data)
        self.pushButton_check_roe.clickek.connect(self.show_roe)
        self.pushButton_help.clicked.connect(self.help)
    
    

    def help(self):
        msgBox = QMessageBox()
        msgBox.setText("도움말")

        msgBox = msgBox.exec_() 

    def show_financial_data(self):
        financail_show_window(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_show_financal_data.setEnabled(True)
        else:
            self.pushButton_download.setEnabled(False)
            self.pushButton_show_financal_data.setEnabled(False)
        if self.lineEdit_roe.text() and self.lineEdit_stock_num.text() and self.open:
            self.pushButton_check_stock_price.setEnabled(True)
            self.pushButton_check_roe.setEnabled(True)
        else:
            self.pushButton_check_stock_price.setEnabled(False)
            self.pushButton_check_roe.setEnabled(False)
    
        





    def show_price(self):
        data = self.data
        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]', '',self.lineEdit_stock_num.text()))
        wanting_revenue = float(self.lineEdit_roe.text())

        stock_price = (during_year_capital + (during_year_capital * (during_year_roe - wanting_revenue)/wanting_revenue)) / stock_num 
        msgBox = QMessageBox()
        msgBox.setText("적정주가는 %.2f 원입니다."%(stock_price))

        msgBox = msgBox.exec_() 


    def show_roe(self):
        data = self.data
        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)))
        stock_num =  float(re.sub('[^0-9]', '',self.lineEdit_stock_num.text()))

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

        msgBox = QMessageBox()
        msgBox.setText("ROE는 {}%입니다.".format(during_year_roe,))

        msgBox = msgBox.exec_() 




    def download_linked_financial_statement_to_cvs(self):  
        
        data = self.data
        # if data == None:
            
        #     msgBox = QMessageBox()
        #     msgBox.setText("기업 정보를 입력하고 클릭해 주세요")    
        #     ret = msgBox.exec_() 
        # else:
        fname = os.getcwd()
        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_() 
        
        # msgBox = QMessageBox()
        # msgBox.setText("올바른 기업코드, 연도, 코드를 입력하고 눌러주세요")
        # msgBox = msgBox.exec_() 



    
    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 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()
        driver.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[2]/div[1]/form/fieldset/p[5]/input').click()
        driver.implicitly_wait(1)
        driver.find_element_by_xpath('//*[@id="listContents"]/div[1]/table/tbody/tr[1]/td[1]/div/a').click()
        msgBox = QMessageBox()
        msgBox.setText("종목을 클릭 하시고 rss를 눌러서 기업 코드를 복사하세요 \n 기업코드는 마지막 숫자 8자리 입니다.")
        msgBox.exec_() 
        msgBox.done(3)
       
        
        
            
    
    #         driver.implicitly_wait(10)

        

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

댓글 영역