Get stock prices and create candlestick charts in Python

I will write about stock price acquisition and stock price chart (candlestick chart) for stock price analysis. My dreams are only expanding, such as deep learning of time-series data, but this time I will collect tools for studying. However, this is a memo I am studying, so please forgive me for making mistakes (especially in economic terms).

Candlestick chart

According to Wikipedia, a candlestick chart is a "unit period, with the first price attached during the unit period as the opening price, the last price attached as the closing price, the highest price as the highest price, and the lowest price as the lowest price. These four types of prices (four values) are drawn on a single bar-shaped figure called a candle, arranged in chronological order, and the fluctuation of the stock price is represented as a graph. "(Reference: Wikipedia" Candlestick " Chart "). The red candle is the day when the stock price finally rises, and the green candle is the day when the stock price finally falls, making it easy to visually understand the up and down movement of the stock price. Now, I will explain how to create this candlestick chart.   rousokuasi_chart.png

environment

・ Windows 8 ・ Anaconda 4.4.0 (Python3.6) ・ Install "daytime" and "pandas_datareader" with pip

Data acquisition

Python3.6:GetStock.py


import datetime
import pandas_datareader.data as web

#Setting the period
start = datetime.datetime(2017, 1, 1)
end = datetime.datetime(2017, 5, 30)

#Stock price acquisition
df = web.DataReader('TM', 'google', start, end)
df = toyota.drop('Volume', axis=1)  #Erase Volume from DataFrame
df = df.loc[:, ['Open', 'Close', 'High','Low']]

Python has a library to get stock prices, and if you enter the start date, end date, company, and the site to get the data as arguments, it will return it in a format that can be used with pandas. In the case of Google, Volume is also included in the data, but since it is unnecessary, delete it (By the way, Volume is the number of shares traded). Finally, sort the data. The results are shown in the figure below, but as you can see, the relationship between the four values is not clear. So, finally, I will explain how to write a candlestick chart. chart.png

Candlestick chart creation

There is also a candlestick charting library. The upper half is the one explained earlier in data acquisition. A function called "mpf.candlestick_ochl" is provided, so you can easily create a diagram by entering the date and the corresponding data as arguments. A grid is attached to improve visibility.

python3.6:RousokuasiChart.py


import numpy as np
import datetime
import pandas_datareader.data as web
import matplotlib.pyplot as plt
import matplotlib.finance as mpf
from matplotlib.dates import date2num

def main():
    #Setting the stock price acquisition period
    start = datetime.datetime(2017, 1, 1)
    end = datetime.datetime(2017, 5, 30)

    #Stock price acquisition
    df = web.DataReader('TM', 'google', start, end)
    df = toyota.drop('Volume', axis=1)  #Erase Volume from DataFrame
    df = df.ix[:, ['Open', 'Close', 'High','Low']]

    #Image creation
    fig = plt.figure()
    ax = plt.subplot()
    xdate = [x.date() for x in df.index]  #date
    ochl = np.vstack((date2num(xdate), df.values.T)).T
    mpf.candlestick_ochl(ax, ochl, width=0.7, colorup='g', colordown='r')
    ax.grid()  #Grid display
    ax.set_xlim(df.index[0].date(), df.index[-1].date())  #x-axis range
    fig.autofmt_xdate()  #x-axis autoformat
    plt.savefig('rousokuasi_chart.png')#Save image

if __name__ == '__main__':
    main()

Running this program completes the candlestick chart you first saw.

rousokuasi_chart.png

Reference site

  1. "Forecast stock prices from past data by big data analysis"

http://qiita.com/ynakayama/items/420ebe206e34f9941e51

  1. Get the stock price with Python and display it as a graph

http://qiita.com/akichikn/items/782033e746c7ee6832f5

  1. Display candlestick chart in Python (matplotlib edition)

http://qiita.com/toyolab/items/1b5d11b5d376bd542022

Recommended Posts

Get stock prices and create candlestick charts in Python
Create and read messagepacks in Python
Displaying candlestick charts in Python (matplotlib edition)
Displaying candlestick charts in Python (Plotly edition)
Detect golden crosses on stock charts in Python
Create SpatiaLite in Python
Get date in Python
Get your current location and user agent in Python
Plot Bitcoin candle charts and technical indicators in Python
Get YouTube Comments in Python
Drawing candle charts in python
Create a function in Python
Create a dictionary in Python
Create gif video in Python
Get Terminal size in Python
Explicitly get EOF in python
Stack and Queue in Python
Unittest and CI in Python
[python] Get quotient and remainder
Get stock price with Python
Get Evernote notes in Python
Get Japanese synonyms in Python
Get and create nodes added and updated in the new version
Get the MIME type in Python and determine the file format
Create code that outputs "A and pretending B" in python
Get the current date and time in Python, considering the time difference
Get Leap Motion data in Python.
MIDI packages in Python midi and pretty_midi
Difference between list () and [] in Python
View photos in Python and html
Sorting algorithm and implementation in Python
Get data from Quandl in Python
Create a DI Container in Python
Get the desktop path in Python
Manipulate files and folders in Python
About dtypes in Python and Cython
Get the script path in Python
Assignments and changes in Python objects
Create your own graph structure class and its drawing in python
Create a binary file in Python
Check and move directories in Python
Create Gmail in Python without API
Ciphertext in Python: IND-CCA2 and RSA-OAEP
Hashing data in R and Python
Get, post communication memo in Python
Function synthesis and application in Python
Create a CGH for branching a laser in Python (laser and SLM required)
Create a Kubernetes Operator in Python
Export and output files in Python
Get the desktop path in Python
Reverse Hiragana and Katakana in Python2.7
Get the host name in Python
Reading and writing text in Python
[GUI in Python] PyQt5-Menu and Toolbar-
Create a random string in Python
Get started with Python in Blender
Get the title and delivery date of Yahoo! News in Python
How to get the date and time difference in seconds with python
Get parameter and Post body, enable CORS in Flask (Python) and Express (Node.js)
Sample code to get the Twitter API oauth_token and oauth_token_secret in Python 2.7
Get options in Python from both JSON files and command line arguments