Replicating_Tradingview_chart_in_python
Replicating_Tradingview_chart_in_python
com/replicating-tradingview-chart-in-python-8bb6ff00bb4e
Search Medium
Write
Get unlimited access to the best of Medium for less than $1/week.
Become a member
Image by Author
Follow
Published in
Level Up Coding
9 min read
Aug 2
350
5
Importing Packages
The first and foremost step of setting up the coding
environment is to import the required packages. In this
article, we are going to use five different packages which
are pandas for data manipulation, and requests for making
API calls, numpy for numerical
calculations, lightweight_chart for replicating the
TradingView look, time for time-related functions, and
finally asyncio and nest_asyncio for asynchronous
programming. The following code will import all the
mentioned packages into our Python environment:
import pandas as pd
import requests
import numpy as np
from lightweight_charts import Chart
import time
import asyncio
import nest_asyncio
nest_asyncio.apply()
If you haven’t installed any of the imported packages,
make sure to do so using the pip command in your
terminal. Before moving further, for extracting the data,
we’ll be using the APIs of FinancialModelingPrep. So for
the smooth execution of the upcoming code block, you
need to have an FMP developer account which you can
easily create using the link here.
hist_df.tail()
In the above code, we are first storing the secret API key in
a variable (remember to replace YOUR API KEY with your
actual secret key), and then, using the get provided by the
Requests package, we are extracting the historical data of
Apple. We are then converting the JSON response into a
Pandas dataframe, and after performing some data
manipulation, this is the final output:
Image by Author
TradingView Charts
In this section, we are going to dive deep into
the lightweight_charts module and explore the exciting
possibilities. Let’s start off with a basic graph in the style
of TradingView. Here’s the code to generate a
TradingView graph using the library:
chart = Chart()
chart.set(hist_df)
chart.show(block = False)
chart = Chart()
chart.candle_style(up_color='#2962ff', down_color='#e91e63',
border_up_color='#2962ffcb',
border_down_color='#e91e63cb',
wick_up_color='#2962ffcb', wick_down_color='#e91e63cb')
chart.volume_config(up_color='#2962ffcb', down_color='#e91e63cb')
chart.title('AAPL')
chart.legend(visible = True, font_family = 'Trebuchet MS', ohlc = True,
percent = True)
##########################################################################
###########
chart.set(hist_df)
chart.show(block = False)
rt_chart = Chart()
rt_chart.set(rt_df1)
rt_chart.show(block = False)
Pretty cool, right?! But like how there was a lot of scope
for improvements in the basic historical graph, this real-
time chart can also be improved and modified in a lot of
places. We can first change the theme of the plot and
similar to how we added SMA lines to the historical chart
for better insights, we can add more details for an
informative visualization. Here’s the code for the modified
or advanced version of the initial real-time chart:
hist_df['SMA9'] = hist_df.close.rolling(window = 9).mean()
hist_df['SMA12'] = hist_df.close.rolling(window = 12).mean()
hist_df = hist_df.dropna()
rt_df1 = hist_df[:25]
rt_df2 = hist_df[25:]
rt_chart = Chart()
rt_chart.candle_style(up_color='#2962ff', down_color='#e91e63',
border_up_color='#2962ffcb',
border_down_color='#e91e63cb',
wick_up_color='#2962ffcb', wick_down_color='#e91e63cb')
rt_chart.volume_config(up_color='#2962ffcb', down_color='#e91e63cb')
##########################################################################
###########
rt_chart.set(rt_df1)
rt_chart.show(block = False)
time.sleep(0.1)
def fetch_data(symbol):
api_key = 'YOUR API KEY'
hist_json =
requests.get(f'https://financialmodelingprep.com/api/v3/historical-price-
full/AAPL?apikey={api_key}').json()
hist_df = pd.DataFrame(hist_json['historical']).drop('label', axis =
1)
hist_df = hist_df.iloc[::-1].reset_index().drop(['index','adjClose'],
axis = 1)
hist_df.date = pd.to_datetime(hist_df.date)
hist_df = hist_df.iloc[:,:6].iloc[-365:]
hist_df.columns = ['time', 'open', 'high', 'low', 'close', 'volume']
return hist_df
class API:
def __init__(self):
self.chart = None
df = fetch_data('AAPL')
chart.set(df)
if __name__ == '__main__':
asyncio.run(main())
Closing Notes
In this article, we explored an interesting library
called lightweight_charts which helps in creating financial
visualizations in the look of TradingView with as less code
as possible. We went from generating a basic historical
graph to real-time and interactive charts and during the
process, we experimented with different components
provided by the library.
Level Up Coding
Thanks for being a part of our community! Before you go:
Technology
Data Science
Python
Programming
Finance
350
5
2.9K Followers
·Writer for
Level Up Coding
in
DataDrivenInvestor
13 min read·May 26
384
12
Sanjay Priyadarshi
in
Level Up Coding
1.1K
10
Prathamesh Gadekar
in
Level Up Coding
Python Libraries for Lazy Data Scientists
Do you feel lethargic today? Use these five libraries to boost your productivity.
7 min read·Apr 8
1.1K
4
Nikhil Adithyan
in
Level Up Coding
227
6 min read·Jul 8
77
4
Constantin Picoron
How I ended up building a quantitative trading algorithm
without a data science degree
For the past 20 month or so, I’ve been building a quantitative trading algorithm in
Python by myself. It’s been quite a journey, and here…
6 min read·Mar 20
Lists
ChatGPT prompts
24 stories·303 saves
Rupe Dodkins
5 min read·Jun 21
chatgpt-writer
3 min read·Jul 24
1
Michael May
10 min read·Apr 23
3
martin vizzolini
in
Coinmonks
How to Beat the Stock Market with Maths: A Dual Strategy
Approach
Is it possible to discover a foolproof winning strategy? What if we could
simultaneously bet on red and black in a casino roulette while…
11 min read·Jul 27
Help
Status
Writers
Blog
Careers
Privacy
Terms
About
Text to speech
Teams