개발자_이훈규
천천히, 빠르게. 개발자의 Repository
개발자_이훈규
전체 방문자
오늘
어제
  • 분류 전체보기 (473)
    • 티스토리 (4)
    • 개발자 뉴스 (2)
    • 소프트웨어 (203)
      • C (7)
      • c++ (25)
      • Objective-C (3)
      • Do it! 반응형 웹디자인 (4)
      • openGL (8)
      • Java (24)
      • Jni (3)
      • Android (9)
      • Wordpress (2)
      • 버그 만난 후 느낀점 (2)
      • Git (3)
      • node js (2)
      • window tablet (1)
      • HTML (3)
      • javascript (3)
      • perl (1)
      • AngularJS (0)
      • JSON (0)
      • Docker (3)
      • python (5)
      • jQuery (1)
      • MFC (4)
      • cocos studio (6)
      • Golang (1)
      • SQLite3 (0)
      • Spring Boot (8)
      • thymeleaf (0)
      • Django (0)
      • iOS (3)
      • skia (0)
      • VBA (0)
      • PHP (2)
      • Oracle (1)
      • JSP (0)
      • R (0)
    • TCP IP (2)
    • 금융 (0)
      • 금융 Study (0)
      • 금융 Archive (0)
      • 금융 Article (0)
    • 개인 프로젝트 (7)
      • gif 홈페이지 만들기 (0)
      • study app만들기 (0)
      • 크롤러 만들기 (1)
      • 카툰 홈페이지 만들기 (1)
      • 외주 홈페이지 만들기 (3)
      • 웹 홈페이지 만들기 (0)
      • 미디어 서버 만들기 (0)
      • 소개팅 어플 만들기 (0)
      • 인스타그램 풀스택 클론 코딩(인강 노트) (0)
      • 주식 모의거래 만들기 (1)
    • html php mysql (0)
    • node.Js (2)
    • 일상 (2)
    • 빈공간 uml 공부 (0)
    • Ubuntu(linux) (12)
    • 맥OS (10)
      • android 설치하기 (2)
    • Programming quizzes (0)
    • IoT (구 유비쿼터스) (16)
      • 라즈베리 파이 (11)
      • 아두이노 (5)
    • 하드웨어 (5)
      • 아수스 비보탭 노트8 asus vivotap no.. (2)
      • 크레마 카르타 (3)
    • 분석할 문장, 구문, 코드 (0)
    • 키보드 (1)
      • 해피해킹 (1)
    • 코드 라이언 (0)
    • 전자기기 (4)
    • Ted (0)
    • NAS (0)
    • 알고리즘 (0)
    • 연합인포맥스 (0)
    • 이벤트 응모함 (4)

블로그 메뉴

  • 홈
  • 태그
  • 미디어로그
  • 위치로그
  • 방명록

공지사항

인기 글

태그

  • error
  • 방법
  • 코드
  • 에러
  • Example
  • 라즈베리 파이
  • C
  • GIT
  • Python
  • 예제
  • 소스
  • 설명
  • CODE
  • 우분투
  • 개발
  • Java
  • C++
  • 설치
  • ubuntu
  • install

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
개발자_이훈규

천천히, 빠르게. 개발자의 Repository

네이버 주식 일별 시세 크롤링 (request을 이용, format json)
소프트웨어/python

네이버 주식 일별 시세 크롤링 (request을 이용, format json)

2020. 2. 7. 09:30

요즘에 취미로 데이터 모으는 기법을 공부하고 있다.

 

특히 시계열 데이터를 다루는걸 하는데

pandas datareader로 읽어오면 일별 시세가 온전하지 않아서

naver 주식 일별 시세의 정보로 만드는 코드를 만들었다.

 

 

 

python 네이버 주식 일별 시세를

크롤링으로 pandas datareader형태로

시작일부터 종료일까지

json file로 export하기

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import requests
import time
import pandas as pd
 
from bs4 import BeautifulSoup as bs
from datetime import datetime
 
 
def exportData(code, startdate, enddate):
    
    isEnd = False
    res = {
        'index': [],
        'data': []
    }
    
    print("Start")
    
    page = 1
    while isEnd != True:
        url = "https://finance.naver.com/item/sise_day.nhn?code="+code+"&page="+ str(page)
        response = requests.get(url)
        html = bs(response.text, 'html.parser')
        
        # parse
        trList = html.find_all("tr", {"onmouseover":"mouseOver(this)"})
        for tr in trList:
            tdList = tr.find_all('td')
#             print(tdList[0].text.strip())  # 날짜
#             print(tdList[1].text.strip())  # 종가
#             print(tdList[2].text.strip())  # 전일비
#             print(tdList[3].text.strip())  # 시가
#             print(tdList[4].text.strip())  # 고가
#             print(tdList[5].text.strip())  # 저가
#             print(tdList[6].text.strip())  # 거래량
        
            date = tdList[0].text.strip()  # 날짜
            closePrice = int(tdList[1].text.strip().replace(',', ''))  # 종가
            diffPrice = int(tdList[2].text.strip().replace(',', ''))  # 전일비
            openPrice = int(tdList[3].text.strip().replace(',', ''))  # 시가
            highPrice = int(tdList[4].text.strip().replace(',', ''))  # 고가
            lowPrice = int(tdList[5].text.strip().replace(',', ''))  # 저가
            volume = int(tdList[6].text.strip().replace(',', ''))  # 거래량
            
            target = datetime.fromisoformat(date.replace('.', '-'))
            if target < start:
                isEnd = True
                break
            elif target < end and target > start:
                print(target)
                # insert index
                res['index'].insert(0, date)
                
                # insert data with ["High","Low","Open","Close","Volume","Adj Close"]
                res['data'].insert(0, [highPrice, lowPrice, openPrice, closePrice, volume])
                        
        page += 1
        time.sleep(2)
        
    df = pd.DataFrame(data=res['data'], index=res['index'])
    df.to_json(code+'.json', orient='split', date_format='index')
    
    print("Start - Done")
    
code = "005930"
start = datetime(2019, 1, 1)
end = datetime(2019, 12, 31)
 
exportData(code, start, end)
Colored by Color Scripter
cs

 

저작자표시 (새창열림)

'소프트웨어 > python' 카테고리의 다른 글

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbb in position 0: invalid start byte  (0) 2020.02.12
list에서 짝수 홀수 출력하기  (0) 2015.09.15
[python] print에서 new line(개행문자) 출력하지 않는 방법  (0) 2015.09.09
[python] 파일 입출력 코드/예제  (0) 2015.09.09
    '소프트웨어/python' 카테고리의 다른 글
    • UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbb in position 0: invalid start byte
    • list에서 짝수 홀수 출력하기
    • [python] print에서 new line(개행문자) 출력하지 않는 방법
    • [python] 파일 입출력 코드/예제
    개발자_이훈규
    개발자_이훈규
    혼자 꽁양꽁양 개발하면서 놀아요~ - 노트같은 블로그

    티스토리툴바