### Install borsapy CLI Source: https://github.com/saidsurucu/borsapy/blob/master/CLI.md Installs the borsapy package using pip. After installation, the `borsapy` command becomes available for use. ```bash pip install borsapy ``` -------------------------------- ### Debugging and CLI Help Source: https://github.com/saidsurucu/borsapy/blob/master/CLI.md Commands to verify the installation version, access help documentation, and check authentication status for data access. ```bash borsapy --version borsapy --help borsapy --help borsapy auth status ``` -------------------------------- ### Python RSI Strategy Example Source: https://github.com/saidsurucu/borsapy/blob/master/docs/borsapy/backtest.html An example of a simple Relative Strength Index (RSI) strategy function that can be passed to the `backtest` function. This strategy decides to buy when RSI is below 30 and sell when RSI is above 70, provided a position is currently held. ```python def rsi_strategy(candle, position, indicators): if indicators.get('rsi', 50) < 30 and position is None: return 'BUY' elif indicators.get('rsi', 50) > 70 and position == 'long': return 'SELL' return 'HOLD' ``` -------------------------------- ### Initialize and Get Index Info with BorsaPy Source: https://github.com/saidsurucu/borsapy/blob/master/docs/borsapy/index.html Demonstrates how to initialize an Index object with a symbol and retrieve its current information. This includes details like the index name, last traded value, and daily high/low. ```python import borsapy as bp xu100 = bp.Index("XU100") print(xu100.info) ``` -------------------------------- ### Example Technical Trading Strategies with BorsaPy Source: https://github.com/saidsurucu/borsapy/blob/master/README.md Presents several example trading strategies implemented using BorsaPy's `scan()` function. These include identifying oversold conditions, golden/death crosses, MACD crossovers, high-volume momentum, price breakouts above/below moving averages, and Bollinger Band proximity. ```python import borsapy as bp # Oversold tarama oversold = bp.scan("XU100", "rsi < 30") # Golden Cross golden = bp.scan("XU030", "sma_20 crosses_above sma_50") # Death Cross death = bp.scan("XU030", "sma_20 crosses_below sma_50") # MACD sıfır çizgisini geçiyor macd_cross = bp.scan("XU100", "macd crosses signal") # Yüksek hacimli momentum momentum = bp.scan("XU030", "rsi > 50 and volume > 5000000 and change_percent > 2") # Fiyat SMA50'nin %5 üzerinde breakout = bp.scan("XU030", "close above_pct sma_50 1.05") # Fiyat SMA200'ün %10 altında (potansiyel dip) dip = bp.scan("XU100", "close below_pct sma_200 0.90") # Bollinger alt bandına yakın bb_low = bp.scan("XU030", "close < bb_lower") # Saatlik RSI oversold hourly_oversold = bp.scan("XU030", "rsi < 30", interval="1h") ``` -------------------------------- ### TradingView Authentication Setup (Python) Source: https://github.com/saidsurucu/borsapy/blob/master/CLAUDE.md Shows how to set up TradingView authentication for BorsaPy. A single call to `set_tradingview_auth()` enables centralized authentication for all TradingView providers, including support for auth cookies for live data. ```python import borsapy as bp # Set TradingView authentication (e.g., using cookies) bp.set_tradingview_auth(auth_cookie="YOUR_AUTH_COOKIE") # Now all TradingView providers will use this authentication ``` -------------------------------- ### Analyst Targets and Recommendations Source: https://github.com/saidsurucu/borsapy/blob/master/CLI.md Get analyst price targets, buy/sell/hold recommendations, and distribution summaries for specific stocks. ```bash borsapy targets THYAO borsapy targets THYAO --recommendations borsapy targets THYAO --summary ``` -------------------------------- ### Manage Multi-Asset Portfolio Source: https://github.com/saidsurucu/borsapy/blob/master/CLAUDE.md Demonstrates how to initialize a portfolio, add various asset types (stocks, FX, crypto, funds), set a benchmark, and retrieve risk metrics. ```python portfolio = bp.Portfolio() portfolio.add("THYAO", shares=100, cost=280.0) portfolio.add("gram-altin", shares=5, asset_type="fx") portfolio.add("BTCTRY", shares=0.5) portfolio.add("YAY", shares=500, asset_type="fund") portfolio.set_benchmark("XU100") print(portfolio.holdings) print(portfolio.value) print(portfolio.risk_metrics()) ``` -------------------------------- ### GET /search/index Source: https://github.com/saidsurucu/borsapy/blob/master/docs/borsapy/search.html Search for market index symbols. ```APIDOC ## GET /search/index ### Description Searches for market index symbols based on a provided query. ### Method GET ### Endpoint /search/index ### Parameters #### Query Parameters - **query** (string) - Required - The search term (e.g., "XU", "SP500") - **limit** (integer) - Optional - Maximum number of results to return (default: 50) ### Request Example GET /search/index?query=XU ### Response #### Success Response (200) - **symbols** (array of strings) - List of matching index symbols #### Response Example ["XU100", "XU030", "XU050"] ``` -------------------------------- ### POST /backtest/initialize Source: https://github.com/saidsurucu/borsapy/blob/master/docs/borsapy/backtest.html Initializes a new backtest instance with specific market parameters and strategy configuration. ```APIDOC ## POST /backtest/initialize ### Description Initializes the backtest environment with the target symbol, timeframe, capital, and technical indicators. ### Method POST ### Endpoint /backtest/initialize ### Parameters #### Request Body - **symbol** (string) - Required - Stock symbol (e.g., "THYAO") - **strategy** (function) - Required - Strategy function with signature: strategy(candle, position, indicators) -> 'BUY'|'SELL'|'HOLD'|None - **period** (string) - Required - Historical data period (1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y) - **interval** (string) - Required - Data interval (1m, 5m, 15m, 30m, 1h, 4h, 1d) - **capital** (float) - Required - Initial capital in TL - **commission** (float) - Optional - Commission rate per trade (default 0.001) - **indicators** (list) - Optional - List of indicators (e.g., ['rsi', 'sma_20', 'macd']) ### Request Example { "symbol": "THYAO", "period": "1y", "interval": "1d", "capital": 100000, "commission": 0.001 } ### Response #### Success Response (200) - **status** (string) - Initialization success message #### Response Example { "status": "Backtest initialized successfully" } ``` -------------------------------- ### GET /search/viop Source: https://github.com/saidsurucu/borsapy/blob/master/docs/borsapy/search.html Search for VIOP (Turkish derivatives) symbols. ```APIDOC ## GET /search/viop ### Description Searches for futures and options contracts on BIST. ### Method GET ### Endpoint /search/viop ### Parameters #### Query Parameters - **query** (string) - Required - The search term (e.g., "XU030", "AKBNK") - **limit** (integer) - Optional - Maximum number of results to return (default: 50) ### Request Example GET /search/viop?query=XU030 ### Response #### Success Response (200) - **symbols** (array of strings) - List of matching VIOP contract symbols #### Response Example ["XU030D", "XU030DG2026"] ``` -------------------------------- ### GET /backtest/trades Source: https://github.com/saidsurucu/borsapy/blob/master/docs/borsapy/backtest.html Retrieves the list of executed trades as a pandas DataFrame. ```APIDOC ## GET /backtest/trades ### Description Returns a DataFrame containing detailed information about all trades executed during the backtest, including entry/exit times, prices, and profit metrics. ### Method GET ### Endpoint /backtest/trades ### Response #### Success Response (200) - **trades_df** (DataFrame) - A pandas DataFrame containing columns: entry_time, entry_price, exit_time, exit_price, side, shares, commission, profit, profit_pct, duration. #### Response Example { "trades_df": "[DataFrame object]" } ``` -------------------------------- ### Initialize and Authenticate Colendi Broker Source: https://github.com/saidsurucu/borsapy/blob/master/CLAUDE.md Demonstrates how to initialize the broker instance with credentials and perform the two-step SMS OTP authentication process required for session establishment. ```python import borsapy as bp broker = bp.Broker( license_key="BORSAPY-PRO-XXXX", api_key="colendi_api_key", api_secret="colendi_secret", username="internet_banking_user", password="internet_banking_pass" ) broker.request_otp() broker.verify_otp("123456") ``` -------------------------------- ### Index Initialization and Info Source: https://github.com/saidsurucu/borsapy/blob/master/docs/borsapy/index.html Demonstrates how to initialize an Index object with a symbol and retrieve its current information. ```APIDOC ## Initialize Index Object ### Description Initializes an Index object with a given stock market index symbol. ### Method `bp.Index(symbol: str)` ### Parameters #### Path Parameters - **symbol** (str) - Required - The symbol of the index (e.g., "XU100", "XU030", "XBANK"). ### Request Example ```python import borsapy as bp xu100 = bp.Index("XU100") ``` ## Get Index Information ### Description Retrieves the current information for the initialized index. ### Method `Index.info` (property) ### Parameters None ### Request Example ```python index_info = xu100.info print(index_info) ``` ### Response #### Success Response (200) - **symbol** (str) - Index symbol - **name** (str) - Index full name - **last** (float) - Current value - **open** (float) - Opening value - **high** (float) - Day high - **low** (float) - Day low - **close** (float) - Previous close - **change** (float) - Value change - **change_percent** (float) - Percent change - **update_time** (str) - Last update timestamp #### Response Example ```json { "symbol": "XU100", "name": "BIST 100", "last": 9500.5, "open": 9450.0, "high": 9550.0, "low": 9400.0, "close": 9480.0, "change": 20.5, "change_percent": 0.216, "update_time": "2023-10-27T18:30:00Z" } ``` ``` -------------------------------- ### GET /index/components Source: https://github.com/saidsurucu/borsapy/blob/master/docs/borsapy/index.html Retrieves the list of constituent stocks for a specific index. ```APIDOC ## GET /index/components ### Description Returns a list of all stocks currently included in the index. ### Method GET ### Endpoint /index/components ### Response #### Success Response (200) - **components** (list[dict]) - A list of dictionaries containing 'symbol' and 'name' keys for each constituent. #### Response Example [ {"symbol": "AKBNK", "name": "AKBANK"}, {"symbol": "AKSA", "name": "AKSA AKRILIK"} ] ``` -------------------------------- ### GET /backtest/results Source: https://github.com/saidsurucu/borsapy/blob/master/docs/borsapy/backtest.html Retrieves the formatted performance summary of a completed backtest session. ```APIDOC ## GET /backtest/results ### Description Returns a structured summary of backtest results, including performance metrics, trade statistics, and risk analysis. ### Method GET ### Endpoint /backtest/results ### Parameters #### Query Parameters - **symbol** (string) - Required - The ticker symbol to retrieve results for. ### Request Example GET /backtest/results?symbol=THYAO ### Response #### Success Response (200) - **net_profit** (float) - The total profit generated by the strategy. - **final_equity** (float) - The final portfolio value after the backtest period. - **win_rate** (float) - Percentage of winning trades. - **sharpe_ratio** (float) - Risk-adjusted return metric. - **max_drawdown** (float) - The maximum observed loss from a peak to a trough. #### Response Example { "symbol": "THYAO", "net_profit": 15000.50, "final_equity": 115000.50, "win_rate": 65.5, "sharpe_ratio": 1.8, "max_drawdown": 12.4 } ``` -------------------------------- ### POST /backtest/initialize Source: https://github.com/saidsurucu/borsapy/blob/master/docs/borsapy/backtest.html Initializes a new backtest session with specific market parameters and technical indicators. ```APIDOC ## POST /backtest/initialize ### Description Initializes the backtesting environment for a given stock symbol, setting up the strategy logic, historical data timeframe, and technical indicators to be calculated. ### Method POST ### Endpoint /backtest/initialize ### Parameters #### Request Body - **symbol** (string) - Required - Stock symbol (e.g., "THYAO") - **strategy** (function) - Required - Strategy function with signature: strategy(candle, position, indicators) -> 'BUY'|'SELL'|'HOLD'|None - **period** (string) - Required - Historical data period (1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y) - **interval** (string) - Required - Data interval (1m, 5m, 15m, 30m, 1h, 4h, 1d) - **capital** (float) - Optional - Initial capital in TL - **commission** (float) - Optional - Commission rate per trade (default 0.001) - **indicators** (list[str]) - Optional - List of indicators to calculate (e.g., 'rsi', 'sma_20', 'macd') - **slippage** (float) - Optional - Slippage per trade ### Request Example { "symbol": "THYAO", "period": "1y", "interval": "1d", "capital": 100000, "indicators": ["rsi", "sma_20", "macd"] } ### Response #### Success Response (200) - **status** (string) - Initialization status - **strategy_name** (string) - The name of the loaded strategy #### Response Example { "status": "success", "strategy_name": "custom_strategy" } ``` -------------------------------- ### Generate API Documentation with pdoc Source: https://github.com/saidsurucu/borsapy/blob/master/CLAUDE.md Commands to generate static HTML documentation or run a local development server for the BorsaPy API. ```bash uv run pdoc borsapy -o docs uv run pdoc borsapy ``` -------------------------------- ### GET /portfolio/risk_metrics Source: https://github.com/saidsurucu/borsapy/blob/master/README.md Calculates comprehensive risk metrics for the portfolio over a specified period. ```APIDOC ## GET /portfolio/risk_metrics ### Description Returns risk-adjusted performance metrics including Sharpe ratio, Sortino ratio, Beta, and Alpha. ### Method GET ### Endpoint /portfolio/risk_metrics ### Parameters #### Query Parameters - **period** (string) - Optional - Time period for analysis (e.g., '1y', '6m'). ### Response #### Success Response (200) - **annualized_return** (float) - Annualized return percentage. - **sharpe_ratio** (float) - Sharpe ratio value. - **max_drawdown** (float) - Maximum drawdown percentage. #### Response Example { "annualized_return": 18.2, "sharpe_ratio": 0.65, "max_drawdown": -15.3 } ``` -------------------------------- ### GET /etf_holders Source: https://github.com/saidsurucu/borsapy/blob/master/README.md Retrieves information about ETFs that hold a specific stock in their portfolio. ```APIDOC ## GET /etf_holders ### Description Returns a list of ETFs holding the specified stock, including market value and weight percentage. ### Method GET ### Response #### Success Response (200) - **holders** (pandas.DataFrame) - List of ETFs with columns: symbol, exchange, name, market_cap_usd, holding_weight_pct, issuer. ``` -------------------------------- ### Basic borsapy CLI Usage Source: https://github.com/saidsurucu/borsapy/blob/master/CLI.md Demonstrates fundamental commands for fetching stock prices, historical data, technical signals, and live price monitoring. ```bash borsapy --help ``` ```bash borsapy price THYAO ``` ```bash borsapy history THYAO --period 1y --output csv > thyao.csv ``` ```bash borsapy signals THYAO ``` ```bash borsapy watch THYAO GARAN ASELS ``` -------------------------------- ### GET /viop/contracts Source: https://github.com/saidsurucu/borsapy/blob/master/docs/borsapy/search.html Retrieve available VIOP contracts for a specific base symbol. ```APIDOC ## GET /viop/contracts ### Description Queries TradingView to find all active contracts (expiry months) for a given futures base symbol. ### Method GET ### Endpoint /viop/contracts ### Parameters #### Query Parameters - **base_symbol** (string) - Required - The base futures symbol (e.g., "XU030D") - **full_info** (boolean) - Optional - If true, returns detailed contract objects instead of strings ### Request Example GET /viop/contracts?base_symbol=XU030D&full_info=false ### Response #### Success Response (200) - **contracts** (array) - List of contract strings or detailed objects #### Response Example ["XU030DG2026", "XU030DJ2026"] ``` -------------------------------- ### Implement TradingView Real-time Streaming Source: https://github.com/saidsurucu/borsapy/blob/master/CLAUDE.md Demonstrates how to initialize a persistent TradingView stream, subscribe to symbols, fetch quotes, and handle real-time updates via callbacks or context managers. ```python import borsapy as bp # Stream oluştur ve bağlan stream = bp.TradingViewStream() stream.connect() # Sembollere abone ol stream.subscribe("THYAO") stream.subscribe("GARAN") stream.subscribe("ASELS") # Anlık fiyat al (cached, ~1ms) quote = stream.get_quote("THYAO") print(quote['last']) print(quote['bid']) print(quote['ask']) print(quote['volume']) # İlk quote için bekle (blocking) quote = stream.wait_for_quote("THYAO", timeout=5.0) # Callback ile real-time updates def on_price_update(symbol, quote): print(f"{symbol}: {quote['last']}") stream.on_quote("THYAO", on_price_update) # Tüm semboller için callback stream.on_any_quote(lambda s, q: print(f"{s}: {q['last']}")) # Bağlantıyı kapat stream.disconnect() # Context manager kullanımı with bp.TradingViewStream() as stream: stream.subscribe("THYAO") while True: quote = stream.get_quote("THYAO") ``` -------------------------------- ### GET /search/forex Source: https://github.com/saidsurucu/borsapy/blob/master/docs/borsapy/search.html Search for forex symbol strings based on a query string. ```APIDOC ## GET /search/forex ### Description Searches for forex currency pairs and symbols based on a search query. ### Method GET ### Endpoint /search/forex ### Parameters #### Query Parameters - **query** (string) - Required - The search term (e.g., "gold", "USD") - **limit** (integer) - Optional - Maximum number of results to return (default: 50) ### Request Example GET /search/forex?query=gold&limit=10 ### Response #### Success Response (200) - **symbols** (array of strings) - List of matching forex symbols #### Response Example ["XAUUSD", "XAUTRY"] ``` -------------------------------- ### Configuring Purchase Dates Source: https://github.com/saidsurucu/borsapy/blob/master/README.md Shows how to track assets with specific purchase dates to enable accurate holding duration and return calculations. ```python from datetime import date portfolio.add("THYAO", shares=100, cost=280.0, purchase_date="2024-01-15") portfolio.add("GARAN", shares=200, cost=45.0, purchase_date=date(2024, 6, 1)) print(portfolio.holdings[['symbol', 'cost', 'purchase_date', 'holding_days']]) ``` -------------------------------- ### Get Index Components Source: https://github.com/saidsurucu/borsapy/blob/master/CLI.md Lists the constituent stocks of a specified stock market index. ```bash borsapy index XU030 ``` -------------------------------- ### Stock Screening with BorsaPy Source: https://context7.com/saidsurucu/borsapy/llms.txt Demonstrates how to screen stocks using predefined templates (e.g., high dividend, low P/E) and direct filters (e.g., max P/E, min dividend yield). It also shows how to combine filters with sector/index criteria and use the Fluent API with the `Screener` class for more complex strategies. ```python import borsapy as bp # Hazır şablonlar df = bp.screen_stocks(template="high_dividend") # Temettü verimi > %2 df = bp.screen_stocks(template="low_pe") # F/K < 10 df = bp.screen_stocks(template="high_roe") # ROE > %15 # Doğrudan filtreler df = bp.screen_stocks(pe_max=10) # F/K en fazla 10 df = bp.screen_stocks(dividend_yield_min=3) # Temettü verimi min %3 df = bp.screen_stocks(roe_min=20, pb_max=2) # ROE > %20, PD/DD < 2 # Sektör/endeks ile kombine df = bp.screen_stocks(sector="Bankacılık", dividend_yield_min=3) # Fluent API (Screener class) screener = bp.Screener() screener.add_filter("pe", max=15) # F/K < 15 screener.add_filter("pb", max=2) # PD/DD < 2 screener.add_filter("dividend_yield", min=3) # Temettü verimi > %3 screener.add_filter("roe", min=15) # ROE > %15 screener.set_sector("Bankacılık") screener.set_index("BIST 100") screener.set_recommendation("AL") results = screener.run() # Değer yatırımı stratejisi screener = bp.Screener() screener.add_filter("pe", max=10) screener.add_filter("pb", max=1.5) screener.add_filter("dividend_yield", min=4) value_stocks = screener.run() # Yardımcı fonksiyonlar print(bp.screener_criteria()) # Tüm filtre kriterleri print(bp.sectors()) # Sektör listesi (53 sektör) print(bp.stock_indices()) # Endeks listesi ``` -------------------------------- ### GET /stream/indicators Source: https://github.com/saidsurucu/borsapy/blob/master/README.md Connects to the TradingView stream to receive real-time updates for Pine Script indicators. ```APIDOC ## GET /stream/indicators ### Description Subscribes to a symbol and interval to receive real-time indicator data updates. ### Method GET ### Endpoint /stream/indicators ### Parameters #### Query Parameters - **symbol** (string) - Required - The ticker symbol - **interval** (string) - Required - Time interval (e.g., '1m', '5m') - **indicator** (string) - Required - Name of the indicator (e.g., 'RSI', 'MACD') ### Request Example { "symbol": "THYAO", "interval": "1m", "indicator": "RSI" } ### Response #### Success Response (200) - **value** (object) - Current indicator values #### Response Example { "RSI": {"value": 48.5} } ``` -------------------------------- ### Managing Portfolio Assets Source: https://github.com/saidsurucu/borsapy/blob/master/README.md Demonstrates how to add various asset types (stocks, FX, crypto, funds) to a portfolio, set benchmarks, and access portfolio summary statistics. ```python portfolio.add("THYAO", shares=100, cost=280.0) portfolio.add("gram-altin", shares=10, asset_type="fx") portfolio.add("BTCTRY", shares=0.5) portfolio.set_benchmark("XU100") print(portfolio.holdings) print(portfolio.value) print(portfolio.pnl) ``` -------------------------------- ### Execute Historical Replay for Backtesting Source: https://github.com/saidsurucu/borsapy/blob/master/README.md Shows how to create a replay session for historical data, allowing for candle-by-candle iteration to test trading logic. ```python import borsapy as bp # Create replay session 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']}") # Using a callback def on_candle(c): print(f"Progress: {c['_index']}/{c['_total']}") session.on_candle(on_candle) list(session.replay()) ``` -------------------------------- ### GET /ticker/{symbol}/ta_signals Source: https://github.com/saidsurucu/borsapy/blob/master/CLAUDE.md Retrieves technical analysis signals (BUY/SELL/NEUTRAL) for a given ticker symbol. ```APIDOC ## GET /ticker/{symbol}/ta_signals ### Description Returns technical analysis signals including oscillators and moving averages for a specific ticker. ### Method GET ### Endpoint /ticker/{symbol}/ta_signals ### Parameters #### Path Parameters - **symbol** (string) - Required - The ticker symbol #### Query Parameters - **interval** (string) - Optional - Timeframe (e.g., 1h, 1d, 1w) ### Response #### Success Response (200) - **summary** (object) - Overall recommendation - **oscillators** (object) - Oscillator signals - **moving_averages** (object) - Moving average values #### Response Example { "summary": { "recommendation": "STRONG_BUY" }, "oscillators": { "compute": { "RSI": "BUY" } } } ``` -------------------------------- ### Portfolio Rebalancing with Borsapy Source: https://github.com/saidsurucu/borsapy/blob/master/CLAUDE.md Demonstrates how to set target asset weights, perform drift analysis to identify deviations, and execute rebalancing plans. The process supports dry runs to preview changes before applying them to the portfolio. ```python import borsapy as bp p = bp.Portfolio() p.add("THYAO", shares=100, cost=280) p.add("GARAN", shares=200, cost=50) p.add("gram-altin", shares=5, asset_type="fx") # Hedef agirliklar belirle (0-1 olcegi, toplam ~1.0) p.set_target_weights({"THYAO": 0.50, "GARAN": 0.30, "gram-altin": 0.20}) # Sapma analizi print(p.drift()) # Dengeleme plani (esik: %2 altindaki sapmalar yoksayilir) plan = p.rebalance_plan(threshold=0.02) print(plan) # Dengelemeyi calistir p.rebalance(threshold=0.02) # Dry run (sadece plan, uygulama yok) plan = p.rebalance(threshold=0.02, dry_run=True) # Export/Import hedef agirliklar korunur data = p.to_dict() p2 = bp.Portfolio.from_dict(data) print(p2.target_weights) ``` -------------------------------- ### GET /ticker/{symbol}/etf_holders Source: https://github.com/saidsurucu/borsapy/blob/master/CLAUDE.md Retrieves a list of international ETFs that hold the specified BIST stock. ```APIDOC ## GET /ticker/{symbol}/etf_holders ### Description Fetches international ETF holdings for a specific BIST stock ticker. ### Method GET ### Endpoint /ticker/{symbol}/etf_holders ### Parameters #### Path Parameters - **symbol** (string) - Required - The stock ticker symbol (e.g., ASELS) ### Response #### Success Response (200) - **data** (array) - List of ETF objects containing symbol, name, market_cap_usd, holding_weight_pct, etc. #### Response Example { "symbol": "ASELS", "holders": [ { "symbol": "IEMG", "name": "iShares Core MSCI Emerging Markets ETF", "holding_weight_pct": 0.090686 } ] } ``` -------------------------------- ### GET /backtest/summary Source: https://github.com/saidsurucu/borsapy/blob/master/docs/borsapy/backtest.html Exports the complete backtest results as a dictionary, including performance metrics and risk statistics. ```APIDOC ## GET /backtest/summary ### Description Exports the backtest results to a dictionary format, compatible with TradingView/Mathieu2301 standards. Includes identification, configuration, summary, trade statistics, and risk metrics. ### Method GET ### Endpoint /backtest/summary ### Response #### Success Response (200) - **result** (object) - Dictionary containing symbol, period, interval, strategy_name, net_profit, win_rate, sharpe_ratio, etc. #### Response Example { "symbol": "AAPL", "net_profit": 1500.50, "win_rate": 0.65, "sharpe_ratio": 1.85 } ``` -------------------------------- ### Initialize Backtest Class Source: https://github.com/saidsurucu/borsapy/blob/master/docs/borsapy/backtest.html Shows the constructor signature for the Backtest class, which configures the trading environment including symbol, initial capital, and indicator selection. ```python def __init__(self, symbol: str, strategy: StrategyFunc, period: str = "1y", interval: str = "1d", capital: float = 100_000.0, commission: float = 0.001, indicators: list[str] | None = None, slippage: float = 0.0): self.symbol = symbol.upper() self.strategy = strategy self.period = period self.interval = interval self.capital = capital self.commission = commission self.indicators = indicators or ["rsi", "sma_20", "ema_12", "macd"] ``` -------------------------------- ### Initialize Backtest - BorsaPy Source: https://github.com/saidsurucu/borsapy/blob/master/docs/borsapy/backtest.html Initializes the Backtest class with parameters for a trading simulation. It accepts stock symbol, strategy function, data period and interval, initial capital, commission rates, and a list of technical indicators to be calculated. Default indicators are provided if none are specified. ```python def __init__(self, symbol: str, strategy: Callable, period: str, interval: str, capital: float, commission: float, indicators: list[str] | None = None, slippage: float = 0.0): """ Initialize Backtest. Args: symbol: Stock symbol (e.g., "THYAO"). strategy: Strategy function with signature: strategy(candle, position, indicators) -> 'BUY'|'SELL'|'HOLD'|None period: Historical data period (1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y). interval: Data interval (1m, 5m, 15m, 30m, 1h, 4h, 1d). capital: Initial capital in TL. commission: Commission rate per trade (0.001 = 0.1%). indicators: List of indicators to calculate. Options: 'rsi', 'rsi_7', 'sma_20', 'sma_50', 'sma_200', 'ema_12', 'ema_26', 'ema_50', 'macd', 'bollinger', 'atr', 'atr_20', 'stochastic', 'adx' slippage: Slippage per trade (for future use). """ self.symbol = symbol.upper() self.strategy = strategy self.period = period self.interval = interval self.capital = capital self.commission = commission self.indicators = indicators or ["rsi", "sma_20", "ema_12", "macd"] self.slippage = slippage # Strategy name for reporting self._strategy_name = getattr(strategy, "__name__", "custom_strategy") # Data storage self._df: pd.DataFrame | None = None self._df_with_indicators: pd.DataFrame | None = None ``` -------------------------------- ### GET /history Source: https://github.com/saidsurucu/borsapy/blob/master/README.md Retrieves historical price data for a specific ticker symbol over a defined period and interval. ```APIDOC ## GET /history ### Description Fetches historical market data for a given ticker. Supports various time periods and granular intervals. ### Method GET ### Parameters #### Query Parameters - **period** (string) - Required - Time range (e.g., '1g', '1ay', '1y') - **interval** (string) - Required - Data granularity (e.g., '1m', '1h', '1d') ### Request Example ```python df = hisse.history(period="1g", interval="1m") ``` ### Response #### Success Response (200) - **DataFrame** (pandas.DataFrame) - Historical price data including OHLCV columns. ``` -------------------------------- ### POST /backtest/run Source: https://github.com/saidsurucu/borsapy/blob/master/docs/borsapy/backtest.html Initializes a backtest simulation for a specific stock symbol using a user-defined strategy function and historical data parameters. ```APIDOC ## POST /backtest/run ### Description Initializes the Backtest engine with a symbol, strategy function, and configuration parameters to simulate trading performance. ### Method POST ### Endpoint /backtest/run ### Parameters #### Request Body - **symbol** (string) - Required - Stock symbol (e.g., "THYAO"). - **strategy** (function) - Required - Callback with signature: strategy(candle, position, indicators) -> 'BUY'|'SELL'|'HOLD'|None. - **period** (string) - Optional - Historical data period (1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y). Default: "1y". - **interval** (string) - Optional - Data interval (1m, 5m, 15m, 30m, 1h, 4h, 1d). Default: "1d". - **capital** (float) - Optional - Initial capital in TL. Default: 100,000.0. - **commission** (float) - Optional - Commission rate per trade (0.001 = 0.1%). Default: 0.001. - **indicators** (list[str]) - Optional - List of technical indicators to calculate (e.g., 'rsi', 'sma_20', 'macd'). ### Request Example { "symbol": "THYAO", "period": "1y", "capital": 100000, "indicators": ["rsi", "sma_20"] } ### Response #### Success Response (200) - **sharpe_ratio** (float) - The calculated Sharpe ratio of the strategy performance. - **total_return** (float) - The total percentage return of the simulation. #### Response Example { "sharpe_ratio": 1.25, "total_return": 0.15 } ``` -------------------------------- ### Get All Indices Source: https://github.com/saidsurucu/borsapy/blob/master/docs/borsapy/index.html Retrieves a list of all available indices in the BIST, including their symbols, names, and component counts. ```APIDOC ## GET /all_indices ### Description Fetches all available indices from BIST with their component counts. This includes all 79 indices, not just the commonly used ones. ### Method GET ### Endpoint /all_indices ### Parameters None ### Request Example None ### Response #### Success Response (200) - **List[dict]**: A list of dictionaries, where each dictionary contains 'symbol', 'name', and 'count' keys. #### Response Example ```json [ { "symbol": "X030C", "name": "BIST 30 Capped", "count": 30 }, ... ] ``` ``` -------------------------------- ### GET /index/history Source: https://github.com/saidsurucu/borsapy/blob/master/docs/borsapy/index.html Retrieves historical OHLCV data for the index based on specified time ranges or periods. ```APIDOC ## GET /index/history ### Description Fetches historical market data for the index. Supports relative periods or absolute date ranges. ### Method GET ### Parameters #### Query Parameters - **period** (string) - Optional - Data duration (e.g., '1mo', '1y', 'max'). Ignored if start is provided. - **interval** (string) - Optional - Data resolution (e.g., '1h', '1d', '1wk'). - **start** (string) - Optional - Start date (YYYY-MM-DD). - **end** (string) - Optional - End date (YYYY-MM-DD). ### Response #### Success Response (200) - **data** (DataFrame) - A pandas DataFrame containing Open, High, Low, Close, and Volume columns. #### Response Example { "Date": ["2024-01-01", "2024-01-02"], "Open": [100.5, 101.2], "High": [102.0, 103.5], "Low": [99.8, 100.1], "Close": [101.0, 102.8], "Volume": [10000, 12000] } ``` -------------------------------- ### Portfolio Rebalancing with BorsaPy Source: https://github.com/saidsurucu/borsapy/blob/master/README.md Demonstrates how to plan and execute portfolio rebalancing based on target weights and drift thresholds. It includes generating a rebalance plan and applying it to the portfolio, with an option for a dry run. ```python import borsapy as bp # Assuming 'p' is an initialized Portfolio object # Dengeleme planı (eşik: %2 altındaki sapmalar yoksayılır) plan = p.rebalance_plan(threshold=0.02) print(plan) # symbol, current_shares, target_shares, delta_shares, delta_value, action # Dengelemeyi uygula p.rebalance(threshold=0.02) # Dry run (sadece plan, uygulama yok) plan = p.rebalance(threshold=0.02, dry_run=True) ``` -------------------------------- ### Portfolio Import and Export with BorsaPy Source: https://github.com/saidsurucu/borsapy/blob/master/README.md Shows how to export portfolio data to a dictionary and import it back, preserving purchase dates. It also covers saving and loading portfolio data to/from JSON files. ```python # Dict olarak export (target_weights dahil) data = portfolio.to_dict() print(data) # Dict'ten import (purchase_date korunur) portfolio2 = bp.Portfolio.from_dict(data) # JSON'a kaydetme import json with open("portfolio.json", "w") as f: json.dump(portfolio.to_dict(), f) # JSON'dan yükleme with open("portfolio.json") as f: portfolio3 = bp.Portfolio.from_dict(json.load(f)) ``` -------------------------------- ### GET /search_viop Source: https://github.com/saidsurucu/borsapy/blob/master/docs/borsapy/search.html Searches for VIOP (Turkish derivatives) symbols on the BIST exchange based on a query string. ```APIDOC ## GET /search_viop ### Description Searches for futures and options contracts on BIST using a keyword query. ### Method GET ### Endpoint /search_viop ### Parameters #### Query Parameters - **query** (string) - Required - Search query (e.g., "XU030", "AKBNK", "gold") - **limit** (integer) - Optional - Maximum number of results to return (default: 50) ### Request Example GET /search_viop?query=XU030&limit=10 ### Response #### Success Response (200) - **symbols** (array of strings) - List of matching VIOP contract symbol strings #### Response Example ["XU030D", "XU030DG2026", "XU030DJ2026"] ``` -------------------------------- ### GET /viop_contracts Source: https://github.com/saidsurucu/borsapy/blob/master/docs/borsapy/search.html Retrieves available VIOP contracts for a specific base symbol, including expiry month details. ```APIDOC ## GET /viop_contracts ### Description Queries TradingView to find all active contracts (expiry months) for a given futures base symbol. ### Method GET ### Endpoint /viop_contracts ### Parameters #### Query Parameters - **base_symbol** (string) - Required - Base futures symbol (e.g., "XU030D", "XAUTRYD") - **full_info** (boolean) - Optional - If true, returns detailed contract objects including month and year info ### Request Example GET /viop_contracts?base_symbol=XU030D&full_info=false ### Response #### Success Response (200) - **contracts** (array) - List of contract symbols or detailed objects #### Response Example ["XU030DG2026", "XU030DJ2026"] ``` -------------------------------- ### POST /backtest/run Source: https://github.com/saidsurucu/borsapy/blob/master/docs/borsapy/backtest.html Executes the configured backtest simulation and returns performance metrics. ```APIDOC ## POST /backtest/run ### Description Runs the simulation loop over the historical data using the initialized strategy and returns the performance results. ### Method POST ### Endpoint /backtest/run ### Parameters None ### Request Example {} ### Response #### Success Response (200) - **BacktestResult** (object) - Contains performance metrics, equity curve, and trade history. #### Response Example { "total_return": 0.15, "sharpe_ratio": 1.2, "trades": [] } ``` -------------------------------- ### Retrieve Fund History and Risk Metrics Source: https://github.com/saidsurucu/borsapy/blob/master/CLAUDE.md Shows how to fetch historical fund performance over various periods and calculate key risk metrics like Sharpe and Sortino ratios. ```python fund = bp.Fund("YAY") fund.history(period="1y") fund.history(period="3y") fund.history(period="5y") fund.history(period="max") # Risk metrics fund.sharpe_ratio(period="3y") metrics = fund.risk_metrics(period="1y") ``` -------------------------------- ### Get Futures Contract Data Source: https://github.com/saidsurucu/borsapy/blob/master/CLI.md Fetches data for VİOP (Borsa Istanbul Derivatives Market) futures contracts. ```bash borsapy viop XU030D ``` -------------------------------- ### Get Government Bond Yields Source: https://github.com/saidsurucu/borsapy/blob/master/CLI.md Fetches yield data for government bonds, specified by maturity (e.g., 10Y). ```bash borsapy bonds 10Y ``` -------------------------------- ### Manage Portfolio with Purchase Dates Source: https://github.com/saidsurucu/borsapy/blob/master/CLAUDE.md Illustrates how to add assets to a portfolio with specific purchase dates, view the resulting holdings dataframe, and export/import portfolio data using JSON. ```python import borsapy as bp from datetime import date portfolio = bp.Portfolio() # Tarih ile ekleme portfolio.add("THYAO", shares=100, cost=280.0, purchase_date="2024-01-15") portfolio.add("GARAN", shares=200, cost=45.0, purchase_date=date(2024, 6, 1)) portfolio.add("ASELS", shares=50, cost=120.0) # Holdings DataFrame'de yeni sütunlar print(portfolio.holdings) # JSON export/import data = portfolio.to_dict() portfolio2 = bp.Portfolio.from_dict(data) ``` -------------------------------- ### Get Index Details Source: https://github.com/saidsurucu/borsapy/blob/master/docs/borsapy/index.html Retrieves an Index object for a given symbol, allowing access to historical data and other index-specific information. ```APIDOC ## GET /index/{symbol} ### Description Gets an Index object for the specified symbol. This is a convenience function to create an Index object for further operations like fetching historical data. ### Method GET ### Endpoint /index/{symbol} ### Parameters #### Path Parameters - **symbol** (str) - Required - The index symbol (e.g., "XU100", "XBANK"). ### Request Example None (This is a function call, not a direct HTTP request) ### Response #### Success Response (200) - **Index** (object) - An Index object containing details and methods for the specified index. #### Response Example ```python import borsapy as bp xu100 = bp.index("XU100") # Now you can use xu100 object, e.g.: # history = xu100.history(period="1mo") ``` ``` -------------------------------- ### BorsaPy VIOP (Futures and Options) Basic Usage Source: https://github.com/saidsurucu/borsapy/blob/master/README.md This section demonstrates the basic usage of BorsaPy's VIOP module for accessing futures and options data. It covers how to retrieve lists of all futures and options contracts, access specific sub-categories like stock, index, currency, and commodity futures, and search for derivatives based on a symbol. ```python import borsapy as bp viop = bp.VIOP() # Tüm vadeli işlem kontratları print(viop.futures) # Tüm opsiyonlar print(viop.options) # Vadeli işlem alt kategorileri print(viop.stock_futures) # Pay vadeli print(viop.index_futures) # Endeks vadeli print(viop.currency_futures) # Döviz vadeli print(viop.commodity_futures) # Emtia vadeli # Opsiyon alt kategorileri print(viop.stock_options) # Pay opsiyonları print(viop.index_options) # Endeks opsiyonları # Sembol bazlı arama print(viop.get_by_symbol("THYAO")) # THYAO'nun tüm türevleri ```