### Run Linux Installer Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/assets/Vnstock_Insider_Package_Setup_Colab.ipynb Executes the 'linux_installer.run' script to install the vnstock package. This is the final step in the setup process. ```python !./linux_installer.run ``` -------------------------------- ### Navigate to Installer Directory Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/assets/Vnstock_Insider_Package_Setup_Colab.ipynb Changes the current working directory to the 'oneclick_installer' folder within the cloned vnstock_insider_guide repository. This directory contains the installation script. ```python %cd /content/vnstock_insider_guide/oneclick_installer ``` -------------------------------- ### Clone vnstock_insider_guide Repository Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/assets/Vnstock_Insider_Package_Setup_Colab.ipynb Clones the vnstock_insider_guide repository from GitHub to the Colab environment. This is the first step to get the necessary files for the package setup. ```python !git clone https://github.com/vnstock-hq/vnstock_insider_guide ``` -------------------------------- ### Grant Execute Permissions to Installer Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/assets/Vnstock_Insider_Package_Setup_Colab.ipynb Grants execute permissions to the 'linux_installer.run' file. This is a necessary step before running the installer script to ensure it can be executed. ```python !chmod +x linux_installer.run ``` -------------------------------- ### Initialize CommodityPrice API (Python) Source: https://context7.com/vnstock-hq/vnstock_insider_guide/llms.txt Initializes the CommodityPrice API with a specified start and end date for fetching commodity data. This setup is necessary before querying specific commodity prices. ```python from vnstock_data import CommodityPrice # Khởi tạo với khoảng thời gian commodity = CommodityPrice( start="2022-01-03", end="2024-12-31" ) ``` -------------------------------- ### Execute Vnstock macOS Installation Script Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/README.md This command executes the 'oneclick_python_vnstock3_macos.sh' installation script on macOS. Ensure you have already navigated to the correct directory and granted execute permissions to the script. ```shell ./oneclick_python_vnstock3_macos.sh ``` -------------------------------- ### Initialize Market API (Python) Source: https://context7.com/vnstock-hq/vnstock_insider_guide/llms.txt Initializes the Market API for different Vietnamese stock exchanges: HNX, HOSE (VNINDEX), and UPCOM. This setup allows for fetching market-specific valuation data. ```python from vnstock_data import Market # Khởi tạo với chỉ số thị trường market_hnx = Market(index='HNXINDEX') market_hose = Market(index='VNINDEX') market_upcom = Market(index='UPCOM') ``` -------------------------------- ### Fetch and Display Company Officer Information with vnstock Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/1_1_vnstock_data_explorer_v2_wrapper.ipynb This snippet fetches and displays information about company officers using the vnstock library. It calls `c.officers()` to get the data and then uses `display()` to show the initial rows of the DataFrame. This function requires the vnstock library to be installed and a client `c` to be initialized. ```python print("\n=== Company.officers ===") print(c.officers()) ``` -------------------------------- ### Install vnstock in Github Codespace using Shell Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/1_1_vnstock_data_explorer_v2_wrapper.ipynb Clones the vnstock_insider_guide repository, changes directory, makes the installer executable, and runs the installation script. This is intended for use within a Github Codespace terminal. ```shell git clone https://github.com/vnstock-hq/vnstock_insider_guide %cd vnstock_insider_guide/oneclick_installer chmod +x linux_installer.run ./linux_installer.run ``` -------------------------------- ### Navigate to Downloads Directory on macOS Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/README.md This command changes the current directory to 'Downloads'. It is a prerequisite for executing installation scripts located in the Downloads folder on macOS. Ensure you have downloaded the installation file to this directory. ```shell cd Downloads ``` -------------------------------- ### Install vnstock Library in Google Colab Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/2-vnstock_ta-demo.ipynb This snippet shows how to clone the vnstock_insider_guide repository, navigate to the installer directory, grant execution permissions, and run the installation script. It requires restarting the Colab session after installation. ```bash !git clone https://github.com/vnstock-hq/vnstock_insider_guide %cd /content/vnstock_insider_guide/oneclick_installer !chmod +x linux_installer.run !./linux_installer.run ``` -------------------------------- ### Install vnstock in Google Colab using Python Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/1_1_vnstock_data_explorer_v2_wrapper.ipynb Clones the vnstock_insider_guide repository into the Colab environment, changes the directory, grants execute permissions to the installer script, and prepares it for execution. This code is designed to be run directly within a Colab notebook cell. ```python # Sao chép mã nguồn từ GitHub về Google Colab !git clone https://github.com/vnstock-hq/vnstock_insider_guide # Chuyển đến thư mục vừa clone %cd /content/vnstock_insider_guide/oneclick_installer # Trao quyền thực thi cho file !chmod +x linux_installer.run ``` -------------------------------- ### Initialize vnstock Async Batch Crawler Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/4-vnstock_news_v2.1_demo.ipynb This Python code demonstrates the initialization of logging and essential components for the vnstock news crawler. It sets up a logger and imports necessary classes for asynchronous crawling, site configuration, and sitemap resolution. This serves as a setup for more advanced news updating functionalities. ```python import os import pandas as pd import logging import asyncio from vnstock_news.async_crawlers.async_batch import AsyncBatchCrawler from vnstock_news.config.sites import SITES_CONFIG from vnstock_news.utils.logger import setup_logger from vnstock_news.config.sitemap_resolver import DynamicSitemapResolver # Khởi tạo logger logger = setup_logger("export_feed_info", debug=True) ``` -------------------------------- ### Grant Execution Permissions for macOS Installer Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/README.md This command grants execute permissions to the 'oneclick_python_vnstock3_macos.sh' script. This is necessary on macOS to allow the shell to run the installation script. The script is used for installing Vnstock on macOS. ```shell chmod +x oneclick_python_vnstock3_macos.sh ``` -------------------------------- ### Install vnstock Library using Linux Installer Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/3-vnstock_pipeline_v2_demo.ipynb This code snippet demonstrates how to install the vnstock library on a Google Colab environment by cloning the repository, navigating to the installer directory, granting execute permissions, and running the installer script. It requires a restart of the Colab session after installation. ```python # Sao chép mã nguồn từ GitHub về Google Colab !git clone https://github.com/vnstock-hq/vnstock_insider_guide # Chuyển đến thư mục vừa clone %cd /content/vnstock_insider_guide/oneclick_installer # Trao quyền thực thi cho file !chmod +x linux_installer.run # Chạy trình cài đặt !./linux_installer.run ``` -------------------------------- ### Initialize Crawler and Get Article Details (Python) Source: https://context7.com/vnstock-hq/vnstock_insider_guide/llms.txt Demonstrates how to initialize a crawler for specific websites (CafeF, VNExpress) and extract details of a single article using its URL. The output is a dictionary containing title, content, author, publish date, and the original URL. ```python from vnstock_news.core.crawler import Crawler # Khởi tạo crawler cho CafeF cafef_crawler = Crawler("cafef") sample_url = "https://cafef.vn/dragon-capital-ky-vong-trien-khai-he-thong-krx-va-tien-trinh-nang-hang-thi-truong-se-thu-hut-them-nha-dau-tu-chung-khoan-188241215221837066.chn" article_cafef = cafef_crawler.get_article_details(sample_url) # Kết quả: Dictionary chứa thông tin bài viết # - title: Tiêu đề # - content: Nội dung đầy đủ # - author: Tác giả # - publish_date: Ngày xuất bản # - url: Link gốc print(f"Tiêu đề: {article_cafef['title']}") print(f"Ngày: {article_cafef['publish_date']}") print(f"Nội dung: {article_cafef['content'][:200]}...") # Khởi tạo crawler cho VNExpress vnexpress_crawler = Crawler("vnexpress") sample_url_vne = "https://vnexpress.net/bi-thu-tinh-uy-vinh-phuc-chon-can-bo-tam-huyet-uy-tin-sau-tinh-gon-4828307.html" article_vne = vnexpress_crawler.get_article_details(sample_url_vne) print(f"\nVNExpress - {article_vne['title']}") ``` -------------------------------- ### Get Market Comprehensive Evaluation (Python) Source: https://context7.com/vnstock-hq/vnstock_insider_guide/llms.txt Fetches a comprehensive market evaluation including P/E, P/B ratios, market capitalization, liquidity, and other valuation indicators over a specified duration (e.g., 5 months). The result is a DataFrame containing these metrics. ```python # Lấy các chỉ số đánh giá thị trường trong 5 tháng evaluation = market_hose.evaluation(duration='5M') # Kết quả: DataFrame với nhiều chỉ số định giá # - P/E, P/B # - Vốn hóa thị trường # - Thanh khoản # - Và các chỉ số khác print(evaluation) ``` -------------------------------- ### Retrieve and Display Stock Listings (Python) Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/1_1_vnstock_data_explorer_v2_wrapper.ipynb Demonstrates how to use the Listing module to fetch stock symbols. It shows how to get all symbols, symbols by exchange, symbols by group (e.g., VN30), and industry classifications based on ICB codes. Results are displayed as pandas DataFrames. ```python print("=== Listing.all_symbols ===") lst = Listing(source="vci", random_agent=False, show_log=False) df_all = lst.all_symbols(to_df=True) display(df_all.head()) print("\n=== Listing.symbols_by_exchange ===") df_ex = lst.symbols_by_exchange(lang="en") display(df_ex.head()) print("=== Listing.symbols_by_group (VN30) ===") df_grp = lst.symbols_by_group(group="VN30") display(df_grp.head()) print("=== Listing.industries_icb ===") df_icb = lst.industries_icb() display(df_icb.head()) ``` -------------------------------- ### Get Stock Price History with vnstock Python Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/1-vnstock_data_explorer_v2_demo.ipynb This Python code snippet demonstrates how to initialize the Trading class from the vnstock_data library to fetch historical price data for a specific stock symbol ('MSN') from a given source ('VCI') within a defined date range. It requires the vnstock_data library to be installed. ```python from vnstock_data import Trading trading = Trading(symbol='MSN', source='VCI') START_DATE = '2024-01-02' END_DATE = '2024-11-08' trading.price_history(start=START_DATE, end=END_DATE) ``` -------------------------------- ### Example RSS Feed Data Structure Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/4-vnstock_news_v2.1_demo.ipynb This shows an example of the data structure returned after fetching an RSS feed using the `vnstock-news` library. Each item in the list represents a news article, containing its link, title, a brief description, and the publication time. This structure is useful for further processing or displaying the news content. ```json [ { "link": "https://vnexpress.net/di-chuyen-mot-que-diem-de-sua-phep-tinh-sai-4931779.html", "title": "Di chuyển một que diêm để sửa phép tính sai", "description": "Nghe đơn giản, nhưng tin mình đi, hơn 90% người thử đều phải vò đầu bứt tai, thậm chí 'cà khịa chính mình' vì… nghĩ mãi không ra.", "publish_time": "Sun, 31 Aug 2025 14:00:00 +0700" }, { "link": "https://vnexpress.net/nt-logistics-ra-mat-dich-vu-dinh-tuyen-giup-cat-giam-phi-van-tai-4932052.html", "title": "NT Logistics ra mắt dịch vụ định tuyến giúp cắt giảm phí vận tải", "description": "Dịch vụ RaaS+ của NT Logistics giúp tối ưu đội xe và nâng cao hiệu quả giao hàng nhờ kết hợp công nghệ định tuyến với chuyên gia.", "publish_time": "Sun, 31 Aug 2025 14:00:00 +0700" }, { "link": "https://vnexpress.net/le-hoang-phuong-dien-vay-20-kg-lam-vedette-4933708.html", "title": "Lê Hoàng Phương diện váy 20 kg làm vedette", "description": "Hoa hậu Lê Hoàng Phương diễn đầm dạ hội \"Mảnh sáng lấp lánh\" với trọng lượng lớn của nhà thiết kế Thanh Hương Bùi.", "publish_time": "Sun, 31 Aug 2025 13:35:15 +0700" }, { "link": "https://vnexpress.net/tong-bi-thu-dang-huong-tai-noi-chu-tich-ho-chi-minh-viet-tuyen-ngon-doc-lap-4933707.html", "title": "Tổng Bí thư dâng hương tại nơi Chủ tịch Hồ Chí Minh viết Tuyên ngôn độc lập", "description": "Sáng 31/8, Tổng Bí thư Tô Lâm đến dâng hương tưởng niệm Chủ tịch Hồ Chí Minh tại nhà số 48 Hàng Ngang, phường Hoàn Kiếm." } ] ``` -------------------------------- ### List Supported News Sites (Python) Source: https://context7.com/vnstock-hq/vnstock_insider_guide/llms.txt Retrieves a list of supported news websites from which market news can be scraped. The output is a list of dictionaries, each containing the site's name and domain. ```python from vnstock_news import list_supported_sites # Lấy danh sách các trang tin được hỗ trợ sites = list_supported_sites() # Kết quả: List of dictionaries với name và domain # [ # {'name': 'cafef', 'domain': 'cafef.vn'}, # {'name': 'cafebiz', 'domain': 'cafebiz.vn'}, # {'name': 'vietstock', 'domain': 'vietstock.vn'}, # {'name': 'vneconomy', 'domain': 'vneconomy.vn'}, # {'name': 'plo', 'domain': 'plo.vn'}, # {'name': 'vnexpress', 'domain': 'vnexpress.net'}, # {'name': 'tuoitre', 'domain': 'tuoitre.vn'}, # ... và nhiều trang khác # ] for site in sites: print(f"{site['name']}: {site['domain']}") ``` -------------------------------- ### Finance API - VCI Source Source: https://context7.com/vnstock-hq/vnstock_insider_guide/llms.txt Initializes the Finance API using the VCI data source for accessing financial statement data. This API is intended for sponsored members. ```APIDOC ## POST /api/finance/vci/initialize ### Description Initializes the Finance API client using the VCI data source. This endpoint is part of the financial data retrieval module and is intended for sponsored members requiring access to financial statements and related data with higher limits. ### Method POST ### Endpoint /api/finance/vci/initialize ### Parameters No specific parameters are required for initialization at the endpoint level. Initialization is typically done via the SDK as shown in the example. ### Request Example ```python from vnstock_data.explorer.vci import Finance # Initialize Finance API from VCI source finance = Finance() # Subsequent calls would use the 'finance' object to fetch data. # Example: finance.financial_reports(symbol='FPT', report_type='quarterly') ``` ### Response #### Success Response (200) - **Object** - An initialized `Finance` object ready to make requests. #### Response Example (The response is the initialized Python object, not a typical JSON response for this type of SDK initialization.) ```python # Successful initialization returns a Finance object ``` ``` -------------------------------- ### Initialize VNExpress Crawler in Python Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/4-vnstock_news_v2.1_demo.ipynb This Python snippet demonstrates how to initialize a Crawler object for the VNExpress news source using the vnstock_news library. It requires the vnstock_news library to be installed. ```python from vnstock_news.core.crawler import Crawler # Initialize Crawler for VNExpress vneconomy_crawler = Crawler("vneconomy") ``` -------------------------------- ### Fetch Proprietary Trading Data with vnstock Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/1-vnstock_data_explorer_v2_demo.ipynb Retrieves proprietary trading statistics for a specified date range. Requires start and end dates as input. Outputs a pandas DataFrame containing detailed trading volumes and values. ```python trading.prop_trade(start=START_DATE, end=END_DATE) ``` -------------------------------- ### Fetch Gold Prices with vnstock CommodityPrice Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/1_1_vnstock_data_explorer_v2_wrapper.ipynb Retrieves gold prices, both for Vietnam and globally, using the CommodityPrice adapter. Allows specifying the data source, start and end dates. Outputs a pandas DataFrame with price data. ```python # 1. Instantiate the adapter (adjust start/end dates as needed) c = CommodityPrice(source="spl", start="2024-01-01", end="2025-04-18", show_log=False) # 2. Uncomment the method call(s) you want to test: df = c.gold_vn() # df = c.gold_global() ``` -------------------------------- ### Crawl News using vnstock CLI Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/4-vnstock_news_v2.1_demo.ipynb This command-line snippet instructs users to change the directory to where they want to save news data and then execute the `vnstock-news-crawl` command. This is typically used after installing the library to initiate news crawling. ```shell # Chuyển thư mục làm việc về nơi bạn muốn lưu dữ liệu tin tức %cd /content !vnstock-news-crawl ``` -------------------------------- ### Get Market Valuation Metrics with vnstock Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/1-vnstock_data_explorer_v2_demo.ipynb Retrieves comprehensive market valuation metrics, including PE and PB ratios, for a specified duration. This method aggregates multiple valuation indicators. Requires a duration string (e.g., '5M'). ```python market.evaluation(duration='5M') ``` -------------------------------- ### Fetch Historical Stock Data with vnstock Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/1-vnstock_data_explorer_v2_demo.ipynb Retrieves historical stock data for a given symbol and date range. Requires the vnstock_data.explorer.vci.Quote module. It takes a symbol, start date, end date, and interval as input, returning a pandas DataFrame with time, open, high, low, close, and volume. ```python from vnstock_data.explorer.vci import Quote quote = Quote(symbol='REE') quote.history(start='2000-07-28', end='2024-08-31', interval='1D') ``` -------------------------------- ### Initialize News Crawler (Python) Source: https://context7.com/vnstock-hq/vnstock_insider_guide/llms.txt Initializes the Crawler class from vnstock_news.core.crawler, which is used for fetching detailed news articles from supported websites. ```python from vnstock_news.core.crawler import Crawler ``` -------------------------------- ### Khởi tạo TopStock API Source: https://context7.com/vnstock-hq/vnstock_insider_guide/llms.txt Khởi tạo đối tượng TopStock để truy cập các API liên quan đến top cổ phiếu theo các tiêu chí khác nhau. ```python from vnstock_data import TopStock # Khởi tạo đối tượng TopStock top = TopStock() ``` -------------------------------- ### Fetch and Display Company News and Events with vnstock Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/1_1_vnstock_data_explorer_v2_wrapper.ipynb This snippet demonstrates how to fetch company news and events using the vnstock library. It initializes a client, retrieves news and events data, and displays the head of the resulting DataFrames. No external dependencies are required beyond the vnstock library and pandas. ```python print("\n=== Company.news ===") df_news = c.news() display(df_news.head()) print("\n=== Company.events ===") df_evt = c.events() display(df_evt.head()) ``` -------------------------------- ### Get Insider Trading Deals - Python Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/1-vnstock_data_explorer_v2_demo.ipynb Retrieves a list of insider trading deals within a specified date range. It requires the 'vnstock' library and takes 'start' and 'end' dates as input. The output is a pandas DataFrame containing detailed information about each trade. ```python trading.insider_deal(start='2024-01-02', end=END_DATE) ``` -------------------------------- ### Get Top Stocks by Deals (Python) Source: https://context7.com/vnstock-hq/vnstock_insider_guide/llms.txt Retrieves a list of stocks with the highest number of transactions. The output is a DataFrame sorted by transaction volume, reflecting investor interest. ```python # Lấy danh sách cổ phiếu có số lệnh khớp nhiều nhất top_by_deals = top.deal() # Kết quả: DataFrame sắp xếp theo số lượng giao dịch # Phản ánh sự quan tâm của nhà đầu tư print(top_by_deals.head(10)) ``` -------------------------------- ### Fetch Company News Details with vnstock Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/1_1_vnstock_data_explorer_v2_wrapper.ipynb This code retrieves detailed news information for a company using the vnstock library. It calls `c.news()` and then prints the result. The output includes news titles, dates, sources, and content. This function requires the vnstock library and a pre-initialized client `c`. ```python print("\n=== Company.news ===") print(c.news()) ``` -------------------------------- ### Initialize Market Data Object with vnstock Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/1-vnstock_data_explorer_v2_demo.ipynb Initializes a Market object to retrieve data for a specific stock index. Requires the 'vnstock_data' library. The index parameter specifies which market index to track. ```python from vnstock_data import Market market = Market(index='HNXINDEX') ``` -------------------------------- ### Get Agricultural Product Prices (Python) Source: https://context7.com/vnstock-hq/vnstock_insider_guide/llms.txt Fetches time series data for agricultural commodities such as Ure fertilizer, soybeans, corn, and sugar. The output for each is a DataFrame containing the price history. ```python # Giá phân bón Ure fertilizer_ure = commodity.fertilizer_ure() print("Giá phân Ure:") print(fertilizer_ure.tail()) # Giá đậu nành soybean = commodity.soybean() print("Giá đậu nành:") print(soybean.tail()) # Giá ngô corn = commodity.corn() print("Giá ngô:") print(corn.tail()) # Giá đường sugar = commodity.sugar() print("Giá đường:") print(sugar.tail()) ``` -------------------------------- ### Get Energy Prices (Python) Source: https://context7.com/vnstock-hq/vnstock_insider_guide/llms.txt Fetches time series data for various energy commodities, including Vietnamese RON92 gasoline, global crude oil, and natural gas prices. The output for each is a DataFrame. ```python # Giá xăng Việt Nam (RON92) gas_vn = commodity.gas_vn() print("Giá xăng Việt Nam:") print(gas_vn.tail()) # Giá dầu thô thế giới (Crude Oil) oil_crude = commodity.oil_crude() print("Giá dầu thô:") print(oil_crude.tail()) # Giá khí đốt tự nhiên gas_natural = commodity.gas_natural() print("Giá khí đốt:") print(gas_natural.tail()) ``` -------------------------------- ### Fetch Company Subsidiaries with vnstock Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/1_1_vnstock_data_explorer_v2_wrapper.ipynb This code snippet demonstrates how to fetch a company's subsidiaries using the vnstock library. It calls the `c.subsidiaries()` method. The output is displayed directly, showing an empty DataFrame in this specific case, indicating no subsidiaries were found or the function returned an empty result. Ensure the vnstock library is installed. ```python print("\n=== Company.subsidiaries ===") print(c.subsidiaries()) ``` -------------------------------- ### Import vnstock Data Modules (Python) Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/1_1_vnstock_data_explorer_v2_wrapper.ipynb Imports essential data modules from the vnstock library, including Quote, Trading, Finance, Listing, Company, CommodityPrice, and Macro. These modules are the primary interfaces for accessing different types of financial data. ```python from IPython.display import display from vnstock_data import Quote, Trading, Finance, Listing, Company, CommodityPrice, Macro ``` -------------------------------- ### Get Insider Deal Information in Python Source: https://context7.com/vnstock-hq/vnstock_insider_guide/llms.txt Retrieves information on insider deals, including transactions made by executives and major shareholders. This data helps in tracking the activities of individuals with privileged information about a company. ```python # Lấy thông tin giao dịch của cổ đông nội bộ insider_df = trading.insider_deal(start='2024-01-02', end=END_DATE) # Kết quả: DataFrame chứa thông tin # - Người thực hiện giao dịch (executives, major shareholders) # - Loại giao dịch (mua/bán) # - Số lượng cổ phiếu # - Thời gian thực hiện # Hữu ích để theo dõi hành vi của người trong cuộc print(insider_df) ``` -------------------------------- ### Get Proprietary Trade Data in Python Source: https://context7.com/vnstock-hq/vnstock_insider_guide/llms.txt Fetches proprietary trading data, detailing the trading activities of securities firms. This information can be used to analyze institutional trading behavior and potential market influences. ```python # Thống kê giao dịch tự doanh của công ty chứng khoán prop_df = trading.prop_trade(start=START_DATE, end=END_DATE) # Kết quả: DataFrame với khối lượng và giá trị giao dịch tự doanh # Hữu ích để phân tích xu hướng của các tổ chức print(prop_df.head()) ``` -------------------------------- ### Fetch and Display Company Shareholder Information with vnstock Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/1_1_vnstock_data_explorer_v2_wrapper.ipynb This code retrieves and displays the top shareholders of a company using the vnstock library. It calls the `c.shareholders()` method and then uses `display()` to show the first few rows of the resulting DataFrame. Ensure the vnstock library is installed and a client instance `c` is available. ```python print("\n=== Company.shareholders ===") print(c.shareholders()) ``` -------------------------------- ### Get Annual Financial Plan Data with vnstock Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/1-vnstock_data_explorer_v2_demo.ipynb Retrieves the annual financial plan for a company using the vnstock Python library. It requires the 'vnstock' library to be installed. The function `fin.annual_plan` takes a language parameter 'lang' to specify the output language. ```python import vnstock # Fetch the annual financial plan in Vietnamese annual_plan_data = vnstock.fin.annual_plan(lang='vi') # Display the first 5 rows of the data print(annual_plan_data.head()) ``` -------------------------------- ### Get Vietnamese and Global Gold Prices (Python) Source: https://context7.com/vnstock-hq/vnstock_insider_guide/llms.txt Retrieves historical prices for Vietnamese and global gold. The results are DataFrames with 'time' and gold price columns. Vietnamese prices are in VND/chi, and global prices are in USD/ounce. ```python # Giá vàng trong nước (giá mua vào) gold_vn = commodity.gold_vn() print("Giá vàng Việt Nam:") print(gold_vn.tail()) # Giá vàng thế giới gold_global = commodity.gold_global() print("Giá vàng thế giới:") print(gold_global.tail()) # Kết quả: DataFrame với cột time và giá vàng # Đơn vị: VND/chỉ (Việt Nam), USD/ounce (thế giới) ``` -------------------------------- ### Fetch Full Annual Balance Sheet Data (Python) Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/1-vnstock_data_explorer_v2_demo.ipynb This snippet demonstrates how to initialize the vnstock library, fetch annual balance sheet data in Vietnamese, and display the entire dataset. It requires the vnstock library to be installed. The output is a pandas DataFrame containing detailed financial information. ```python import vnstock as vn fin = vn.vnstock() balance_sheet_data = fin.balance_sheet(period='year', lang='vi') print(balance_sheet_data) ``` -------------------------------- ### Get Livestock Prices (Python) Source: https://context7.com/vnstock-hq/vnstock_insider_guide/llms.txt Retrieves historical prices for livestock, specifically Northern Vietnamese pork and Chinese pork. The function returns a DataFrame containing the time series price data, useful for analyzing related stock correlations. ```python # Giá thịt lợn miền Bắc Việt Nam pork_north_vn = commodity.pork_north_vn() print("Giá thịt lợn miền Bắc:") print(pork_north_vn.tail()) # Giá thịt lợn Trung Quốc pork_china = commodity.pork_china() print("Giá thịt lợn Trung Quốc:") print(pork_china.tail()) # Kết quả: Tất cả trả về DataFrame với time series giá hàng hóa # Hữu ích để phân tích tương quan với cổ phiếu ngành liên quan ``` -------------------------------- ### Initialize Finance Explorer with vnstock Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/1-vnstock_data_explorer_v2_demo.ipynb Initializes the Finance data explorer from vnstock_data.explorer.vci. It allows specifying the stock symbol and the financial reporting period (e.g., 'quarter'). This offers enhanced rate limits compared to the public version. ```python from vnstock_data.explorer.vci import Finance # Khai báo tham số period một lần khi khởi tạo hoặc thay đổi khi gọi phương thức cụ thể, mặc định là 'quarter' fin = Finance(symbol='VCI', period='quarter') ``` -------------------------------- ### Fetch Feed Summaries from Multiple Sites using vnstock (Python) Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/4-vnstock_news_v2.1_demo.ipynb Hàm này thu thập thông tin tóm tắt (tiêu đề, link, mô tả, ngày đăng) từ các trang web được cấu hình trong SITES_CONFIG. Nó có thể lấy dữ liệu từ sitemap hoặc RSS feed, lọc theo số lượng bài viết (`top_n`) và khoảng thời gian (`within`), sau đó lưu kết quả vào file CSV. Thư viện vnstock, pandas, asyncio, logging và os là các phụ thuộc cần thiết. ```python import os import pandas as pd import logging import asyncio from vnstock_news.async_crawlers.async_batch import AsyncBatchCrawler from vnstock_news.config.sites import SITES_CONFIG from vnstock_news.utils.logger import setup_logger from vnstock_news.config.sitemap_resolver import DynamicSitemapResolver # Khởi tạo logger logger = setup_logger("export_feed_info", debug=False) # Thư mục để lưu file CSV OUTPUT_DIR = "output/feed_info" async def fetch_feed_info(site_name: str, top_n: int = None, within: str = None): """ Thu thập thông tin tóm tắt từ sitemap hoặc RSS feed và lưu vào file CSV. Parameters: site_name (str): Tên của trang (từ SITES_CONFIG). top_n (int): Giới hạn số lượng bài viết cần lấy. within (str): Khoảng thời gian để lọc bài viết (ví dụ: '1h', '1d', '7d'). """ try: logger.info(f"Đang xử lý trang: {site_name}") # Khởi tạo AsyncBatchCrawler crawler = AsyncBatchCrawler(site_name=site_name) # Xác định nguồn (sitemap hoặc RSS) site_data = SITES_CONFIG.get(site_name) sources = [] if site_data.get("rss"): sources = site_data["rss"]["urls"] elif "sitemap" in site_data: # Xử lý cấu trúc sitemap mới resolver = DynamicSitemapResolver() sitemap_url = resolver.resolve_sitemap_url(site_name, site_data) if sitemap_url: sources = [sitemap_url] elif site_data.get("sitemap_url"): # Cấu trúc cũ sources = [site_data["sitemap_url"]] if not sources: logger.warning(f"Không tìm thấy nguồn cho trang {site_name}. Bỏ qua...") return # Thu thập dữ liệu feed (không crawl chi tiết bài viết) logger.info(f"Đang thu thập thông tin feed từ các nguồn: {sources}") feed_df = await crawler.prepare_feeder_async(sources) # Lọc dữ liệu nếu có điều kiện if not feed_df.empty: filtered_df = crawler.filter_feeder(feed_df, top_n=top_n, within=within) else: logger.warning(f"Không có dữ liệu nào được thu thập từ {site_name}") return # Thiết lập thư mục output os.makedirs(OUTPUT_DIR, exist_ok=True) output_file = os.path.join(OUTPUT_DIR, f"{site_name}_feed_info.csv") # Lưu vào file CSV if not filtered_df.empty: filtered_df.to_csv(output_file, index=False, encoding="utf-8-sig") logger.info(f"Đã lưu {len(filtered_df)} bản ghi vào {output_file}") else: logger.warning(f"Không có bản ghi nào sau khi lọc cho {site_name}") except Exception as e: logger.error(f"Lỗi khi xử lý trang '{site_name}': {e}") async def main(): """ Hàm chính để thu thập và lưu thông tin feed cho tất cả các trang được hỗ trợ. """ logger.info("Bắt đầu quá trình xuất thông tin feed cho tất cả các trang...") # Tạo danh sách các tác vụ để chạy đồng thời tasks = [] for site_name in SITES_CONFIG.keys(): task = fetch_feed_info(site_name=site_name, top_n=20, within="1d") tasks.append(task) # Chạy tất cả các tác vụ đồng thời await asyncio.gather(*tasks) logger.info("Quá trình xuất thông tin feed đã hoàn tất!") # --- Cách chạy trong Jupyter Notebook --- # import asyncio # asyncio.run(main()) ``` -------------------------------- ### Get Foreign Investment Top Stocks (Python) Source: https://context7.com/vnstock-hq/vnstock_insider_guide/llms.txt Fetches top stocks based on foreign investor activity, specifically identifying net buying and net selling volumes for a given date. The output is a DataFrame detailing foreign transactions. ```python # Top cổ phiếu được nước ngoài mua ròng nhiều nhất top_foreign_buy = top.foreign_buy(date='2024-08-16') # Kết quả: DataFrame với thông tin giao dịch của nước ngoài print(top_foreign_buy.head(10)) # Top cổ phiếu được nước ngoài bán ròng nhiều nhất top_foreign_sell = top.foreign_sell(date='2024-08-16') print(top_foreign_sell.head(10)) ``` -------------------------------- ### Get Foreign Investor Trade Data in Python Source: https://context7.com/vnstock-hq/vnstock_insider_guide/llms.txt Retrieves statistical data on foreign investor trading activities, including buy/sell volume and value, as well as net transactions. This data is valuable for understanding foreign market sentiment and trends. ```python # Thống kê mua/bán của nhà đầu tư nước ngoài foreign_df = trading.foreign_trade(start=START_DATE, end=END_DATE) # Kết quả: DataFrame với các cột # - Khối lượng mua/bán của nước ngoài # - Giá trị mua/bán của nước ngoài # - Khối lượng và giá trị ròng print(foreign_df.head()) ``` -------------------------------- ### Initialize TopStock Class in Python Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/1-vnstock_data_explorer_v2_demo.ipynb This snippet shows how to import and initialize the TopStock class from the vnstock_data library. This class is used to access functions for retrieving top stock data. No external dependencies beyond the vnstock library are required. ```python from vnstock_data import TopStock top = TopStock() ``` -------------------------------- ### Get Metal Prices (Python) Source: https://context7.com/vnstock-hq/vnstock_insider_guide/llms.txt Retrieves historical prices for various metals, including coke, D10 steel (construction steel), HRC steel (hot-rolled coil), and iron ore. Each query returns a DataFrame with time series price data. ```python # Giá than cốc coke = commodity.coke() print("Giá than cốc:") print(coke.tail()) # Giá thép D10 (thép xây dựng) steel_d10 = commodity.steel_d10() print("Giá thép D10:") print(steel_d10.tail()) # Giá thép HRC (thép cán nóng) steel_hrc = commodity.steel_hrc() print("Giá thép HRC:") print(steel_hrc.tail()) # Giá quặng sắt iron_ore = commodity.iron_ore() print("Giá quặng sắt:") print(iron_ore.tail()) ``` -------------------------------- ### Initialize Finance Object (Python) Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/1-vnstock_data_explorer_v2_demo.ipynb This code snippet initializes a `Finance` object from the vnstock library. This object is used to access various financial data for a specific stock symbol. It requires the `vnstock_data.explorer.mas` module and takes the stock symbol and data period as parameters. ```python from vnstock_data.explorer.mas import Finance fin = Finance(symbol='VCI', period='quarter') ``` -------------------------------- ### Fetch Price Board Data with vnstock_pipeline (Python) Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/3-vnstock_pipeline_v2_demo.ipynb This Python script demonstrates fetching Price Board data using the `run_price_board` task from `vnstock_pipeline`. It supports 'live' mode for continuous updates during trading hours and 'EOD' mode for a single End-of-Day data download. The example shows how to define a list of tickers and set the desired mode. ```Python from vnstock_pipeline.tasks.price_board import run_price_board if __name__ == "__main__": # Danh sách mã VN30 mẫu TICKERS = [ 'ACB', 'BCM', 'BID', 'BVH', 'CTG', 'FPT', 'GAS', 'GVR', 'HDB', 'HPG', 'LPB', 'MBB', 'MSN', 'MWG', 'PLX', 'SAB', 'SHB', 'SSB', 'SSI', 'STB', 'TCB', 'TPB', 'VCB', 'VHM', 'VIB', 'VIC', 'VJC', 'VNM', 'VPB', 'VRE' ] # Chọn chế độ: "live" để cập nhật liên tục trong phiên giao dịch, # hoặc "EOD" để tải dữ liệu tĩnh một lần. mode = "eod" # mode = "live" hoặc mode = "EOD" # Gọi hàm run_price_board với danh sách mã, thời gian chờ giữa các lần cập nhật, và chế độ tải run_price_board(TICKERS, interval=60, mode=mode) ``` -------------------------------- ### Initialize Trading Object in Python Source: https://context7.com/vnstock-hq/vnstock_insider_guide/llms.txt Initializes a Trading object from the vnstock_data library to interact with trading data. Requires a stock symbol and a data source. Specifies the start and end dates for data retrieval. This object is fundamental for accessing various trading-related APIs. ```python from vnstock_data import Trading # Khởi tạo với mã cổ phiếu và nguồn dữ liệu trading = Trading(symbol='MSN', source='VCI') # Định nghĩa khoảng thời gian START_DATE = '2024-01-02' END_DATE = '2024-11-08' ``` -------------------------------- ### Get Market P/B Ratio History (Python) Source: https://context7.com/vnstock-hq/vnstock_insider_guide/llms.txt Retrieves the historical P/B ratio for a market index over a specified duration (e.g., 5 years). The output is a DataFrame with time series P/B ratio data, which can be used in conjunction with P/E for market valuation analysis. ```python # Lấy P/B ratio lịch sử 5 năm pb_history = market_hose.pb(duration='5Y') # Kết quả: DataFrame với time series P/B ratio # Kết hợp P/E và P/B để đánh giá định giá thị trường print(pb_history.head()) print(f"P/B hiện tại: {pb_history.iloc[-1]['pb']:.2f}") ``` -------------------------------- ### Initialize Finance API from VCI in Python Source: https://context7.com/vnstock-hq/vnstock_insider_guide/llms.txt Initializes the Finance API from the vnstock_data.explorer.vci module. This API is intended for sponsored members and provides access to financial statement data. It serves as the entry point for retrieving detailed financial reports of companies. ```python from vnstock_data.explorer.vci import Finance ``` -------------------------------- ### Get Market P/E Ratio History (Python) Source: https://context7.com/vnstock-hq/vnstock_insider_guide/llms.txt Fetches the historical P/E ratio for a specified market index (e.g., VNINDEX) over a given duration (e.g., 5 years). The result is a DataFrame containing report dates and P/E values, useful for assessing overall market valuation. ```python # Lấy P/E ratio lịch sử 5 năm pe_history = market_hose.pe(duration='5Y') # Kết quả: DataFrame với các cột # - reportDate: Ngày báo cáo # - pe: Giá trị P/E ratio của chỉ số # Hữu ích để đánh giá định giá tổng thể thị trường print(pe_history.head()) print(f"P/E hiện tại: {pe_history.iloc[-1]['pe']:.2f}") ``` -------------------------------- ### Fetch Article Details - Python Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/4-vnstock_news_v2.1_demo.ipynb This Python code snippet demonstrates how to fetch the details of a specific article from a given URL using the `vnstock` library. It requires the `crawler` object to be initialized. The output is a dictionary containing various details about the article. ```python url = "https://vietstock.vn/2024/12/nhip-dap-thi-truong-1812-sac-xanh-bao-phu-hau-het-cac-nhom-nganh-1636-1253348.htm" article_details = crawler.get_article_details(url) article_details ``` -------------------------------- ### Retrieve Company Information (Python) Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/1_1_vnstock_data_explorer_v2_wrapper.ipynb Demonstrates the use of the Company module to fetch various details about a company. This includes the company overview, shareholder information, officer details, and subsidiaries. The data is presented in pandas DataFrames. ```python print("=== Company.overview ===") c = Company(source="vci", symbol="VCI", random_agent=False, show_log=False) df_ov = c.overview() display(df_ov.head()) print("\n=== Company.shareholders ===") df_sh = c.shareholders() display(df_sh.head()) print("=== Company.officers ===") df_of = c.officers(filter_by="all") display(df_of.head()) print("=== Company.subsidiaries ===") df_sub = c.subsidiaries(filter_by="all") display(df_sub.head()) ``` -------------------------------- ### Get Market PB Ratio with vnstock Source: https://github.com/vnstock-hq/vnstock_insider_guide/blob/main/demo/1-vnstock_data_explorer_v2_demo.ipynb Retrieves the Price-to-Book (PB) ratio for a given market index over a specified duration. This function is part of the Market object and requires a duration string (e.g., '5Y'). ```python market.pb(duration='5Y') ```