DEV Community

parksejun24
parksejun24

Posted on

Can stock prices be predicted when stock prices fluctuate as they do now?

Introduction

The economy in 2022 was very chaotic. So I got curious that Time series prediction library be able to prediction stock price. To solve this questions, the research was conducte in the following way. The subject of this research is the Korean Stock market and pandas, matplotlib, datetime and fbprophet libraries were used to predict stock price. fbprophet is time series prediction library made by facebook. The rest of the libraries are for additional calculation work.

Process

  1. Stock price data of all companies listed on the Korean stock market will be imported in the form of CSV using the Korea Exchange API.
  2. If you enter the name of the company you want to predict the stock price, the dataframe taken from the API parsing the stock code and date.
  3. Based on the data that has been parsing, it finds stock price data through Yahoo API and brings stock price data from the listing date to today's date.
  4. Learning a time series prediction model based on parsed market closing time stock price data.
  5. The error range data of the predicted value, actual value, predicted value, and actual value for the one year are made in CSV format and stored.

Result

Certainly, the economy is not an area that can be predicted by numbers alone. I expected it to be a library optimized for time series prediction. However, even if the stock data is a time series structure, it is judged that there is a limit to predicting only with numerical data because it is data that moves according to social and economic trends.

CODE

import pandas as pd 
import pandas_datareader as pdr
import matplotlib.pyplot as mpl

from pandas import ExcelWriter
from fbprophet import Prophet #Facebook에서 개발한 시계열 예측 라이브러리 
from datetime import datetime, timedelta, date #날짜, 시간을 쉽게 사용할수있도록 도와주는 라이브러리

koreaStock = pd.read_html('http://kind.krx.co.kr/corpgeneral/corpList.do?method=download', header=0)[0] #한국거래소에서 운영하는 공시사이트 API를 활용하여 실시간으로 공시가를 받아옴
koreaStock = koreaStock.rename(columns={'회사명':'name','종목코드':'stockCode','상장일':'stockBirth'}) #받아온 html형식의 데이터의 컬럼명[회사명, 종목코드, 상장일]을 name, stockCode, stockBirth로 재정의
koreaStock = koreaStock[['name', 'stockCode','stockBirth']] #실질적으로 필요한 데이터인 name, stockCode,stockBirth 컬럼만 남겨둔다

today = [datetime.today().year, datetime.today().month, datetime.today().day] #오늘 날짜의 년, 월, 일 을 받아와 today 배열에 저장
yesterday = (date.today() - timedelta(1)).strftime('%Y-%m-%d') # 어제 날짜를 년-월-일 형식으로 받아온다

def searchStockCode(): # 원하는 주식종목의 데이터를 가져와주는 함수
    try :
        userSerchingStock = input() # 사용자가 원하는 주식종목명 입력
        stockCode = koreaStock[koreaStock['name'].isin([userSerchingStock])].iloc[0,1] #iloc 행 번호로 데이터를 뽑아오는 함수 iloc[0,1]이면 첫번째 행 두번째 행의 데이터만 가져옴   
        stockCode = str(stockCode).zfill(6) + '.KS' #zfill: ex) str(stockCode).zfill(6) 이면 String형식의 문자 6자리중 3자리만 채워져 있으면 앞에서부터 빈공간을 0으로 채우는 함수
        stockBirth = koreaStock[koreaStock['name'].isin([userSerchingStock])].iloc[0,2]
        stockBirth = str(stockBirth).split('-') #split() 특정문자열을 기준으로 문자열을 split해주는 함수 split의 기본값은 공백을 기준으로 split함 
        return stockCode,stockBirth
    except:
        return searchStockCode() # 데이터를 가져오지 못했을때 searchStockCode()함수 다시 실행

stockCode,stockBirth = searchStockCode() # 원하는 주식 종목 데이터 가져옴

start = datetime(int(stockBirth[0]), int(stockBirth[1]), int(stockBirth[2])) # 특정 종목의 상장날짜를 받아옴
done = datetime(today[0],today[1],today[2]) # 오늘날짜

searchStock = pdr.DataReader(stockCode, "yahoo", start, done) # yahoo 주식 사이트에서 상장날부터 오늘까지의 특정주식의 데이터를 가져옴 
realityDF = pd.DataFrame({'ds': searchStock.index, 'y' : searchStock['Close']}) # 상장날부터 지금 까지의 장 마감시간의 주가를 데이터프레임형태로 변환

model = Prophet() #시계열 예측 모델 생성
model.fit(realityDF) # 시계열 예측 모델에 realitydf(특정 종목 역대 장마감 시간의 주가 데이터를 바탕으로 모델 학습)

future = model.make_future_dataframe(periods=365) # 앞으로 1년의 주가를 예측하기로 설정
forecast = model.predict(future) #학습된 모델을 바탕으로 앞으로 1년의 주기를 예측

forecast.to_excel(r'C:\Users\sunny\Documents\StockDataFrame1.xlsx', sheet_name='sheet1' , index = False) #예측한 데이터를 데이터프레임 형태에서 exel형식으로 변환하여 로컬에 저장

futureData = forecast[forecast['ds'].isin([yesterday])] 
futureData = int(futureData.iloc[0,18]) # 예측데이터 

todayData = realityDF.loc[yesterday : yesterday]
todayData = int(todayData.iloc[0,1]) # 실제데이터

errorValue = todayData - futureData # 실제데이터와 예측데이터의 오차범위 비교

print("nowData", todayData,'won', ' | ', 'futureData', futureData, 'won', ' | ', 'errorValue', errorValue, 'won') 

model.plot(forecast) #예측데이터를 바탕으로 plot그리기
mpl.show() # plot 팝업창 띄우기
Enter fullscreen mode Exit fullscreen mode

Top comments (0)