In this tutorial, we would understand how to write a simple python script to plot live stock chart. In the previous tutorials, we have fetched data using Google API, but as a matter of fact Google has recently deprecated it’s API. Also, Yahoo finance API is no longer in use. In order to fetch stock data, we would use Alpha Vantage API in this script. This API is free to use, and can fetch real-time and historical data from all popular exchanges in the world. Check the API documentation here.
Check out all the Python related tutorials in the below link:
Algorithmic Trading using Python
Prerequisites
Generate API key from Alpha Vantage website using below link:
https://www.alphavantage.co/support/#api-key
Once the API key is generated, open command prompt and copy past the below commands (one by one) to install alpha_vantage and matplotlib modules:
pip install alpha_vantage pip install matplotlib
Python Script to plot Live Stock Chart
from alpha_vantage.timeseries import TimeSeries import matplotlib.pyplot as plt import sys def stockchart(symbol): ts = TimeSeries(key='your_key', output_format='pandas') data, meta_data = ts.get_intraday(symbol=symbol,interval='1min', outputsize='full') print data data['close'].plot() plt.title('Stock chart') plt.show() symbol=raw_input("Enter symbol name:") stockchart(symbol)
Here is the output of this script when executed from PyCharm:
At the bottom left of the output screen you can see the options to zoom-in and zoom-out, and scroll through the chart.
Now, let’s understand the code logic and see how it works
The first few import statements are to use the modules we installed in previous step. Next, there is a function where we fetch the intraday data for the symbol entered. Please note that we have use the API key value from Alpha Vantage. Finally the line chart is plotted using the ‘close’ values in the time series. Similarly you can also plot open, high , low and volume data.
You can explore the Alpha Vantage API documentation, and there are literally lot many features you can make use of. The best thing is that the API usage is free of cost, which is hard to find anywhere else. Let us know in comments section if you have any queries.
Thanks a ton, very useful!
hi sir not able to launch chart . i am stuck after installing matplotlib
Hi Rahul,
Can you let me know what is the exact error you are facing?
How to execute the script from pycharm.
I installed anaconda as pip was not working for installing jupyter. I installed matplotlib in cmd and save script as.py in anaconda folder then I run command python script.py then nothing work
very helpfull for beginer ,great job ….
how do we get symbol for Indian stocks
You can try NSE and BSE website for symbol codes
Admin sir, Namaskar pls advice 1. how can we learn fractals for long term investing, pls advice some books and courses 2.which software supports this technology 3 can it be used on amibroker which we are using for sometime. thanks n Regards
Dear Admin,
Can i get NSE and MCX Real Time Data from this API? If yes can you tell me How symbol Name should use to get RT for these symbols.
current month BANKNIFTY from NSE and current month CRUDEOIL from Mcx Exchange. Thankyou .
by this API we are gettting O,H,L,C,V only.
is it possible to get open interest and other parameter
Hi Rahul,
The API is evolving, they should add other parameters soon
sir i m getting error as ::
C:\>pip install alpha_vantage
‘pip’ is not recognized as an internal or external command,
operable program or batch file.
please help me
I think you did not install Python properly, maybe you can try reinstalling it. And when running command prompt, run it in administrator mode.
how do i down load API, i got the KEY
sir i m getting following error in installation
C:\>pip install alpha_vantage
‘pip’ is not recognized as an internal or external command,
operable program or batch file.
please help me
Hi Charusheela,
I think you missed to set the environment variable. Can you please go through the article again
I am trying to install alphavantage library on a conda environment downgraded to py3.5 and it throws exception while installing. TypeError: parse() got an unexpected keyword argument ‘transport_encoding’
I would love to see a tweak in the code:
Instead of data (1 min for intraday), can we have 1 min data for USER SUPPLIED dates??
getting error
Traceback (most recent call last):
File “C:/Users/Admin/AppData/Local/Programs/Python/Python36-32/alpha_vantage.py”, line 1, in
from alpha_vantage.timeseries import TimeSeries
File “C:/Users/Admin/AppData/Local/Programs/Python/Python36-32\alpha_vantage.py”, line 1, in
from alpha_vantage.timeseries import TimeSeries
ModuleNotFoundError: No module named ‘alpha_vantage.timeseries’; ‘alpha_vantage’ is not a package
Hi Bhavesh,
You would need to install AlphaVantage module to use this code
hi mine is printing out the symbol alone with no chart
Hi Jera,
Which version of Python you are in?
I’d love to see this done with 1Forge’s forex tick data!
Not sure if you still read this comments but I was wondering if you can post an example of something like this… current RSI in the 15 min bar and current price. ex. FB 151.22 RSI 65 5 day high 150.22
thanks so much
Thanks, I had to edit the column name:
from data[‘close’] # threw a KeyError exception
to data[‘4. close’] # this worked
Also- the script is python 2 and I am using python 3, so the print statement required parentheses..
This fixed my problem on Windows 10 and Python 3.7
I noticed the 4. and the dot next to it.
NameError: name ‘raw_input’ is not defined
Try changing “raw_input” to a ticker name, for example “MSFT”
To get the code working change data[‘close’].plot() to data[‘4. close’].plot().
Also, change symbol=raw_input(“Enter symbol name:”) to symbol=input(‘Enter symbol name:’).
Change data[‘close’].plot() to data[‘4. close’].plot() and change symbol=raw_input(“Enter symbol name:”) to symbol=input(‘Enter symbol name:’) to get the code working.
import pandas as pd
from alpha_vantage.timeseries import TimeSeries
import time
api_key = “XXXXXXXXXXXXXXX”
ts = TimeSeries(key=api_key, output_format=’pandas’)
data, meta_data = ts.get_intraday(symbol=”NSE:SBIN”, interval = ‘1min’, outputsize = ‘full’)
print(data)
I have done a lot of searching. I know some Python but I am definitely not a developer. I simply want to do exactly what you have done above, produce a daily intraday graph for a stock or stocks. Yours is by far the easiest code I have come across. If you could assist with this error I would appreciate it!
I am getting a key error. I went to Alpha Vantage and generated a key. I put that in your script. It generates the rows and columns but then I get the following key error:
Traceback (most recent call last):
File “C:\Users\David3\AppData\Roaming\Python\Python37\site-packages\pandas\core\indexes\base.py”, line 3361, in get_loc
return self._engine.get_loc(casted_key)
File “pandas\_libs\index.pyx”, line 76, in pandas._libs.index.IndexEngine.get_loc
File “pandas\_libs\index.pyx”, line 108, in pandas._libs.index.IndexEngine.get_loc
File “pandas\_libs\hashtable_class_helper.pxi”, line 5198, in pandas._libs.hashtable.PyObjectHashTable.get_item
File “pandas\_libs\hashtable_class_helper.pxi”, line 5206, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: ‘close’
Thank you.
The above exception was the direct cause of the following exception: