### Quick Start: Get Live Market Data and Historical Data Source: https://github.com/fredysessie/casabourse/blob/main/README.md Import the library and use basic functions to fetch live market data and historical data for a specific ticker. ```python import casabourse as cb # Récupérer les données de marché en direct df_live = cb.get_live_market_data() print(df_live.head()) # Historique d'un ticker hist = cb.get_historical_data_auto('IAM', '2024-01-01', '2024-12-31') print(hist.head()) ``` -------------------------------- ### Developer Installation Source: https://github.com/fredysessie/casabourse/blob/main/README.md Clone the repository and install the library in development mode for contributing or modifying the code. Includes installing development dependencies. ```bash git clone https://github.com/Fredysessie/casabourse.git cd casabourse pip install -e . pip install -r requirements.txt pip install -r docs/requirements-docs.txt ``` -------------------------------- ### Initialize Casabourse and Get Build ID Source: https://github.com/fredysessie/casabourse/blob/main/examples/example_notebook.ipynb Imports the casabourse library and displays the cached build ID. Ensure casabourse is installed. ```python import casabourse as cb from IPython.display import display print('build id:', cb.get_build_id_cached()) ``` -------------------------------- ### Install and Build Casabourse Documentation Source: https://github.com/fredysessie/casabourse/blob/main/docs/index.md Install the library in development mode and its documentation dependencies. Then, use the provided script to generate the HTML documentation. ```powershell pip install -e . pip install -r docs/requirements-docs.txt ``` ```powershell python .\scripts\build_docs.py ``` -------------------------------- ### Install Casabourse Library Source: https://github.com/fredysessie/casabourse/blob/main/README.md Install the Casabourse library using pip. This is the recommended method for users. ```bash pip install casabourse ``` -------------------------------- ### Quick Usage Examples Source: https://github.com/fredysessie/casabourse/blob/main/README.md Demonstrates basic usage of the Casabourse library for fetching live market data and historical data. ```APIDOC ## Quick Usage Examples ### Description These examples show how to quickly get started with the Casabourse library to fetch live market data and historical data for a given ticker. ### Code Examples ```python import casabourse as cb # Retrieve live market data (pandas DataFrame) df_live = cb.get_live_market_data() print(df_live.head()) # Get historical data for a ticker over a period hist = cb.get_historical_data_auto('IAM', '2024-01-01', '2024-12-31') print(hist.head()) ``` ``` -------------------------------- ### Run Pytest Suite Source: https://github.com/fredysessie/casabourse/blob/main/README.md Install pytest and run the test suite with the quiet flag for concise output. Ensure requirements are installed first. ```powershell pip install -r requirements.txt ``` ```powershell pip install pytest ``` ```powershell pytest -q ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/fredysessie/casabourse/blob/main/README.md Install the project's development dependencies using pip. This includes the project itself in editable mode and other requirements. ```bash pip install -e . ``` ```bash pip install -r requirements.txt ``` ```bash pip install -r docs/requirements-docs.txt ``` -------------------------------- ### Historical Plot Example Source: https://github.com/fredysessie/casabourse/blob/main/README.md Illustrates how to use an example script to fetch historical data and plot closing prices. ```APIDOC ## Historical Plot Example ### Description This example demonstrates how to use the `examples/historical_plot.py` script to retrieve historical ticker data and visualize its closing price. ### Usage ```powershell pip install -e . pip install pandas matplotlib python .\examples\historical_plot.py IAM --start 2024-01-01 --end 2024-12-31 ``` The script automatically identifies the closing price column and saves a PNG image of the plot. For interactive plotting, the code can be adapted for use in a Jupyter notebook with `%matplotlib inline`. ``` -------------------------------- ### Plot Historical Prices using Example Script Source: https://github.com/fredysessie/casabourse/blob/main/README.md Execute an example script to fetch historical ticker data and plot its closing price. Requires pandas and matplotlib. The script automatically identifies the closing price column. ```powershell pip install -e . pip install pandas matplotlib python .\examples\historical_plot.py IAM --start 2024-01-01 --end 2024-12-31 ``` -------------------------------- ### Fetch Live Market Data and Symbol Info Source: https://github.com/fredysessie/casabourse/blob/main/docs/usage.md Use this snippet to get real-time market data as a pandas DataFrame and to find a symbol's ID from its ticker. Ensure the casabourse library is installed. ```python import casabourse as cb # récupère les données de marché en direct (DataFrame pandas) df_live = cb.get_live_market_data() print(df_live.head()) # recherche d'identifiant de symbole à partir d'un ticker sid = cb.get_symbol_id_from_ticker_auto('AFM') print('symbol id AFM:', sid) ``` -------------------------------- ### Build Project Documentation Source: https://github.com/fredysessie/casabourse/blob/main/README.md Generate HTML and PDF documentation using the provided script. Ensure the documentation dependencies are installed and a TeX distribution is available for PDF generation. ```powershell pip install -r docs/requirements-docs.txt ``` ```powershell # pour générer le PDF via LaTeX, installez également une distribution TeX (ex: TeX Live, MiKTeX) ``` ```powershell python .\scripts\build_docs.py ``` -------------------------------- ### Get Available Instruments and Indices Source: https://github.com/fredysessie/casabourse/blob/main/README.md Fetch lists of available financial instruments and market indices supported by Casabourse. ```python import casabourse as cb # Liste des instruments disponibles df_instruments = cb.get_available_instrument() print(df_instruments.head()) # Liste des indices disponibles df_indices = cb.get_available_indexes() print(df_indices.head()) ``` -------------------------------- ### Get Volume and Capitalization Overview Source: https://github.com/fredysessie/casabourse/blob/main/examples/example_notebook.ipynb Fetches and displays volume overview data and global capitalization. Handles cases where data might be missing. ```python # Volumes et capitalisation gv = cb.get_volume_overview() if gv and gv[0] is not None: display(gv[0]) cap = cb.get_capitalization_overview() if cap: display(cap['global_cap']) ``` -------------------------------- ### Get Market Summary Source: https://context7.com/fredysessie/casabourse/llms.txt Provides a global market summary with key indicators like total capitalization and average variations. Requires the 'casabourse' library to be imported. ```python import casabourse as cb summary = cb.get_market_summary() if summary: print(f"Date : {summary['date_heure']}") print(f"Nombre d'instruments : {summary['Nombre total instruments']}") print(f"En hausse : {summary['Instruments en hausse']}") print(f"En baisse : {summary['Instruments en baisse']}") print(f"Volume total : {summary['Volume total échangé']:,.0f} MAD") print(f"Capitalisation totale : {summary['Capitalisation totale']:,.0f} MAD") # Sortie : # Date : 2025-01-15 10:30:00 # Nombre d'instruments : 75 # En hausse : 42 # En baisse : 21 # Volume total : 450 234 567 MAD ``` -------------------------------- ### Get Available Instruments Source: https://context7.com/fredysessie/casabourse/llms.txt Retrieves a list of all available instruments on the Casablanca Stock Exchange with their metadata. Returns a pandas DataFrame or None if an error occurs. ```python import casabourse as cb df_instruments = cb.get_available_instrument() if df_instruments is not None: print(f"Nombre total d'instruments : {len(df_instruments)}") print(df_instruments.head(10)) ``` -------------------------------- ### Get Index Composition and Quotation Source: https://github.com/fredysessie/casabourse/blob/main/examples/example_notebook.ipynb Retrieves the composition and quotation for a given stock index. Displays the data or a 'no data' message if unavailable. ```python # Indices : composition et cotation comp = cb.get_index_composition('MSI20') display(comp.head() if comp is not None else 'no composition') quot = cb.get_index_quotation('MSI20') display(quot if quot is not None else 'no quotation') ``` -------------------------------- ### Get Simplified Market Data with casabourse Source: https://context7.com/fredysessie/casabourse/llms.txt Fetch simplified market data from the `/api/bourse/dashboard/ticker` endpoint. This method is faster than `get_live_market_data` but provides fewer details per instrument. ```python import casabourse as cb # Marché principal (marche=59, classe=50 par défaut) df = cb.get_market_data(marche=59, classes=[50]) if df is not None: print(df[['Symbole', 'Nom', 'Cours courant', 'Variation %', 'Volume échangé', 'Secteur']].head(10)) # Sortie : # Symbole Nom Cours courant Variation % Volume échangé Secteur # 0 IAM Maroc Telecom SA 143.90 -0.07 5678901.00 Télécommunications # 1 ATW Attijariwafa Bank 549.00 0.55 12345678.00 Banques ``` -------------------------------- ### Get Sector Indices Source: https://context7.com/fredysessie/casabourse/llms.txt Retrieves a list of all available sector indices. Use this to get an overview of market sectors. ```python df_sector = cb.get_sector_indices(formatted=True) if df_sector is not None: print(f"\n{len(df_sector)} indices sectoriels disponibles") print(df_sector[['Indice', 'Code_Index', 'Variation veille (%)']].to_string(index=False)) ``` -------------------------------- ### Get Historical Volume Data Source: https://context7.com/fredysessie/casabourse/llms.txt Retrieves detailed historical volume data for a specified period, including central market, block trades, IPOs, takeovers, and transfers. Requires start and end dates. ```python import casabourse as cb ``` -------------------------------- ### Get Sector Performance Source: https://context7.com/fredysessie/casabourse/llms.txt Aggregates sector performance data, including average variation and total capitalization. Requires the 'casabourse' library to be imported. ```python import casabourse as cb sectors = cb.get_sector_performance() if sectors is not None: print("=== PERFORMANCE PAR SECTEUR ===") print(sectors.to_string()) # Sortie (triée par variation décroissante) : # Variation moyenne % Capitalisation totale Nombre d'instruments # Secteur # Télécommunications 1.25 89000000000.0 2 # Banques 0.85 250000000000.0 8 # Immobilier -0.30 15000000000.0 5 ``` -------------------------------- ### Get Top Gainers and Losers Source: https://context7.com/fredysessie/casabourse/llms.txt Retrieves the top 5 stocks with the highest gains or losses for the day. Requires the 'casabourse' library to be imported. ```python import casabourse as cb # Top 5 des hausses du jour gainers = cb.get_top_gainers(limit=5) if gainers is not None: print("=== TOP 5 HAUSSIERS ===") print(gainers.to_string(index=False)) # Sortie : # Symbole Nom Cours courant Variation % Volume échangé # XYZ Société ABC SA 250.00 5.80 1 234 567 # Top 5 des baisses du jour losers = cb.get_top_losers(limit=5) if losers is not None: print("=== TOP 5 BAISSIERS ===") print(losers.to_string(index=False)) # Sortie : # Symbole Nom Cours courant Variation % Volume échangé # DEF Société DEF SA 130.00 -3.20 890 123 ``` -------------------------------- ### Get Volume Overview Source: https://context7.com/fredysessie/casabourse/llms.txt Provides a summary of trading volumes for the current session, returning five DataFrames: global volume, top 10 active instruments, central market, block market, and other markets. Returns None if data is unavailable. ```python import casabourse as cb df_global, df_top, df_central, df_blocs, df_autres = cb.get_volume_overview() if df_global is not None: print("=== VOLUME GLOBAL DE LA SÉANCE ===") print(df_global.to_string(index=False)) print("\n=== TOP 10 INSTRUMENTS ACTIFS ===") print(df_top.to_string(index=False)) print("\n=== MARCHÉ CENTRAL ===") print(df_central.to_string(index=False)) print("\n=== MARCHÉ DE BLOCS ===") print(df_blocs.to_string(index=False)) ``` -------------------------------- ### Get Technical Indicators Source: https://context7.com/fredysessie/casabourse/llms.txt Calculates basic technical indicators for a given instrument, such as support/resistance levels and intraday variation. Requires the 'casabourse' library to be imported. ```python import casabourse as cb indicators = cb.get_technical_indicators('IAM') if indicators: for cle, valeur in indicators.items(): print(f" {cle} : {valeur}") # Sortie : # Support (Plus bas) : 142.5 # Résistance (Plus haut) : 145.2 # Amplitude journée (%) : 1.89 # Variation vs ouverture (%) : -0.14 # Ecart prix achat/vente : 0.10 # Ratio volume/transactions : 18234.56 ``` -------------------------------- ### Get Index Composition Source: https://context7.com/fredysessie/casabourse/llms.txt Retrieves the list of instruments within a specific index, including real-time market data. Use for analyzing index constituents. ```python import casabourse as cb # Composition du MSI20 (20 valeurs les plus liquides) df_comp = cb.get_index_composition('MSI20', formatted=True, verify_index=True) if df_comp is not None: print(f"Nombre de composantes du MSI20 : {len(df_comp)}") print(df_comp[['Société', 'Ticker', 'Dernier cours', 'Variation (%)', 'Capitalisation']].head(5)) ``` ```python # Récupération en lot pour plusieurs indices batch = cb.get_index_composition_batch(['MSI20', 'MASI', 'BANK'], formatted=True) for code_indice, df in batch.items(): print(f"{code_indice} : {len(df)} composantes") ``` ```python # Tous les indices principaux en une fois all_comp = cb.get_composition_for_main_indices(formatted=True) ``` -------------------------------- ### Get Live Market Data with casabourse Source: https://context7.com/fredysessie/casabourse/llms.txt Retrieve comprehensive live market data for the Casablanca Stock Exchange, including prices, volumes, and order book details. The data is formatted for readability and can be saved to a CSV file. ```python import casabourse as cb # Récupération des données en direct (avec formatage des nombres) df_live = cb.get_live_market_data(formatted=True) if df_live is not None: print(f"Nombre d'instruments : {len(df_live)}") print(df_live[['Instrument', 'Dernier cours', 'Variation en %', 'Volume', 'Capitalisation']].head(5)) # Exemple de sortie : # Instrument Dernier cours Variation en % Volume Capitalisation # 0 ATTIJARIWAFA BANK 549,00 +0.55% 12 345 678,00 131 000 000 000,00 # 1 MAROC TELECOM 143,90 -0.07% 5 678 901,00 89 000 000 000,00 # Sauvegarder en CSV df_live.to_csv("marche_live.csv", index=False, encoding="utf-8-sig") print("Données sauvegardées dans marche_live.csv") ``` -------------------------------- ### Retrieve Historical Data for a Ticker Source: https://github.com/fredysessie/casabourse/blob/main/docs/usage.md This example shows how to fetch historical stock data for a given ticker symbol within a specified date range. The data is returned as a pandas DataFrame. ```python # historique d'un ticker sur une période hist = cb.get_historical_data_auto('IAM', '2024-01-01', '2024-12-31') print(hist.head()) ``` -------------------------------- ### Get Instrument Details Source: https://context7.com/fredysessie/casabourse/llms.txt Retrieves detailed information for a specific instrument, including ISIN, nominal value, listing price, trading method, and recent transactions. Returns a dictionary or None. ```python import casabourse as cb details = cb.get_instrument_details('ATW') if details: print(f"Nom : {details.get('Nom')}") print(f"Cours courant : {details.get('Cours courant')}") print(f"Variation : {details.get('Variation %')}%)" print(f"Volume : {details.get('Volume échangé')}") print(f"Capitalisation : {details.get('Capitalisation')}") ``` -------------------------------- ### Get Indices List with Capitalization and Available Indices Source: https://context7.com/fredysessie/casabourse/llms.txt Retrieve a full list of indices with their capitalization or a filtered list of indices with non-zero capitalization. Use `formatted=True` for human-readable output. ```python import casabourse as cb # Liste complète des indices avec capitalisation, triée par capitalisation décroissante df_list = cb.get_indices_list_with_capitalization(formatted=True) if df_list is not None: print(df_list[['Indice', 'Code_Index', 'Capitalisation (MAD)', 'Catégorie']].head(10)) ``` ```python # Indices disponibles pour récupérer la composition (capitalisation > 0) available = cb.get_available_indices_for_composition() if available is not None: print(f"{len(available)} indices disponibles pour composition") # Utilisation typique : itérer pour récupérer toutes les compositions for _, row in available.head(3).iterrows(): print(f" → {row['Code_Index']} : {row['Capitalisation (MAD)']} MAD") ``` -------------------------------- ### Get Current Capitalization Overview Source: https://context7.com/fredysessie/casabourse/llms.txt Retrieves a dictionary containing the current global capitalization, top 10 capitalized companies, and sectorial capitalization. Use this for a snapshot of the current market status. The `formatted=True` argument ensures human-readable output. ```python import casabourse as cb cap = cb.get_capitalization_overview(formatted=True) if cap: # Capitalisation globale print("=== CAPITALISATION GLOBALE ===") print(cap['global_cap'].to_string(index=False)) # Top 10 print("\n=== TOP 10 DES CAPITALISATIONS ===") print(cap['top_10'][['Rang', 'Société', 'Ticker', 'Capitalisation (MAD)', 'Variation']].to_string(index=False)) # Capitalisation sectorielle print("\n=== RÉPARTITION SECTORIELLE ===") print(cap['sectorial'][['Secteur', 'Pourcentage', 'Capitalisation (MAD)']].to_string(index=False)) ``` -------------------------------- ### Get Index Quotation Data Source: https://context7.com/fredysessie/casabourse/llms.txt Fetches real-time quotation data for an index, including value, variations, and capitalization. Use for current market status of an index. ```python import casabourse as cb df_q = cb.get_index_quotation('MSI20', formatted=True) if df_q is not None: print(df_q.to_string(index=False)) ``` -------------------------------- ### Get Overview of All Indices Source: https://context7.com/fredysessie/casabourse/llms.txt Fetches real-time data for all stock indices, including their value, variation, and capitalization, grouped by category. The `formatted=True` argument provides human-readable values. The result needs to be converted to a DataFrame using `format_indices_to_dataframe`. ```python import casabourse as cb # Récupérer les données brutes groupées par catégorie indices_data = cb.get_all_indices_overview(formatted=True) # Convertir en DataFrame complet if indices_data: df = cb.format_indices_to_dataframe(indices_data, formatted=True) print(f"Total d'indices : {len(df)}") print(df[['Catégorie', 'Indice', 'Code_Index', 'Valeur indice', 'Variation veille (%)']].head(8)) ``` -------------------------------- ### Get and Cache BuildId with casabourse Source: https://context7.com/fredysessie/casabourse/llms.txt Retrieve the dynamic Next.js buildId required for API access. Use the cached version for efficiency, with an option to force refresh. ```python import casabourse as cb # Récupération du buildId (utilisé automatiquement en interne) build_id = cb.get_build_id() print("BuildId actuel :", build_id) # Exemple de sortie : BuildId actuel : abc123xyz # Version avec cache (recommandée pour les appels fréquents) build_id_cached = cb.get_build_id_cached() print("BuildId (cache) :", build_id_cached) # Forcer le rafraîchissement du cache build_id_fresh = cb.get_build_id_cached(force_refresh=True) print("BuildId (forcé) :", build_id_fresh) ``` -------------------------------- ### Get Formatted Trading Volume Data Source: https://context7.com/fredysessie/casabourse/llms.txt Retrieves formatted daily trading volume data for a specified period. The output includes market central volume, block market volume, and total volume. Use this for displaying formatted trading data. ```python df_vol = cb.get_volume_data('2024-01-01', '2024-12-31', formatted=True) if df_vol is not None: print(f"Période : {df_vol['Séance'].min()} → {df_vol['Séance'].max()}") print(f"Nombre de séances : {len(df_vol)}") print(df_vol[['Séance', 'Volume Marché Central', 'Volume Marché De Blocs', 'Total']].head(5)) ``` -------------------------------- ### Get Index by Name or Code Source: https://context7.com/fredysessie/casabourse/llms.txt Fetches data for a specific stock market index using its full name or stock code. Useful for detailed index information. ```python import casabourse as cb # Recherche par nom masi = cb.get_index_by_name('MASI') if masi: print(f"Code : {masi['code_index']}") print(f"Valeur : {masi.get('field_index_value')}") print(f"URL : {masi['url_complete']}") ``` ```python # Recherche par code msi20 = cb.get_index_by_code('MSI20') if msi20: print(f"Nom complet : {msi20.get('index')}") print(f"Capitalisation : {msi20.get('field_market_capitalisation')}") ``` -------------------------------- ### Get Raw Trading Volume Data for Calculations Source: https://context7.com/fredysessie/casabourse/llms.txt Retrieves raw daily trading volume data for calculations. This version is suitable for performing statistical analysis like calculating the average daily volume. ```python # Version brute pour calculs df_raw = cb.get_volume_data('2024-01-01', '2024-12-31', formatted=False) volume_moyen = df_raw['Total'].mean() print(f"Volume moyen journalier : {volume_moyen:,.0f} MAD") ``` -------------------------------- ### Get Historical OHLCV Data Source: https://context7.com/fredysessie/casabourse/llms.txt Fetches historical Open, High, Low, Close, and Volume (OHLCV) data for a given instrument over a specified period. Supports automatic pagination. ```python import casabourse as cb import pandas as pd # Récupération de l'historique annuel d'IAM hist = cb.get_historical_data_auto('IAM', '2024-01-01', '2024-12-31') if hist is not None: print(f"Période : {hist['Date'].min()} → {hist['Date'].max()}") print(f"Nombre de séances : {len(hist)}") print(hist[['Date', 'Ouverture', 'Clôture', 'Plus haut', 'Plus bas', 'Volume']].head(5)) # Calcul de rendement simple hist = hist.sort_values('Date') rendement = (hist['Clôture'].iloc[-1] / hist['Clôture'].iloc[0] - 1) * 100 print(f"Rendement annuel : {rendement:.2f}%") # Sauvegarde hist.to_csv('historique_IAM_2024.csv', index=False, encoding='utf-8-sig') ``` -------------------------------- ### Get Historical Capitalization Data Source: https://context7.com/fredysessie/casabourse/llms.txt Retrieves historical global market capitalization data for a given date range. Use this to analyze trends in the overall market value. The output includes formatted capitalization for display and raw values for calculations. ```python import casabourse as cb df_cap = cb.get_capitalization_data('2024-01-01', '2024-12-31') if df_cap is not None: print(df_cap[['Séance', 'Capitalisation Formatée']].head(5)) # Statistiques descriptives stats = df_cap['Capitalisation (MAD)'].describe() print(f"Capitalisation minimale : {stats['min']:,.0f} MAD") print(f"Capitalisation maximale : {stats['max']:,.0f} MAD") print(f"Capitalisation moyenne : {stats['mean']:,.0f} MAD") # Sauvegarde df_cap.to_csv('capitalisation_2024.csv', index=False, encoding='utf-8-sig') ``` -------------------------------- ### Create and Activate Python Virtual Environment Source: https://github.com/fredysessie/casabourse/blob/main/README.md Use this command to create a new virtual environment for the project. Activate it using the appropriate command for your operating system. ```bash python -m venv venv ``` ```bash # Sur Windows : . venv\Scripts\activate ``` ```bash # Sur Unix/macOS source venv/bin/activate ``` -------------------------------- ### Get Main Stock Indices Data Source: https://context7.com/fredysessie/casabourse/llms.txt Retrieves data for the main stock indices (MASI, MASI 20, MASI ESG, MASI Mid and Small Cap). Use this to get specific information on the primary market indicators. The `formatted=True` argument ensures values are displayed in a readable format. ```python import casabourse as cb # Indices principaux df_main = cb.get_main_indices(formatted=True) if df_main is not None: print("=== INDICES PRINCIPAUX ===") print(df_main[['Indice', 'Valeur indice', 'Variation veille (%)', 'Variation annuelle (%)']].to_string(index=False)) ``` -------------------------------- ### Fetch Live Market Data Source: https://github.com/fredysessie/casabourse/blob/main/examples/example_notebook.ipynb Retrieves and displays the first few rows of live market data. Returns 'no data' if the market data is unavailable. ```python # Live market df = cb.get_live_market_data() display(df.head() if df is not None else 'no data') ``` -------------------------------- ### get_volume_overview() Source: https://context7.com/fredysessie/casabourse/llms.txt Provides an overview of the current trading session's volumes, returning five DataFrames: overall volume, top 10 active instruments, central market, block market, and other markets. ```APIDOC ## `get_volume_overview()` ### Description Returns five DataFrames describing the current session's volumes: overall volume, top 10 active instruments, central market, block market, and other markets. ### Method `get_volume_overview() -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame]` ### Parameters None ### Request Example ```python import casabourse as cb df_global, df_top, df_central, df_blocs, df_autres = cb.get_volume_overview() if df_global is not None: print("=== SESSION GLOBAL VOLUME ===") print(df_global.to_string(index=False)) print("\n=== TOP 10 ACTIVE INSTRUMENTS ===") print(df_top.to_string(index=False)) print("\n=== CENTRAL MARKET ===") print(df_central.to_string(index=False)) print("\n=== BLOCK MARKET ===") print(df_blocs.to_string(index=False)) ``` ### Response - **tuple[DataFrame, DataFrame, DataFrame, DataFrame, DataFrame]**: A tuple containing five pandas DataFrames for: Global Volume, Top 10 Instruments, Central Market, Block Market, and Other Markets. ``` -------------------------------- ### get_live_market_data() / get_live_market_data_auto() Source: https://context7.com/fredysessie/casabourse/llms.txt Retrieves comprehensive live stock market data from the Casablanca Stock Exchange, including prices, volumes, variations, and order book details. The `buildId` is automatically injected. ```APIDOC ## get_live_market_data() / get_live_market_data_auto() ### Description Fetches complete stock market data from the Casablanca Stock Exchange: prices, volumes, variations, order book, and full details per instrument. The `buildId` is automatically injected via the `@with_build_id` decorator. ### Usage ```python import casabourse as cb # Retrieve live data (with number formatting) df_live = cb.get_live_market_data(formatted=True) if df_live is not None: print(f"Number of instruments: {len(df_live)}") print(df_live[['Instrument', 'Dernier cours', 'Variation en %', 'Volume', 'Capitalisation']].head(5)) # Example output: # Instrument Dernier cours Variation en % Volume Capitalisation # 0 ATTIJARIWAFA BANK 549,00 +0.55% 12 345 678,00 131 000 000 000,00 # 1 MAROC TELECOM 143,90 -0.07% 5 678 901,00 89 000 000 000,00 # Save to CSV df_live.to_csv("marche_live.csv", index=False, encoding="utf-8-sig") print("Data saved to marche_live.csv") ``` ### Parameters - `formatted` (bool, optional): If True, formats numbers according to Moroccan financial standards. Defaults to False. ``` -------------------------------- ### get_all_indices_overview Source: https://context7.com/fredysessie/casabourse/llms.txt Fetches real-time data for all stock indices, including value, variation, and capitalization, grouped by category. ```APIDOC ## get_all_indices_overview(formatted=True) ### Description Fetches real-time data for all stock indices (value, variation, capitalization, high/low) grouped by category. ### Parameters #### Path Parameters - `formatted` (boolean) - Optional - If True, returns formatted data. Defaults to True. ### Request Example ```python import casabourse as cb indices_data = cb.get_all_indices_overview(formatted=True) ``` ### Response #### Success Response (200) - Returns data for all indices, typically requiring further processing (e.g., using `format_indices_to_dataframe`) to get a complete DataFrame. #### Response Example (after formatting) ``` Catégorie Indice Code_Index Valeur indice Variation veille (%) 0 Principaux indices MASI MASI 13 456 789,00 0.32 1 Principaux indices MASI 20 MSI20 11 234 567,00 0.55 ``` ``` -------------------------------- ### Get Top and Worst Performing Indices Source: https://context7.com/fredysessie/casabourse/llms.txt Ranks indices by performance over a specified period (daily or annual). Use to identify market leaders and laggards. ```python import casabourse as cb # Top 5 indices par performance du jour top = cb.get_top_performers(n=5, period='veille') if top is not None: print("=== TOP 5 INDICES DU JOUR ===") print(top.to_string(index=False)) ``` ```python # Top 3 indices par performance annuelle top_annuel = cb.get_top_performers(n=3, period='annuelle') print("\n=== TOP 3 INDICES ANNUELS ===") print(top_annuel[['Indice', 'Code_Index', 'Variation annuelle (%)']]) ``` ```python # Pires performeurs (risque/alerte) worst = cb.get_worst_performers(n=5, period='veille') print("\n=== INDICES EN DIFFICULTÉ ===") print(worst[['Indice', 'Variation veille (%)']]) ``` -------------------------------- ### casabourse.get_capitalization_overview Source: https://github.com/fredysessie/casabourse/blob/main/docs/api.md Retrieves an overview of capitalization data. ```APIDOC ## casabourse.get_capitalization_overview(*args, **kwargs) ### Description Retrieves an overview of capitalization data. ### Parameters None ### Returns None ``` -------------------------------- ### Get Most Active Stocks Source: https://context7.com/fredysessie/casabourse/llms.txt Retrieves the top 10 most active stocks, either by traded volume or number of transactions. Requires the 'casabourse' library to be imported. ```python import casabourse as cb # Top 10 par volume échangé (par défaut) df_volume = cb.get_most_active(limit=10, by='volume') print("=== PLUS ACTIFS PAR VOLUME ===") print(df_volume) # Top 10 par nombre de transactions df_tx = cb.get_most_active(limit=10, by='transactions') print("=== PLUS ACTIFS PAR TRANSACTIONS ===") print(df_tx[['Symbole', 'Nom', 'Cours courant', 'Volume échangé', 'Nombre transactions']]) ``` -------------------------------- ### casabourse.get_available_instrument Source: https://github.com/fredysessie/casabourse/blob/main/docs/api.md Returns the complete list of available instruments in Casabourse. ```APIDOC ## casabourse.get_available_instrument() ### Description Returns the complete list of available instruments in Casabourse. Columns: Nom, Symbole, Instrument_id, Secteur ### Returns None ``` -------------------------------- ### get_capitalization_overview Source: https://context7.com/fredysessie/casabourse/llms.txt Returns an overview of current capitalization, including global capitalization, top 10 companies, and sectorial capitalization. ```APIDOC ## get_capitalization_overview(formatted=True) ### Description Returns a dictionary containing three DataFrames: current global capitalization, top 10 most capitalized companies, and capitalization by sector. ### Parameters #### Path Parameters - `formatted` (boolean) - Optional - If True, returns formatted data. Defaults to True. ### Request Example ```python import casabourse as cb cap = cb.get_capitalization_overview(formatted=True) ``` ### Response #### Success Response (200) - Returns a dictionary with keys 'global_cap', 'top_10', and 'sectorial', each containing a pandas DataFrame. #### Response Example ```json { "global_cap": "DataFrame for global capitalization", "top_10": "DataFrame for top 10 companies", "sectorial": "DataFrame for sectorial capitalization" } ``` ``` -------------------------------- ### get_market_summary() Source: https://context7.com/fredysessie/casabourse/llms.txt Provides a global market summary including key indicators like total capitalization, average variations, and top/bottom performers. ```APIDOC ## get_market_summary() ### Description Provides a global market summary with key indicators: total capitalization, average variations, and the best and worst performers of the day. ### Method `get_market_summary()` ### Parameters None ### Response Returns a dictionary containing market summary information, including 'date_heure', 'Nombre total instruments', 'Instruments en hausse', 'Instruments en baisse', 'Volume total échangé', and 'Capitalisation totale'. ### Request Example ```python import casabourse as cb summary = cb.get_market_summary() if summary: print(f"Date : {summary['date_heure']}") print(f"Nombre d'instruments : {summary['Nombre total instruments']}") print(f"En hausse : {summary['Instruments en hausse']}") print(f"En baisse : {summary['Instruments en baisse']}") print(f"Volume total : {summary['Volume total échangé']:,.0f} MAD") print(f"Capitalisation totale : {summary['Capitalisation totale']:,.0f} MAD") ``` ### Response Example ``` Date : 2025-01-15 10:30:00 Nombre d'instruments : 75 En hausse : 42 En baisse : 21 Volume total : 450 234 567 MAD Capitalisation totale : 1 234 567 890 000 MAD ``` ``` -------------------------------- ### get_available_instrument() Source: https://context7.com/fredysessie/casabourse/llms.txt Retrieves a comprehensive list of all available instruments (stocks) on the Casablanca Stock Exchange, along with their associated metadata. ```APIDOC ## `get_available_instrument()` ### Description Returns the complete list of available instruments (stocks) on the Casablanca Stock Exchange with their metadata. ### Method `get_available_instrument()` ### Parameters None ### Request Example ```python import casabourse as cb df_instruments = cb.get_available_instrument() if df_instruments is not None: print(f"Nombre total d'instruments : {len(df_instruments)}") print(df_instruments.head(10)) ``` ### Response - **DataFrame**: A pandas DataFrame containing instrument details like Name, Symbol, Instrument_id, and Sector. ``` -------------------------------- ### get_index_composition() / get_index_composition_batch() Source: https://context7.com/fredysessie/casabourse/llms.txt Retrieves the list of instruments constituting a given index with their real-time market data. ```APIDOC ## get_index_composition() / get_index_composition_batch() ### Description Retrieves the list of instruments constituting a given index with their real-time market data. ### Method GET (implied) ### Endpoint Not specified, typically a function call in the SDK. ### Parameters - **index_code** (string) - Required - The stock code of the index (e.g., 'MSI20'). - **formatted** (boolean) - Optional - Whether to return formatted data. - **verify_index** (boolean) - Optional - Whether to verify the index. - **indices_codes** (list of strings) - Required for batch - A list of index codes. ### Request Example ```python import casabourse as cb # Composition du MSI20 df_comp = cb.get_index_composition('MSI20', formatted=True, verify_index=True) # Récupération en lot pour plusieurs indices batch = cb.get_index_composition_batch(['MSI20', 'MASI', 'BANK'], formatted=True) # Tous les indices principaux en une fois all_comp = cb.get_composition_for_main_indices(formatted=True) ``` ### Response #### Success Response - **Société** (string) - The name of the company. - **Ticker** (string) - The stock ticker. - **Dernier cours** (float) - The last trading price. - **Variation (%)** (float) - The percentage change. - **Capitalisation** (float) - The market capitalization. ``` -------------------------------- ### casabourse.get_market_summary Source: https://github.com/fredysessie/casabourse/blob/main/docs/api.md Retrieves a market summary with key indicators. ```APIDOC ## casabourse.get_market_summary ### Description Récupère un résumé du marché avec les indicateurs clés. ### Parameters **formatted** (*bool*) – Si True, formate les nombres avec des espaces pour les milliers ### Returns Résumé du marché avec les indicateurs clés ### Return type dict ``` -------------------------------- ### Get Indices List with Capitalization Source: https://context7.com/fredysessie/casabourse/llms.txt Retrieves filtered lists of indices, either the complete list with capitalization or a restricted list of indices with non-zero capitalization. Useful for obtaining index compositions. ```APIDOC ## `get_indices_list_with_capitalization()` / `get_available_indices_for_composition()` — Filtered Lists ### Description Returns synthetic views of indices: a complete list with capitalization or a restricted list of indices with non-zero capitalization (useful for `get_index_composition`). ### Method `get_indices_list_with_capitalization(formatted=True)` `get_available_indices_for_composition()` ### Parameters #### `get_indices_list_with_capitalization` - **formatted** (bool) - Optional - If True, returns human-readable strings; otherwise, returns raw numerical values. ### Request Example ```python import casabourse as cb # Complete list of indices with capitalization, sorted by descending capitalization df_list = cb.get_indices_list_with_capitalization(formatted=True) if df_list is not None: print(df_list[['Indice', 'Code_Index', 'Capitalisation (MAD)', 'Catégorie']].head(10)) # Available indices for composition retrieval (capitalization > 0) available = cb.get_available_indices_for_composition() if available is not None: print(f"{len(available)} indices disponibles pour composition") # Typical usage: iterate to retrieve all compositions for _, row in available.head(3).iterrows(): print(f" → {row['Code_Index']} : {row['Capitalisation (MAD)']} MAD") ``` ### Response #### Success Response - Returns a pandas DataFrame containing index information. #### Response Example ``` Indice Code_Index Capitalisation (MAD) Catégorie 0 MASI XCAS 732456789012.00 Indices de référence 1 MSI20 XMSI 89000000000.00 Indices sectoriels ... ``` ``` 3 indices disponibles pour composition → MASI : 732 456 789 012,00 MAD → MSI20 : 89 000 000 000,00 MAD ``` ``` -------------------------------- ### Get Symbol ID from Ticker Source: https://context7.com/fredysessie/casabourse/llms.txt Resolves a stock ticker symbol to its internal Drupal ID, which is necessary for fetching historical data. Supports automatic ID management and batch retrieval. ```python import casabourse as cb # Recherche automatique (buildId géré en interne) symbol_id = cb.get_symbol_id_from_ticker_auto('IAM') print(f"ID du ticker IAM : {symbol_id}") # Recherche de plusieurs tickers en une passe ids = cb.get_multiple_symbol_ids(['AFM', 'IAM', 'ATW']) print("IDs récupérés :") for ticker, sid in ids.items(): statut = "✅" if sid else "❌" print(f" {statut} {ticker} → {sid}") ``` -------------------------------- ### Listing Available Instruments and Indices Source: https://github.com/fredysessie/casabourse/blob/main/README.md Provides functions to retrieve lists of available instruments and indices supported by Casabourse. ```APIDOC ## Listing Available Instruments and Indices ### Description Easily obtain a comprehensive list of all available instruments and indices within the Casabourse system. ### Code Examples ```python import casabourse as cb # List of available instruments df_instruments = cb.get_available_instrument() print(df_instruments.head()) # List of available indices df_indices = cb.get_available_indexes() print(df_indices.head()) ``` ``` -------------------------------- ### casabourse.get_all_indices_overview Source: https://github.com/fredysessie/casabourse/blob/main/docs/api.md Retrieves an overview of all indices from the Casablanca Stock Exchange. ```APIDOC ## casabourse.get_all_indices_overview(formatted=True) ### Description Retrieves an overview of all indices from the Casablanca Stock Exchange. ### Parameters #### Path Parameters - **formatted** (bool) - Optional - If True, formats numbers with spaces for thousands ### Returns Dictionary with data of all indices grouped by category ### Return type dict ``` -------------------------------- ### Get Available Stock Indices Source: https://context7.com/fredysessie/casabourse/llms.txt Retrieves a list of all available stock indices, including their category, code, and internal ID. This is useful for understanding the scope of available indices before querying specific data. ```python import casabourse as cb df_indices = cb.get_available_indexes() if df_indices is not None: print(f"Nombre total d'indices : {len(df_indices)}") print(df_indices.head(10)) ``` -------------------------------- ### Get Historical Intraday Index Data Source: https://context7.com/fredysessie/casabourse/llms.txt Retrieves historical index values for a specific date, aggregated by time periods (15 min, 1 hour, 3 hours, or daily). Useful for intraday analysis. ```python import casabourse as cb from datetime import datetime today = datetime.now().strftime('%Y-%m-%d') # Données MASI 20 par code, agrégées par heure df_h = cb.get_index_data_by_code('MSI20', today, periode='1H', formatted=False) if df_h is not None: print(f"Points de données (1H) : {len(df_h)}") print(df_h[['datetime', 'index_value']].head()) ``` ```python # Données MASI 20 par nom, agrégées toutes les 15 minutes df_15m = cb.get_index_data_by_name('MASI 20', today, periode='15M', formatted=True) if df_15m is not None: print(f"Points de données (15M) : {len(df_15m)}") print(df_15m.head(8)) ``` -------------------------------- ### get_market_data() Source: https://context7.com/fredysessie/casabourse/llms.txt Retrieves simplified market data from the `/api/bourse/dashboard/ticker` endpoint, offering faster access than `get_live_market_data` but without full instrument details. ```APIDOC ## get_market_data() ### Description Fetches market data from the `/api/bourse/dashboard/ticker` endpoint, which is faster than `get_live_market_data` but lacks the complete details for each instrument. ### Usage ```python import casabourse as cb # Main market (marche=59, classes=50 by default) df = cb.get_market_data(marche=59, classes=[50]) if df is not None: print(df[['Symbole', 'Nom', 'Cours courant', 'Variation %', 'Volume échangé', 'Secteur']].head(10)) # Output: # Symbole Nom Cours courant Variation % Volume échangé Secteur # 0 IAM Maroc Telecom SA 143.90 -0.07 5678901.00 Télécommunications # 1 ATW Attijariwafa Bank 549.00 0.55 12345678.00 Banques ``` ### Parameters - `marche` (int, optional): The market identifier. Defaults to 59. - `classes` (list[int], optional): A list of class identifiers. Defaults to [50]. ```