Use Python for stock market data analysis-do candlestick chart

Source: Internet
Author: User
Tags stock prices



As the undergraduate in the school period around a lot of friends are financial professional, they are in my ear to talk about the stock situation, affected by their influence, the long-term interest in securities. A few months before graduation to find an internship unit, and Chance coincidentally worked in this area for a period of time, learning the various theories of securities trading (Dow Theory, Japanese Candle chart technology, wave theory, etc.), although the late career to do the professional work (data mining), but the securities trading this piece has been concerned. Nothing to do with python to achieve a candle chart, words not much to say, directly on the code:


# Import required packages and modules
import datetime

import pandas as pd
import tushare as ts # This module is an API that provides stock trading data for free


# We'll look at stock prices for the past year starting January 1, 2016
Start = Datetime.date (2016,1,1)
End = Datetime.date.today ()



# Get the stock data of the National Gold Securities Company; The stock code is 600109.
# The first parameter is the stock code string that gets the stock data, the second argument is the start date, the third argument is the end date
Guojin = Ts.get_h_data (' 600109 ', str (start), str (end), ' QFQ ')
Type (Guojin)
Guojin.head ()



Get stock data as follows:





# Visualization of stock data import matplotlib as Mlpimport matplotlib.pyplot as Plt%matplotlib Inline%pylab inline

mlp.rcparams[' figure.figsize ' = (15,9)
guojin[' Close '].plot (grid=true)


Get the trend of the closing price of the National Gold Securities in 2015-2016:





# Import required modules for drawing candlesticks
from matplotlib.dates import DateFormatter
from matplotlib.dates import WeekdayLocator
from matplotlib.dates import MONDAY
from matplotlib.dates import DayLocator
from matplotlib.finance import candlestick_ohlc

# Define drawing function
def pandas_candlestick_ohlc (dat, stick = ‘day’, otherseries = None):
    "" "
    Parameter dat: pandas DataFrame object uses datetime64 exponent, and floating-point number series
    "Open price", "High price", "Close price", "Low price"
    Parameter stick: A string or number is just a period of time covering a single wax stick. effective
    Local string input includes "day", "week", "month", "year" (default is day)
    And any number input that indicates the trading day included in the period
    Parameters otherseries: an iterable that will be coerced to a list containing dat packages
    Columns containing other series will be acknowledged as lines
    This will display a Japanese candlestick chart of stock data stored in dat
    "" "
    mondays = WeekdayLocator (MONDAY) # major ticks every Monday
    alldays = DayLocator () # minor this tick every Sunday
    dayFormatter = DateFormatter ("% d")
    
    # Create a new DataFrame containing the OHLC data for each phase specified by color call-in
    transdat = dat.loc [:, ["open", "high", "low", "close"]]
    if type (stick) == str:
        if stick == "day":
            plotdat = transdat
            stick = 1
        elif stick in [‘week’, ‘month’, ‘year’]:
            if stick == ‘week’:
                transdat [‘week’] = pd.to_datetime (transdat.index) .map (
                    lambda x: x.isocalendar () [1]) #determine week
            elif stick == ‘month’:
                transdat [‘month’] = pd.to_datetime (transdat.index) .map (
                    lambda x: x.month) # determine the month
            transdat [‘year’] = pd.to_datetime (transdat.index) .map (
                lambda x: x.isocalendar () [0]) # determine the year
            
            # Group by year and other appropriate variables
            grouped = transdat.groupby (list (set ([‘year‘, stick])))
            
            # Create an empty data frame that will contain the drawing
            plotdat = pd.DataFrame ({"open": [], "high": [], "low": [], "close": []})
            for name, group in grouped:
                plotdat = plotdat.append (pd.DataFrame ({"open": group.iloc [0,0],
                                                     "high": max (group.high),
                                                     "low": min (group.low),
                                                     "close": group.iloc [-1,3]},
                                                     index = [group.index [0]]))
            if stick == "weed":
                stick = 5
            elif stick == "month":
                stick = 30
            elif stick == "year":
                stick = 365
    elif type (stick) == int and stick> = 1:
        transdat ["stick"] = [np.float (i / stick) for i in range (len (transdat.index))]
        grouped = transdat.groupby ("stick")

        # Create an empty data frame that will contain the drawing
        plotdat = pd.DataFrame ({"open": [], "high": [], "low": [], "close": []})
        grouped = transdat.groupby (‘stick‘)
        for name, group in grouped:
            plotdat = plotdat.append (pd.DataFrame ({"open": group.iloc [0,0],
                                                  "high": max (group.high),
                                                  "low": min (group.low),
                                                  "close": group.iloc [-1,3]},
                                                 index = [group.index [0]]))
    else:
        raise ValueError (‘Valid inputs to argument" stick "include the strings" day "," week "," month "," year ", or a positive integer‘)

    # Set the plot parameters, including using the drawn axis object ax
    fig, ax = plt.subplots ()
    fig.subplots_adjust (bottom = 0.2)
    if plotdat.index [-1]-plotdat.index [0] <pd.Timedelta (‘730 days’):
        weekFormatter = DateFormatter ("% b% d") # For example, January 12
        ax.xaxis.set_major_locator (mondays)
        ax.xaxis.set_minor_locator (alldays)
    else:
        weekFormatter = DateFormatter ("% b% d,% Y")
    ax.xaxis.set_major_formatter (weekFormatter)
    ax.grid (True)

    # Create a bar chart
    candlestick_ohlc (ax, list (zip (list (date2num (plotdat.index.tolist ())),
                                 plotdat ["open"]. tolist (),
                                 plotdat ["high"]. tolist (),
                                 plotdat ["low"]. tolist (),
                                 plotdat ["close"]. tolist ())),
                     colorup = "black", colordown = ‘red’)

    # Draw other series (such as moving averages) as lines
    if otherseries! = None:
        if type (otherseries)! = list:
            otherseries = [otherseries]
        dat.loc [:, otherseries] .plot (ax = ax, lw = 1.3, grid = True)

    ax.xaxis_date ()
    ax.autoscale_view ()
    plt.setp (plt.gca (). get_xticklabels (), rotation = 45,
            horizontalalignment = ‘right’)
    plt.show () 


The function is called below to output the result:


PANDAS_CANDLESTICK_OHLC (Guojin)





The graph looks similar to the commercial trading software display, but there are still some problems, such as the open date candlestick is not continuous, can not be scaled, etc., continue to improve later.



Use Python for stock market data analysis-do candlestick chart


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.