borsapy Documentation

repository·master·Indexed 20 days ago

https://github.com/saidsurucu/borsapy

A Python library for accessing Turkish financial markets data, providing a yfinance-like API for BIST stocks, forex, crypto, investment funds, and macroeconomic data from the TCMB (EVDS). It includes features for retrieving historical OHLCV data, financial statements, corporate actions, analyst targets, and ETF ownership, as well as a CLI for price queries, technical scanning, and fundamental screening.

Tokens
73.2K
Snippets
279
Records
325
Agent score
70%

What's inside borsapy

  1. Data Sources used by borsapy

    master

    borsapy aggregates data from various financial and economic sources. When using this library, be aware that the data belongs to the following providers:

    • İş Yatırım (isyatirim.com.tr): Financial statements, stock scanning, VIOP.
    • TradingView (tradingview.com): Stock OHLCV, indices, real-time streaming, technical analysis signals, symbol search, ETF ownership.
    • KAP (kap.org.tr): Company announcements, ownership structure.
    • TCMB (tcmb.gov.tr): Inflation data, central bank interest rates.
    • BtcTurk: Cryptocurrency data.
    • TEFAS (tefas.gov.tr): Investment fund data.
    • doviz.com: Exchange rates, bank rates, economic calendar, bond yields.
    • canlidoviz.com: Exchange rates, commodity prices.
    • Ziraat Bankası (ziraatbank.com.tr): Eurobond data.
    • hedeffiyat.com.tr: Analyst target prices.
    • isinturkiye.com.tr: ISIN codes.
    • Twitter/X (x.com): Tweet data (accessed via the Scweet library, requires optional dependency).

    Disclaimer: This library is intended for personal use only. Data retrieved through this library must not be used for commercial purposes.

  2. Work with Investment and Pension Funds

    master

    Use the bp.Fund class to access data for TEFAS investment funds (YAT) and pension funds (EMK). The library automatically detects the fund type if not specified, attempting YAT first and then EMK.

    import borsapy as bp
    
    # Search for funds
    print(bp.search_funds("banka"))
    
    # Investment Fund (YAT) - default
    fon = bp.Fund("AAK")
    
    # Pension Fund (EMK) - explicit
    emk = bp.Fund("KJM", fund_type="EMK")
    
    # Auto-detection
    emk = bp.Fund("KJM") # Automatically detected as EMK
  3. Important: EVDS Frequency-Start-Day Rule

    master

    To ensure the requested frequency is displayed correctly, you must provide the first day of the relevant period as the start date.

    • Annual (annual): Use start="2005-01-01" to include 2005. Using 2005-01-02 will skip 2005 and start from 2006.
    • Monthly (monthly): Use start="2025-04-01" for April 2025. Using 2025-04-15 will start from May 2025.
    • Quarterly (quarterly): Use the first day of the quarter (e.g., 2025-04-01 for Q2).
  4. How Supertrend works and how to use it

    master

    Supertrend is an ATR-based trend-following indicator. It returns a dictionary containing the trend value, direction, and bands.

    Interpretation:

    • direction == 1: Bullish trend (price is above Supertrend).
    • direction == -1: Bearish trend (price is below Supertrend).
    • A trend change occurs when the direction value flips sign.

    Parameters:

    • atr_period: Period for ATR calculation.
    • multiplier: Multiplier for the ATR band.
    import borsapy as bp
    
    hisse = bp.Ticker("THYAO")
    
    # Get latest Supertrend values
    st = hisse.supertrend(atr_period=7, multiplier=2.0)
    print(st['value'])      # Supertrend line value
    print(st['direction']) # 1 (bullish) or -1 (bearish)
    print(st['upper'])     # Upper band
    print(st['lower'])     # Lower band
  5. Manage multi-asset portfolios with Portfolio

    master

    The Portfolio class allows you to manage multi-asset portfolios, track performance, and calculate risk metrics. You can add various asset types including stocks, FX (commodities/currencies), crypto, and investment funds.

    Supported asset types:

    • stock: Default (e.g., THYAO, GARAN).
    • fx: Requires asset_type="fx" (e.g., USD, gram-altin, BRENT).
    • crypto: Auto-detected if following the *TRY pattern (e.g., BTCTRY).
    • fund: Requires asset_type="fund" (e.g., YAY).

    Note: Indices like XU100 or XU030 cannot be added as assets; they must be used as a benchmark via set_benchmark().

    import borsapy as bp
    
    portfolio = bp.Portfolio()
    portfolio.add("THYAO", shares=100, cost=280.0)          # Stock
    portfolio.add("gram-altin", shares=10, asset_type="fx")  # FX/Commodity
    portfolio.add("BTCTRY", shares=0.5)                      # Crypto (auto-detected)
    portfolio.add("YAY", shares=1000, asset_type="fund")    # Fund
    portfolio.set_benchmark("XU100")
  6. How Tilson T3 works

    master

    Tilson T3 is a triple-smoothed EMA designed for low-lag moving averages.

    Parameters:

    • period: The T3 period (default is 5).
    • vfactor: Volume factor.
      • 0.5: More responsive (faster reaction).
      • 0.7: Recommended value.
      • 0.9: Smoother (less noise).
    import borsapy as bp
    
    hisse = bp.Ticker("THYAO")
    
    # Get latest T3 value
    t3 = hisse.tilson_t3(t3_period=8, vfactor=0.7)
  7. Use Replay Mode for backtesting

    master

    Replay Mode allows you to play back historical data candle-by-candle, simulating a live market environment for testing trading logic.

    import borsapy as bp
    
    # Create a replay session (e.g., last 6 months, 5x speed)
    session = bp.create_replay("THYAO", period="6mo", speed=5.0)
    
    # Iterate through candles
    for candle in session.replay():
        print(f"{candle['timestamp']}: Close={candle['close']}")
    
    # Filtered replay by date
    for candle in session.replay_filtered(start_date="2024-01-01", end_date="2024-06-01"):
        pass
    
    # Access session statistics
    print(session.stats())
  8. Perform local indicator scans (Supertrend and Tilson T3)

    master

    Since Supertrend and Tilson T3 are not available in the TradingView Scanner API, borsapy calculates them locally.

    Supported Local Fields:

    • supertrend: The Supertrend value.
    • supertrend_direction: 1 for bullish, -1 for bearish.
    • supertrend_upper: Upper band.
    • supertrend_lower: Lower band.
    • t3 / tilson_t3: Tilson T3 value.
    import borsapy as bp
    
    # Supertrend bullish trend
    bullish = bp.scan("XU030", "supertrend_direction == 1")
    
    # Price above Tilson T3
    above_t3 = bp.scan("XU030", "close > t3")
    
    # Combination: RSI oversold + Supertrend bullish
    combo = bp.scan("XU030", "rsi < 30 and supertrend_direction == 1")
  9. How Heikin Ashi charts are calculated

    master

    Heikin Ashi is an alternative candlestick charting method used to filter out market noise. You can calculate Heikin Ashi candles using calculate_heikin_ashi(df) or the convenience method .heikin_ashi(period="...") on asset objects.

    The resulting DataFrame contains: HA_Open, HA_High, HA_Low, HA_Close, and Volume.

    import borsapy as bp
    
    hisse = bp.Ticker("THYAO")
    
    # Using convenience method
    ha_df = hisse.heikin_ashi(period="1y")
    
    # Using pure function
    df = hisse.history(period="1y")
    ha_df = bp.calculate_heikin_ashi(df)
  10. Quickstart with borsapy CLI

    master

    Use these common commands to quickly access financial data:

    • Price Inquiry: borsapy price <SYMBOL>
    • Historical Data: borsapy history <SYMBOL> --period <PERIOD> --output <FORMAT>
    • Technical Signals: borsapy signals <SYMBOL>
    • Live Monitoring: borsapy watch <SYMBOL1> <SYMBOL2> ...
    # Fiyat sorgula
    borsapy price THYAO
    
    # Geçmiş veriler
    borsapy history THYAO --period 1y --output csv > thyao.csv
    
    # Teknik sinyaller
    borsapy signals THYAO
    
    # Canlı izleme
    borsapy watch THYAO GARAN ASELS
  11. Quickstart with borsapy

    master

    The following examples demonstrate how to access various financial data types using borsapy:

    • Stocks (BIST): Use bp.Ticker("SYMBOL") for individual stocks.
    • Multiple Stocks: Use bp.download(["SYM1", "SYM2"], period="...") for bulk data.
    • Forex (Döviz): Use bp.FX("CURRENCY") (e.g., bp.FX("USD")).
    • Crypto: Use bp.Crypto("SYMBOL") (e.g., bp.Crypto("BTCTRY")).
    • Investment Funds: Use bp.Fund("SYMBOL") (e.g., bp.Fund("AAK")).
    • Inflation: Use bp.Inflation().latest() for recent CPI data.
    • EVDS (TCMB): Use bp.set_evds_key("YOUR_KEY") and then bp.evds_series("SERIES_ID", period="...") to access Turkish Central Bank macro data.
    import borsapy as bp
    
    # Stock data
    hisse = bp.Ticker("THYAO")
    print(hisse.info)                    # Instant price and company info
    print(hisse.history(period="1ay"))   # Historical OHLCV data
    print(hisse.balance_sheet)           # Balance sheet
    
    # Multiple stocks
    data = bp.download(["THYAO", "GARAN", "AKBNK"], period="1ay")
    print(data)
    
    # Forex
    usd = bp.FX("USD")
    print(usd.current)                   # Current rate
    print(usd.history(period="1ay"))     # Historical data
    
    # Crypto
    btc = bp.Crypto("BTCTRY")
    print(btc.current)                   # Current price
    
    # Investment fund
    fon = bp.Fund("AAK")
    print(fon.info)                      # Fund info
    
    # Inflation
    enf = bp.Inflation()
    print(enf.latest())                  # Latest CPI data
    
    # EVDS
    bp.set_evds_key("YOUR_EVDS_KEY")
    print(bp.evds_series("TP.DK.USD.A.YTL", period="1y"))
  12. Chain Analysis and Screening with borsapy CLI

    master

    Use the screen and scan commands to filter stocks based on multiple technical or fundamental criteria simultaneously.

    • Fundamental Screening: Combine flags like --pe-max (Price-to-Earnings maximum) and --div-min (Minimum dividend) to find undervalued, high-yield stocks.
    • Technical Scanning: Use a query string in scan to combine indicators like rsi and volume.
    • Analyst Recommendations: Use --rec (recommendation type) and --upside-min to find stocks with high projected upside based on analyst favorites.
    # Düşük F/K ve yüksek temettü
    borsapy screen --pe-max 8 --div-min 4 --index XU100
    
    # Oversold + yüksek hacim
    borsapy scan "rsi < 25 and volume > 5000000"
    
    # Analist favorileri
    borsapy screen --rec AL --upside-min 30