
Research
/Security News
Critical Vulnerability in NestJS Devtools: Localhost RCE via Sandbox Escape
A flawed sandbox in @nestjs/devtools-integration lets attackers run code on your machine via CSRF, leading to full Remote Code Execution (RCE).
tvkit is a Python library that fetches real-time stock data from TradingView, including price, market cap, P/E ratio, ROE, and more for stocks from multiple countries. Easily access and analyze financial metrics for global markets.
Modern Python library for TradingView financial data APIs with comprehensive real-time streaming and export capabilities
tvkit is a comprehensive Python library for accessing TradingView's financial data APIs. It provides real-time market data streaming, comprehensive stock analysis, and powerful export capabilities with modern async-first architecture.
Method 1: Using uv (Recommended)
# Install tvkit using uv
uv add tvkit
# Or create a new project with tvkit
uv init my-trading-project
cd my-trading-project
uv add tvkit
Method 2: Using pip with requirements.txt
# Clone the repository
git clone https://github.com/lumduan/tvkit.git
cd tvkit
# Install dependencies
pip install -r requirements.txt
# For development dependencies (optional)
pip install mypy>=1.17.0 ruff>=0.12.4
Method 3: Direct pip installation
# Install from PyPI
pip install tvkit
# Install with all optional dependencies
pip install 'tvkit[dev]'
import asyncio
from tvkit.api.chart.ohlcv import OHLCV
async def stream_bitcoin():
async with OHLCV() as client:
# Stream real-time OHLCV data for Bitcoin
count = 0
async for bar in client.get_ohlcv("BINANCE:BTCUSDT", interval="1"):
count += 1
print(f"Bar {count}: BTC ${bar.close:,.2f} | Volume: {bar.volume:,.0f}")
# Limit demo to 5 bars
if count >= 5:
break
asyncio.run(stream_bitcoin())
Sample Output:
Bar 1: BTC $43,250.50 | Volume: 125,430
Bar 2: BTC $43,275.25 | Volume: 98,750
Bar 3: BTC $43,290.75 | Volume: 156,890
Bar 4: BTC $43,245.00 | Volume: 134,200
Bar 5: BTC $43,267.50 | Volume: 145,600
import asyncio
from tvkit.api.chart.ohlcv import OHLCV
from tvkit.export import DataExporter
from tvkit.api.utils import convert_timestamp_to_iso
async def fetch_and_export_apple_data():
# Fetch historical Apple stock data
async with OHLCV() as client:
bars = await client.get_historical_ohlcv(
"NASDAQ:AAPL",
interval="1D", # Daily bars
bars_count=30 # Last 30 days
)
print(f"📊 Fetched {len(bars)} daily bars for Apple")
print(f"📅 Date range: {convert_timestamp_to_iso(bars[0].timestamp)[:10]} to {convert_timestamp_to_iso(bars[-1].timestamp)[:10]}")
# Show first 3 bars
print("\n🔍 First 3 bars:")
for i, bar in enumerate(bars[:3]):
date = convert_timestamp_to_iso(bar.timestamp)[:10]
print(f" {date}: Open=${bar.open:.2f}, High=${bar.high:.2f}, Low=${bar.low:.2f}, Close=${bar.close:.2f}, Volume={bar.volume:,.0f}")
# Export to multiple formats
exporter = DataExporter()
# Export to Polars DataFrame with technical analysis
df = await exporter.to_polars(bars, add_analysis=True)
print(f"\n📈 DataFrame created: {df.shape[0]} rows × {df.shape[1]} columns")
print(f"Columns: {', '.join(df.columns[:8])}...")
# Export to files
json_path = await exporter.to_json(bars, "./export/apple_data.json", include_metadata=True)
csv_path = await exporter.to_csv(bars, "./export/apple_data.csv", include_metadata=True)
print(f"\n💾 Exported to:")
print(f" JSON: {json_path}")
print(f" CSV: {csv_path}")
return df
asyncio.run(fetch_and_export_apple_data())
Sample Output:
📊 Fetched 30 daily bars for Apple
📅 Date range: 2024-06-15 to 2024-07-15
🔍 First 3 bars:
2024-06-15: Open=$189.25, High=$191.50, Low=$188.75, Close=$190.90, Volume=52,430,200
2024-06-16: Open=$190.85, High=$192.30, Low=$189.40, Close=$191.75, Volume=48,750,150
2024-06-17: Open=$191.80, High=$193.20, Low=$190.95, Close=$192.45, Volume=55,890,300
📈 DataFrame created: 30 rows × 12 columns
Columns: timestamp, open, high, low, close, volume, sma_20, sma_50...
💾 Exported to:
JSON: ./export/apple_data.json
CSV: ./export/apple_data.csv
tvkit is built with three main components:
tvkit.api.chart
)from tvkit.api.chart.ohlcv import OHLCV
# Stream multiple symbols
async with OHLCV() as client:
symbols = ["BINANCE:BTCUSDT", "NASDAQ:AAPL", "FOREX:EURUSD"]
async for info in client.get_latest_trade_info(symbols):
print(f"Trade info: {info}")
import asyncio
from tvkit.api.scanner import ScannerService, Market, MarketRegion
from tvkit.api.scanner import create_comprehensive_request, ColumnSets, get_markets_by_region
async def scan_asian_markets():
service = ScannerService()
# Create comprehensive request for top stocks by market cap
request = create_comprehensive_request(
sort_by="market_cap_basic",
sort_order="desc",
range_end=5 # Top 5 stocks per market
)
# Scan specific Asian markets
markets_to_scan = [Market.THAILAND, Market.JAPAN, Market.SINGAPORE]
print("🌏 Scanning Asian Markets for Top Stocks by Market Cap")
print("=" * 60)
for market in markets_to_scan:
print(f"\n📊 Scanning {market.value.title()} market...")
response = await service.scan_market(market, request)
print(f"✅ Found {len(response.data)} stocks")
if response.data:
top_stock = response.data[0] # Market leader
print(f"\n🏆 Market Leader:")
print(f" Symbol: {top_stock.name}")
print(f" Price: {top_stock.close} {top_stock.currency}")
if top_stock.market_cap_basic:
print(f" Market Cap: ${top_stock.market_cap_basic:,.0f}")
if top_stock.price_earnings_ttm:
print(f" P/E Ratio: {top_stock.price_earnings_ttm:.2f}")
print(f" Sector: {top_stock.sector or 'N/A'}")
# Regional analysis
print(f"\n🌍 Regional Analysis - Asia Pacific Markets:")
asia_markets = get_markets_by_region(MarketRegion.ASIA_PACIFIC)
print(f"Total Asia Pacific markets available: {len(asia_markets)}")
return response.data
asyncio.run(scan_asian_markets())
Sample Output:
🌏 Scanning Asian Markets for Top Stocks by Market Cap
============================================================
📊 Scanning Thailand market...
✅ Found 5 stocks
🏆 Market Leader:
Symbol: PTT
Price: 38.50 THB
Market Cap: $25,340,000,000
P/E Ratio: 12.45
Sector: Energy
📊 Scanning Japan market...
✅ Found 5 stocks
🏆 Market Leader:
Symbol: 7203
Price: 2,845.50 JPY
Market Cap: $185,200,000,000
P/E Ratio: 8.92
Sector: Consumer Cyclical
📊 Scanning Singapore market...
✅ Found 5 stocks
🏆 Market Leader:
Symbol: D05
Price: 31.82 SGD
Market Cap: $95,750,000,000
P/E Ratio: 13.21
Sector: Financial Services
🌍 Regional Analysis - Asia Pacific Markets:
Total Asia Pacific markets available: 17
tvkit.export
)from tvkit.export import DataExporter, ExportConfig, ExportFormat
# Advanced export configuration
config = ExportConfig(
format=ExportFormat.CSV,
timestamp_format="iso",
include_metadata=True,
options={"delimiter": ";", "include_headers": True}
)
exporter = DataExporter()
result = await exporter.export_ohlcv_data(bars, ExportFormat.CSV, config=config)
Category | Column Sets | Examples |
---|---|---|
Price Data | BASIC , TECHNICAL | Current price, change, volume, market cap, high/low/open |
Valuation Ratios | VALUATION , FUNDAMENTALS | P/E ratio, P/B ratio, EV/Revenue, PEG ratio, Price/Sales |
Profitability | PROFITABILITY , COMPREHENSIVE | ROE, ROA, gross/operating/net margins, EBITDA |
Financial Health | FINANCIAL_STRENGTH | Debt/equity, current ratio, quick ratio, free cash flow |
Dividends | DIVIDENDS , FUNDAMENTALS | Current yield, payout ratio, growth rate, continuous growth |
Performance | PERFORMANCE , DETAILED | YTD, 1M, 3M, 6M, 1Y, 5Y, 10Y returns, volatility metrics |
Technical Indicators | TECHNICAL_INDICATORS | RSI, MACD, Stochastic, CCI, momentum, recommendations |
Cash Flow | CASH_FLOW , COMPREHENSIVE_FULL | Operating/investing/financing activities, free cash flow margin |
Balance Sheet | FINANCIAL_STRENGTH , COMPREHENSIVE_FULL | Total assets/liabilities, debt ratios, cash positions |
Region | Markets | Examples |
---|---|---|
North America | 2 markets | USA (NASDAQ, NYSE), Canada (TSX, TSXV) |
Europe | 30 markets | Germany, France, UK, Netherlands, Switzerland, Italy |
Asia Pacific | 17 markets | Japan, Thailand, Singapore, Korea, Australia, India, China |
Middle East & Africa | 12 markets | UAE, Saudi Arabia, Israel, South Africa |
Latin America | 7 markets | Brazil, Mexico, Argentina, Chile, Colombia |
import asyncio
from tvkit.api.scanner import ScannerService, Market, MarketRegion
from tvkit.api.scanner import create_comprehensive_request, get_markets_by_region
async def comprehensive_market_analysis():
service = ScannerService()
# Create comprehensive request with all financial metrics
request = create_comprehensive_request(
sort_by="market_cap_basic",
sort_order="desc",
range_end=10 # Top 10 stocks per market
)
# Regional analysis - scan all Asia Pacific markets
asia_pacific_markets = get_markets_by_region(MarketRegion.ASIA_PACIFIC)
market_leaders = {}
for market in asia_pacific_markets[:6]: # Top 6 Asian markets
try:
response = await service.scan_market(market, request)
if response.data:
top_stock = response.data[0] # Market leader by market cap
market_leaders[market.value] = {
'symbol': top_stock.name,
'price': f"{top_stock.close} {top_stock.currency}",
'market_cap': f"${top_stock.market_cap_basic:,.0f}" if top_stock.market_cap_basic else "N/A",
'pe_ratio': f"{top_stock.price_earnings_ttm:.2f}" if top_stock.price_earnings_ttm else "N/A",
'sector': top_stock.sector or "N/A"
}
except Exception as e:
print(f"Error scanning {market.value}: {e}")
# Display market leaders
for market, data in market_leaders.items():
print(f"{market.title()}: {data['symbol']} - {data['price']} "
f"(Market Cap: {data['market_cap']}, P/E: {data['pe_ratio']})")
# Run analysis
asyncio.run(comprehensive_market_analysis())
import polars as pl
from tvkit.export import DataExporter
# Get data and convert to Polars DataFrame
exporter = DataExporter()
df = await exporter.to_polars(ohlcv_bars, add_analysis=True)
# Advanced analysis with Polars
analysis_df = df.with_columns([
# Bollinger Bands
(pl.col("sma_20") + 2 * pl.col("close").rolling_std(20)).alias("bb_upper"),
(pl.col("sma_20") - 2 * pl.col("close").rolling_std(20)).alias("bb_lower"),
# Volume analysis
(pl.col("volume") / pl.col("volume").rolling_mean(10)).alias("volume_ratio"),
# Price momentum
(pl.col("close") - pl.col("close").shift(5)).alias("momentum_5"),
])
# Export enhanced analysis
analysis_df.write_parquet("enhanced_analysis.parquet")
import asyncio
from tvkit.api.chart.ohlcv import OHLCV
async def robust_streaming():
max_retries = 3
retry_count = 0
while retry_count < max_retries:
try:
async with OHLCV() as client:
async for bar in client.get_ohlcv("BINANCE:BTCUSDT"):
print(f"Price: ${bar.close}")
except Exception as e:
retry_count += 1
wait_time = 2 ** retry_count # Exponential backoff
print(f"Error: {e}. Retrying in {wait_time}s...")
await asyncio.sleep(wait_time)
else:
break
async def monitor_portfolio():
symbols = [
"BINANCE:BTCUSDT", # Cryptocurrency
"NASDAQ:AAPL", # US Stock
"FOREX:EURUSD", # Forex
"OANDA:XAUUSD" # Commodities (Gold)
]
async with OHLCV() as client:
async for trade_info in client.get_latest_trade_info(symbols):
# Process multi-asset trade information
print(f"Portfolio update: {trade_info}")
tvkit uses modern, high-performance libraries:
Install and test tvkit in under 2 minutes:
# Method 1: Using uv (fastest)
uv init my-trading-app && cd my-trading-app
uv add tvkit
uv run python -c "import tvkit; print('✅ tvkit installed successfully!')"
# Method 2: Using pip
pip install tvkit
python -c "import tvkit; print('✅ tvkit installed successfully!')"
Create first_script.py
and run it:
#!/usr/bin/env python3
import asyncio
from tvkit.api.chart.ohlcv import OHLCV
async def my_first_trading_data():
async with OHLCV() as client:
# Get Apple's latest price
bars = await client.get_historical_ohlcv("NASDAQ:AAPL", "1D", 1)
latest = bars[0]
print(f"🍎 Apple (AAPL): ${latest.close:.2f}")
# Get Bitcoin's latest price
bars = await client.get_historical_ohlcv("BINANCE:BTCUSDT", "1D", 1)
latest = bars[0]
print(f"💰 Bitcoin: ${latest.close:,.2f}")
if __name__ == "__main__":
asyncio.run(my_first_trading_data())
Run it:
# With uv
uv run python first_script.py
# With pip
python first_script.py
Expected output:
🍎 Apple (AAPL): $192.75
💰 Bitcoin: $43,267.50
For Contributors:
# Clone and setup development environment
git clone https://github.com/lumduan/tvkit.git
cd tvkit
# Using uv (recommended)
uv sync
uv run ruff check . && uv run ruff format . && uv run mypy tvkit/
uv run python -m pytest tests/ -v --cov=tvkit
# Using pip
pip install -r requirements.txt
pip install mypy ruff pytest pytest-asyncio pytest-cov
ruff check . && ruff format . && mypy tvkit/
python -m pytest tests/ -v --cov=tvkit
# Comprehensive historical and real-time data demo
uv run python examples/historical_and_realtime_data.py
# ⏱️ Runtime: ~2-3 minutes | 📋 Features: OHLCV, exports, multi-symbol, streaming
# Global market scanner with 69 markets
uv run python examples/multi_market_scanner_example.py
# ⏱️ Runtime: ~1-2 minutes | 📋 Features: Regional analysis, 101+ metrics
# Multiple export formats demo
uv run python examples/export_demo.py
# ⏱️ Runtime: ~30 seconds | 📋 Features: Polars, JSON, CSV, Parquet
We welcome contributions! Please see our contributing guidelines:
Fork the repository
Create a feature branch
Add tests for new functionality
Ensure all quality checks pass:
# With uv
uv run ruff check . && uv run ruff format . && uv run mypy tvkit/
uv run python -m pytest tests/ -v
# Or with pip
ruff check . && ruff format . && mypy tvkit/
python -m pytest tests/ -v
Submit a pull request
This project is licensed under the MIT License - see the LICENSE file for details.
If you find tvkit useful, please consider giving it a star on GitHub! Your support helps us continue developing and improving the library.
tvkit is designed for production use:
Operation | Performance | Notes |
---|---|---|
Historical Data Fetch | ~100-500ms | Per symbol, 100 bars |
Market Scanner Query | ~200-800ms | Per market, 50 stocks |
Real-time Streaming | <50ms latency | Per update |
Polars DataFrame Export | ~10-50ms | 1000 bars with analysis |
JSON/CSV Export | ~20-100ms | 1000 bars with metadata |
Ready to get started? 🚀 Choose your installation method above and run your first script!
Built with ❤️ for the financial data community
FAQs
tvkit is a Python library that fetches real-time stock data from TradingView, including price, market cap, P/E ratio, ROE, and more for stocks from multiple countries. Easily access and analyze financial metrics for global markets.
We found that tvkit demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
/Security News
A flawed sandbox in @nestjs/devtools-integration lets attackers run code on your machine via CSRF, leading to full Remote Code Execution (RCE).
Product
Customize license detection with Socket’s new license overlays: gain control, reduce noise, and handle edge cases with precision.
Product
Socket now supports Rust and Cargo, offering package search for all users and experimental SBOM generation for enterprise projects.