In one of the past tutorials, we learned how to import data from NSEindia using NSEpy library and how to compute co-integration.
In this tutorial, we use the nsepy library to get historical data for the RELIANCE stock from the National Stock Exchange (NSE) in India. The data is then used to create a candlestick chart using the matplotlib library. Also, yfinance to plot the candle data with volume using mplfinance library and plot the drawdown below the line charts
Installing Libraries using pip command
pip install nsepy
pip install mplfinance
pip install matplotlib
pip install pandas
Python Code for Plotting Candle Stick Charts
import nsepy
from nsepy import get_history
from datetime import date
import matplotlib.pyplot as plt
from mplfinance.original_flavor import candlestick_ohlc
import pandas as pd
import matplotlib.dates as mpl_dates
# Set the start and end dates
start_date = date(2022, 10, 1)
end_date = date(2023, 2, 28)
# Get the historical data for the stock
data = get_history(symbol='RELIANCE', start=start_date, end=end_date)
# Reset the index and convert the date to a column
data = data.reset_index()
data['Date'] = pd.to_datetime(data['Date'])
data['Date'] = data['Date'].apply(mpl_dates.date2num)
# Create a new DataFrame with the necessary columns for the Candlestick chart
ohlc = data[['Date', 'Open', 'High', 'Low', 'Close']].copy()
# Create a subplot
fig, ax = plt.subplots()
# Plot the Candlestick chart
candlestick_ohlc(ax, ohlc.values, width=0.6, colorup='green', colordown='red', alpha=0.8)
# Set the x-axis tick format
date_format = mpl_dates.DateFormatter('%d %b %Y')
ax.xaxis.set_major_formatter(date_format)
fig.autofmt_xdate()
# Set the chart title and axis labels
plt.title('RELIANCE Candlestick Chart')
plt.xlabel('Date')
plt.ylabel('Price')
# Show the chart
plt.show()
Output
Plotting Simple Moving Average on Top of the Charts
ticker = "RELIANCE"
plt.plot(data["Close"], label="Close")
plt.plot(data["Close"].rolling(window=10).mean(), label="10-day Moving Average")
plt.plot(data["Close"].rolling(window=20).mean(), label="20-day Moving Average")
plt.title(f"{ticker} Stock Price")
plt.xlabel("Date")
plt.ylabel("Price")
plt.legend()
plt.show()
Plotting Moving Averages using yfinance and mplfinance library
import yfinance as yf
import mplfinance as mpf
# Set the ticker symbol and timeframe
ticker = "RELIANCE.NS"
start_date = "2021-01-01"
end_date = "2022-02-25"
# Fetch the stock data using yfinance
data = yf.download(ticker, start=start_date, end=end_date)
# Plot a candlestick chart with 10-day SMA and 20-day EMA
mpf.plot(data, type="candle", mav=(10, 20), volume=True)
Plotting Drawdown in Percentage Terms
import yfinance as yf
import matplotlib.pyplot as plt
# Download historical data for the stock
ticker = "RELIANCE.NS"
stock = yf.download(ticker)
# Calculate the drawdown
running_max = stock['Adj Close'].cummax()
drawdown = (stock['Adj Close'] - running_max) / running_max *100
# Create a figure with two subplots
fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True, figsize=(12, 8))
# Plot the stock price on the first subplot
ax1.plot(stock.index, stock['Adj Close'], label='Price')
# Plot the drawdown on the second subplot
ax2.fill_between(drawdown.index, drawdown, 0, alpha=0.3)
ax2.set_ylim(-100, 0)
ax2.set_ylabel('Drawdown (%)')
# Add a title and legend
plt.suptitle(f"{ticker} Stock Price and Drawdown")
ax1.legend()
# Show the chart
plt.show()
how to catch sudden spike / spurts in puts/calls in nse data using python