mplfinance, you can use the following command in your command-line interface (such as
pip install mplfinance
And since we'll load data from yahoo finance, we need the
pip install yfinance
import mplfinance as mpf import yfinance as yf
Candlestick charts are mainly used to represent financial data, especially stock prices.
In this post, we'll load Apple's share price data, directly from our Python code via the
yfinance library. All we need to do is define the desired start and end data (
yyyy-mm-dd format), and the ticker or symbol associated with this company (in this case
Our dataset must have the characteristics needed to produce our graph easily:
- be a pandas dataframe
- a date index
- an Open column
- a High column
- a Low column
- a Close column
The tickers can be found on easily on yahoo finance.
According to the documentation of mplfinance: "Non-trading days are simply not shown", by default.
# Define the stock symbol and date range stock_symbol = "AAPL" # Example: Apple Inc. start_date = "2022-01-01" end_date = "2022-03-30" # Load historical data stock_data = yf.download(stock_symbol, start=start_date, end=end_date)
[*********************100%***********************] 1 of 1 completed
Candlestick with a moving average
Once we've opened our dataset, we'll now create the graph.
Finally, if our dataset has the properties listed above, we simply call mplfinance's
Then, we just have to
type='candle'in order to display candles
mav=3(with 3 the moving average you want: the higher it is, the smoother the curve will be).
mpf.plot(stock_data, type='candle', mav=3)
Candlestick with several moving averages
In order to represent several moving averages at the same time, simply set a list of integer values as the argument to
# Define the moving averages you want moving_averages = [5,10,15] # Create and display the plot mpf.plot(stock_data, type='candle', mav=moving_averages)