Import stock Data (ticker code and stock price)

  • Related Categories: How to get stock data, System trading

    You know how to import stock data, but you need the code information for the stock you want to import. 

    Let’s learn how. 


    1. Manually download from KRX 

    You can get the code manually from the link below. 


    Select the desired exchange from the market segmentation and then click the EXCEL button to download it. 


    2. Crawl the web using Pandas 

    This process is equivalent to the course of 1 automatically. 

    Turn on the Chrome developer tool and select the Networks tab.

    Select Market segmentation as a security, and then press the EXCEL button. 

    If you click Headers on the upper screen, the Request URL will be as shown below. 


    And when you see the Form Data column off the screen, it looks like this. 

    In other words, when the user presses the EXCEL button, the Web browser requests data, including Form data, in the request URL. So the KRX server is going to return data to the request.

    With this request in Python, we can get the right data right away. 

    Let’s create a function that functions. Type the following code after you create the file in the autoTradeLesson folder and: 

    import pandas as pd
    def getStockCode(market):
        if market == 'kosdaq':
            url_market = 'kosdaqMkt'
        elif market == 'kospi':
            url_market = 'stockMkt'
            print('invalid market ')
        url = '' % url_market
        df = pd.read_html(url, header=0)[0]
        return df
    if __name__ == '__main__':
        result_df = getStockCode('kosdaq')


    In the code above, I used a library called Pandas, which is the library that is installed when Pandas-datareader is installed. We’re going to be using a lot of pandas to develop in the future, so let’s do a post later in time for pandas. 

    (Once you see it here… –Pandas library document)

    The getStockCode function accepts the market name as a factor and receives the company information listed in KOSPI or Kosdaq. Call getStockCode (‘ Kospi ‘) if you would like to receive Kospi data. 

    GetStockCode (‘ Kosdaq ‘) result


    3. Processing imported data 

    You need a ticker code to get the stock price data from Yahoo. Note that the following are the types of arguments used to request a stock price for Yahoo! 

    1. KOSPI: {Ticker code}. Ks
    2. KOSDAQ: {Ticker code}. KQ

    In other words, one of the results we have been to getStockCode is the need for company name and ticker code. So let’s create a code that stores the data that we have, and extracts only what we want. 

    if __name__ == '__main__':
        result_df = getStockCode('kospi')
        print(result_df[['회사명', '종목코드']])


    If you run the above code, you can see that the kospi.csv file is stored in the autoTradeLesson folder, where the code is run, and output as shown below in the Pycharm results section. 


    4. Request stock data for all/selected stocks in Yahoo 

    In the above operation, we have saved the ticker code-related data from the Web to the Kospi.csv file. 

    Now, let’s read this file to extract the company name and ticker code, and then write the code to get the stock price for a specific company or entire exchange. 

    from pandas_datareader import data
    import os
    def getStockPrice(market, companyNameList = []):
        dirName = "stockPriceData"
        # -------------- dirName을 가진 폴더가 없으면 폴더를 만듬 -----------
            if not (os.path.isdir(dirName)):
        except OSError as e:
            print("Failed to create directory!!!!!", e)
        # -------------- 저장한 종목 코드가 담겨있는 CSV 파일을 Open -----------
        csv_file_name = market + '.csv'
            df = pd.read_csv(csv_file_name)
            print ('No file ')
        # -------------- 종목코드를 Yahoo 가 이해할 수 있는 코드로 변환 -----------
        suffix = '.KS' if market == 'kospi' else '.KQ'
        df_nameAndCode = df[['회사명', '종목코드']]
        df_nameAndCode['종목코드'] = df_nameAndCode['종목코드'].astype(str)
        df_nameAndCode['종목코드'] = df_nameAndCode['종목코드'].str.zfill(6) + suffix
        # -------------- 전체종목 가져오기 -----------
        if companyNameList == []:
            for idx, dat in df_nameAndCode.iterrows():
                    df_stockPrice = data.get_data_yahoo(dat['종목코드'])
                    fileName = os.path.join(dirName, dat['회사명'] + '.csv')
                    print(dat['회사명'], ' Saved')
                except Exception as e:
                    print(dat['회사명'], e)
        # -------------- companyNameList 에 정의된 종목만 가져오기 -----------
            for companyName in companyNameList:
                    idx = df_nameAndCode['회사명'].tolist().index(companyName)
                    df_stockPrice = data.get_data_yahoo(df_nameAndCode['종목코드'][idx])
                    fileName = os.path.join(dirName, df_nameAndCode['회사명'][idx] + '.csv')
                    print(df_nameAndCode['회사명'][idx], ' Saved')
                except Exception as e:



    After you have written the above function in your work file, you can get the data you want by calling the function at the bottom of the file. 

    if __name__ == '__main__':
        #result_df = getStockCode('kospi')
        #print(result_df[['회사명', '종목코드']])
        #getStockPrice('kospi') # 전체 kospi 주가를 가져옴
        getStockPrice('kospi', ['신세계', '삼성전자'])# List 안의 종목만 가져옴 <br><br>


    The red content below is Warning, so you can ignore it. 

    You can see Samsung Electronics and Shinsegae’s stock data values are stored in CSV format as shown below. 


    5. Results

    Getting stock prices from Yahoo is easy, but it took a very long time to get the stock to run for the entire code… And sometimes the request failed due to a frequent Request, intermittent. 

    Yahoo requests are good for back-testing based on historical data. 

    Yahoo is now bothering to stop, and in the next post we’ll cover the Woom securities API. 


    For ♦ Result codes, please see Github below 


    You can refer to the file. 



    You may also like...

    댓글 남기기

    이메일은 공개되지 않습니다.