How to get stock data (Pandas)
Let’s start with getting stock data first.
There are three ways to receive stock price.
- Using brokerage API
- crawl webpages
- Using APIs provided by Google, Yahoo, Morningstar, etc.
First of all, in this post, we will try to import stock price data in third ways which is most simple.
While various vendors offer APIs, let’s first write code that gets data from Yahoo, the oldest.
(However, Yahoo does not provide the latest data for Kospi and Kosdaq. I will post on this part how to get everything from the next or next next post, but data like Nasdaq provides full stock data. .)
Import stock data from Yahoo using Pandas datareader library
Before writing the code, activate the virtual environment on CMD and install the library with the following command.
(You can install it from Pycharm, Open the project and go to File> Settings …> Project Interpreter> right “+” button> search pandas-datareader> install)
- how to enable virtualenv —>Virtualenv Enable
pip install pandas-datareader
If the installation is successful, we will create code to get Naver’s stock price data from Yahoo.
Open Pycharm and write the code below.
from pandas_datareader import data # '035420.KS' = Naver's stock ticker code.KospiCode naver = data.get_data_yahoo('035420.KS') print(naver.head()) print(naver.tail())
As a result of executing the code, the following screen will be displayed.
I have imported data from 2010-01-04 to 2019-03-22 but there is no stock data from February 1 to March 21.
Saving data to a file
In the code above, you can save the pandas dataframe stored in a variable called naver in various forms such as Excel, csv, pickle.
Write the following code after the above code and run it
In the autoTradeLesson Folder, you can see that the file is created as below.
Note that if you want to save in excel format xlsx format, install the library with the following command in CMD environment.
pip install openpyxl
Then add below code
You can get the excel data from running this code from Pycharm
from pandas_datareader import data # '035420.KS' = Naver's stock ticker code.KospiCode naver = data.get_data_yahoo('035420.KS') print(naver.head()) print(naver.tail()) naver.to_csv('naver.csv') naver.to_excel('naver.xlsx') naver.to_pickle('naver.pickle')
I will finish this post with this.
Now that you know how to get the stock, should you know what stock is available? So, in the next post, I will create a code that downloads Kospi, Kosdaq’s stock ticker code and downloads all the stocks or names of certain companies.
Thank you and see you again