Extracting Data from Trading View

Extracting Data from Trading View

In the world of financial analysis and trading, timely and accurate data is crucial. One of the powerful tools available for accessing financial market data is TVDataFeed, an unofficial Python library for extracting data from TradingView. TradingView is a popular charting platform offering real-time market data, and with TVDataFeed, you can programmatically access this data for analysis, backtesting, and algorithmic trading. In this article, we will explore how to extract data from TVDataFeed and make the most of this resource.

What is TVDataFeed?

TVDataFeed is an open-source Python library that allows users to retrieve historical and real-time market data from TradingView. Although it is not an official TradingView API, it provides a reliable way to access TradingView’s extensive database of financial information.

Getting Started with TVDataFeed

Installation

To start using TVDataFeed, you need to install it. You can do this easily using pip, the Python package installer. Open your terminal or command prompt and run the following command:


pip install git+https://github.com/asimov-academy/Asimov_TV_connector.git        

Authentication

TVDataFeed requires a TradingView account for authentication. You’ll need your TradingView username and password to log in. Here’s how you can set up the authentication:


from datetime import datetime, timedelta
import pandas as pd
from tvDatafeed import TvDatafeed, Interval

## Replace 'your_username' and 'your_password' with TV credentials

username = 'your_username'
password = 'your_password'

tv = TvDatafeed(username, password)        

Extracting Data

Once authenticated, you can start extracting data. TVDataFeed supports various types of data extraction, including historical data, and more. Let’s go through some examples.

Fetching Historical Data

To fetch historical data, you need to specify the symbol, exchange, interval, and the date range. Here’s an example of how to fetch historical data for Petrobras. (PETR4) from the BMFBOVESPA exchange:

df = tv.get_hist(symbol = "PETR4", exchange = 'BMFBOVESPA', 
                 interval= Interval.in_1_minute, n_bars= 5000)

print(df)        


Plotting Data


import mplfinance as mpf

mpf.plot(df.head(100),type='candle',style='yahoo',volume=True)        



Handling Different Intervals

TVDataFeed supports various intervals, ranging from 1-minute bars to monthly bars. You can choose the appropriate interval based on your analysis requirements. Here are some examples:


# 1-minute interval
interval_1m = Interval.in_1_minute

# 5-minute interval
interval_5m = Interval.in_5_minute

# Weekly interval
interval_w = Interval.in_weekly

# Fetching data with different intervals
data_1m = tv.get_hist(symbol=symbol, exchange=exchange, interval=interval_1m, n_bars=500)
data_5m = tv.get_hist(symbol=symbol, exchange=exchange, interval=interval_5m, n_bars=500)
data_w = tv.get_hist(symbol=symbol, exchange=exchange, interval=interval_w, n_bars=500)        

Error Handling and Data Validation

When working with data extraction, it’s essential to handle errors and validate the data to ensure accuracy. TVDataFeed provides mechanisms to handle exceptions and check for data integrity.

try:
    data = tv.get_hist(symbol='ETHEUR', exchange='BINANCE', interval=Interval.in_1_minute, n_bars=500)
    if data.empty:
        raise ValueError("No data returned for the specified parameters.")
except Exception as e:
    print(f"Error fetching data: {e}")        


Exporting Data with TVDataFeed

After extracting data from TradingView using TVDataFeed, you may want to export it for further analysis, sharing, or storage. Exporting data can be done in various formats such as CSV, Excel, or JSON, which are widely used in data analysis and storage. In this section, we will discuss how to export data using Python.

Exporting to CSV

CSV (Comma Separated Values) is a popular format for data exchange. It is simple and can be opened with many applications, including Excel. Here’s how you can export data to a CSV file using pandas, a powerful data manipulation library in Python:

Extract Data

First, extract the data using TVDataFeed as shown in the previous examples.

Export to CSV

Next, use pandas to export the extracted data to a CSV file:


# Define the file path
csv_file_path = 'aapl_data.csv'

# Export data to CSV
data.to_csv(csv_file_path)

print(f"Data exported to {csv_file_path}")        

Exporting to JSON

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy to read and write. It’s widely used for web applications and APIs. Here’s how you can export data to a JSON file:

Export to JSON

Use pandas to export the extracted data to a JSON file:


# Define the file path
json_file_path = 'aapl_data.json'

# Export data to JSON
data.to_json(json_file_path, orient='records', lines=True)

print(f"Data exported to {json_file_path}")        

Conclusion

TVDataFeed is a powerful tool for extracting financial market data from TradingView. With its ability to fetch historical and real-time data, it becomes an indispensable resource for traders, analysts, and researchers. By following this guide, you can start leveraging TVDataFeed to enhance your data-driven decision-making processes in the financial markets.

Remember to use TVDataFeed responsibly and adhere to TradingView’s terms of service. Happy data extracting!














Amit Jain

Managing Principal Consultant at Oracle

6 个月

Thanks for sharing the wonderful article Eurico, I am having tradingview account through google, how can i pass my google credentials.? username = "xyz@gmail.com" password = "abc" tv = TvDatafeed(username, password) Error message : "error while signin"

回复

要查看或添加评论,请登录

Eurico Paes的更多文章

社区洞察

其他会员也浏览了