Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Plotting Stock Charts in MATLAB using Python’s yfinance

1 min read

This tutorial explains how to fetch and visualize stock price data from Yahoo Finance using MATLAB. We use Python’s yfinance library from within MATLAB to avoid the need for expensive toolboxes or data subscriptions.

What You’ll Learn

  • How to set up MATLAB to work with Python
  • How to fetch Indian stock data using yfinance
  • How to plot closing prices or other fields using simple MATLAB scripts

Prerequisites

  • MATLAB installed (R2019b or later is recommended) in my case i used Matlab R2024b
  • Python 3.8 to 3.13+ installed on your system
  • The yfinance Python package installed
  • Basic knowledge of MATLAB scripting

Step 1: Install MATLAB (Select Required Components)

During installation:

  • Select only “MATLAB” (core component)
  • You do not need Simulink or engineering toolboxes
  • Optional toolboxes for quant work:
    • Financial Toolbox
    • Statistics and Machine Learning Toolbox

Step 2: Install Python and yfinance

Install Python from https://www.python.org or use Anaconda.

Then open Command Prompt and run:

pip install yfinance

This installs the yfinance package used to access Yahoo Finance data.


Step 3: Check Python Integration

MATLAB usually detects your Python installation automatically. Just run:

pyenv

If it shows a valid Python path and status is either Loaded or NotLoaded, you’re good.

<br>

Test the integration with:

py.importlib.import_module('yfinance')

If no error is returned, you are good to proceed.


Step 4: Create and Run the Data Script

Save the following as datafeed_test.m and run it from the MATLAB editor.

symbols   = {'RELIANCE.NS'};      
startDate = '2024-01-01';
endDate   = '2025-05-05';
field     = 'Close';

py.importlib.import_module('yfinance');  

if numel(symbols)==1
    hist = py.yfinance.Ticker(symbols{1}).history( ...
             pyargs('start',startDate,'end',endDate));
else
    hist = py.yfinance.download(py.list(symbols), ...
             pyargs('start',startDate,'end',endDate));
end

idx = hist.index;
py_strs = cell(py.list(idx.strftime('%Y-%m-%d')));
date_strings = cellfun(@char, py_strs, 'UniformOutput', false);
dates = datetime(date_strings, 'InputFormat', 'yyyy-MM-dd');

figure; hold on;
for s = 1:numel(symbols)
    if hist.columns.nlevels == 1
        series = hist.get(field);
    else
        series = hist.get(py.tuple({symbols{s},field}));
    end
    plot(dates, double(series.values), 'LineWidth',1.8);
end
hold off; grid on;
title(sprintf('%s – %s', strjoin(symbols,', '), field));
xlabel('Date'); ylabel('Price');
legend(arrayfun(@(i) sprintf('%s-%s',symbols{i},field),1:numel(symbols), ...
       'UniformOutput',false), 'Location','best');

Notes

  • Use .NS for NSE stocks (e.g., RELIANCE.NS, INFY.NS)
  • for Nifty index use ^NSEI and for US market S&P500 use ^GSPC
  • You can use 'Open', 'High', 'Low', 'Close', 'Adj Close', or 'Volume' for the field
  • For multiple tickers, use {'RELIANCE.NS', 'TCS.NS'}

MATLAB has always been close to my heart — it was the first vectorized programming language I learned during my college days while studying Digital Signal Processing. That early exposure laid a strong foundation for later mastering Amibroker AFL and TradingView Pine Script, and it made understanding Pandas DataFrames significantly easier.

Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More