### Run Flask Application Source: https://github.com/rafaelquintanilha/quantbrasil-api/blob/master/README.md Starts the Flask development server with debug mode enabled. ```bash FLASK_DEBUG=1 flask run ``` -------------------------------- ### Get Stochastic for All IBOV Stocks Source: https://context7.com/rafaelquintanilha/quantbrasil-api/llms.txt Retrieves stochastic oscillator data with trend signals for all IBOV stocks. ```bash # Get stochastic data for entire IBOV portfolio curl "http://localhost:5000/stochastic" ``` -------------------------------- ### Get Stochastic for All IBOV Stocks Source: https://context7.com/rafaelquintanilha/quantbrasil-api/llms.txt Retrieves stochastic oscillator data with trend signals for all IBOV stocks. ```APIDOC ## GET /stochastic ### Description Retrieves stochastic oscillator data with trend signals for all IBOV stocks. ### Method GET ### Endpoint `/stochastic` ### Response #### Success Response (200) - **{ticker}** (object) - An object where keys are stock tickers and values are indicator data. - **k** (number) - The value of the slow Stochastic %K. - **d** (number) - The value of the slow Stochastic %D. - **price** (number) - The current price of the stock. - **variation** (number) - The price variation percentage. - **k_is_up** (integer) - Indicator for whether %K is trending up (1) or not (0). - **k_crossed_above** (integer) - Indicator for whether %K crossed above %D (1) or not (0). - **k_crossed_below** (integer) - Indicator for whether %K crossed below %D (1) or not (0). - **mme80_is_up** (integer) - Indicator for whether the 80-period exponential moving average is trending up (1) or not (0). ### Request Example ```bash curl "http://localhost:5000/stochastic" ``` ### Response Example ```json { "PETR4": { "k": 45, "d": 48, "price": 36.20, "variation": 12.45, "k_is_up": 0, "k_crossed_above": 0, "k_crossed_below": 1, "mme80_is_up": 1 }, "VALE3": { "k": 72, "d": 65, "price": 68.90, "variation": -5.20, "k_is_up": 1, "k_crossed_above": 1, "k_crossed_below": 0, "mme80_is_up": 0 } } ``` ``` -------------------------------- ### Get RSI/IFR2 for All IBOV Stocks Source: https://context7.com/rafaelquintanilha/quantbrasil-api/llms.txt Retrieves RSI indicators, price targets, and moving average signals for all stocks in the IBOV index. ```bash # Get IFR2 data for entire IBOV portfolio curl "http://localhost:5000/ifr2" ``` -------------------------------- ### Get Beta Coefficient Source: https://context7.com/rafaelquintanilha/quantbrasil-api/llms.txt Calculates the beta coefficient, correlation, and volatility metrics for a stock against the IBOV benchmark. Supports custom time intervals. ```bash # Get beta for Magazine Luiza (MGLU3) over default 365-day interval curl "http://localhost:5000/beta/MGLU3" ``` ```bash # Get beta with custom 180-day interval curl "http://localhost:5000/beta/MGLU3?interval=180" ``` -------------------------------- ### Get Stochastic Oscillator for Single Stock Source: https://context7.com/rafaelquintanilha/quantbrasil-api/llms.txt Returns fast and slow stochastic oscillator values (%K and %D) for a specific stock. ```bash # Get stochastic for Ambev (ABEV3) curl "http://localhost:5000/stochastic/ABEV3" ``` -------------------------------- ### Get Beta Coefficient Source: https://context7.com/rafaelquintanilha/quantbrasil-api/llms.txt Calculates the beta coefficient, correlation, and volatility metrics for a stock against the IBOV benchmark (^BVSP). ```APIDOC ## GET /beta/{ticker} ### Description Calculates the beta coefficient, correlation, and volatility metrics for a stock against the IBOV benchmark (^BVSP). ### Method GET ### Endpoint `/beta/{ticker}` ### Parameters #### Path Parameters - **ticker** (string) - Required - The stock ticker symbol (e.g., MGLU3). #### Query Parameters - **interval** (integer) - Optional - The interval in days for the calculation. Defaults to 365. ### Response #### Success Response (200) - **beta** (number) - The beta coefficient of the stock relative to the IBOV. - **corr** (number) - The correlation coefficient between the stock and the IBOV. - **std_asset** (number) - The standard deviation of the asset's returns. - **std_bench** (number) - The standard deviation of the benchmark (IBOV) returns. ### Request Example ```bash # Get beta with default interval curl "http://localhost:5000/beta/MGLU3" # Get beta with custom interval curl "http://localhost:5000/beta/MGLU3?interval=180" ``` ### Response Example ```json { "beta": 1.45, "corr": 0.72, "std_asset": 0.0312, "std_bench": 0.0156 } ``` ``` -------------------------------- ### Get Bollinger Bands Source: https://context7.com/rafaelquintanilha/quantbrasil-api/llms.txt Calculates Bollinger Bands for a stock and returns the current position relative to the bands. Supports custom parameters for k and n. ```bash # Get Bollinger Bands for Bradesco (BBDC4) with default parameters (k=2, n=20) curl "http://localhost:5000/bb/BBDC4" ``` ```bash # Get Bollinger Bands with custom parameters (k=2.5, n=30) curl "http://localhost:5000/bb/BBDC4?k=2.5&n=30" ``` -------------------------------- ### Get Stochastic Oscillator for Single Stock Source: https://context7.com/rafaelquintanilha/quantbrasil-api/llms.txt Returns fast and slow stochastic oscillator values (%K and %D) for a specific stock. ```APIDOC ## GET /stochastic/{ticker} ### Description Returns fast and slow stochastic oscillator values (%K and %D) for a specific stock. ### Method GET ### Endpoint `/stochastic/{ticker}` ### Parameters #### Path Parameters - **ticker** (string) - Required - The stock ticker symbol (e.g., ABEV3). ### Response #### Success Response (200) - **fast_k** (number) - The value of the fast Stochastic %K. - **fast_d** (number) - The value of the fast Stochastic %D. - **k** (number) - The value of the slow Stochastic %K. - **d** (number) - The value of the slow Stochastic %D. ### Request Example ```bash curl "http://localhost:5000/stochastic/ABEV3" ``` ### Response Example ```json { "fast_k": 65, "fast_d": 58, "k": 58, "d": 52 } ``` ``` -------------------------------- ### Get RSI/IFR2 for All IBOV Stocks Source: https://context7.com/rafaelquintanilha/quantbrasil-api/llms.txt Retrieves RSI indicators, price targets, and moving average signals for all stocks in the IBOV index. ```APIDOC ## GET /ifr2 ### Description Retrieves RSI indicators, price targets, and moving average signals for all stocks in the IBOV index. ### Method GET ### Endpoint `/ifr2` ### Response #### Success Response (200) - **{ticker}** (object) - An object where keys are stock tickers and values are indicator data. - **rsi** (number) - The current RSI value. - **target** (number) - The price target. - **price** (number) - The current price. - **upside** (number) - The potential upside percentage. - **mm50_is_up** (integer) - Indicator for whether the 50-day moving average is trending up (1) or not (0). - **variation** (number) - The price variation percentage. ### Request Example ```bash curl "http://localhost:5000/ifr2" ``` ### Response Example ```json { "PETR4": { "rsi": 32, "target": 38.50, "price": 36.20, "upside": 6.35, "mm50_is_up": 1, "variation": 12.45 }, "VALE3": { "rsi": 58, "target": 72.30, "price": 68.90, "upside": 4.93, "mm50_is_up": 0, "variation": -5.20 } } ``` ``` -------------------------------- ### Get Bollinger Bands Source: https://context7.com/rafaelquintanilha/quantbrasil-api/llms.txt Calculates Bollinger Bands for a stock and returns the current position relative to the bands along with band values. ```APIDOC ## GET /bb/{ticker} ### Description Calculates Bollinger Bands for a stock and returns the current position relative to the bands along with band values. ### Method GET ### Endpoint `/bb/{ticker}` ### Parameters #### Path Parameters - **ticker** (string) - Required - The stock ticker symbol (e.g., BBDC4). #### Query Parameters - **k** (number) - Optional - The number of standard deviations to use for the bands. Defaults to 2. - **n** (integer) - Optional - The number of periods to use for the moving average and standard deviation calculation. Defaults to 20. ### Response #### Success Response (200) - **middle_band** (number) - The value of the middle band (typically a 20-period simple moving average). - **upper_band** (number) - The value of the upper band. - **lower_band** (number) - The value of the lower band. - **current_price** (number) - The current price of the stock. - **text** (string) - A textual description of the current price's position relative to the bands. ### Request Example ```bash # Get Bollinger Bands with default parameters curl "http://localhost:5000/bb/BBDC4" # Get Bollinger Bands with custom parameters curl "http://localhost:5000/bb/BBDC4?k=2.5&n=30" ``` ### Response Example ```json { "middle_band": 14.25, "upper_band": 15.80, "lower_band": 12.70, "current_price": 13.45, "text": "BBDC4 está dentro das Bandas de Bollinger" } ``` ``` -------------------------------- ### Get Complete Indicators Dashboard Source: https://context7.com/rafaelquintanilha/quantbrasil-api/llms.txt Retrieves a dashboard with technical indicators for all IBOV stocks. This endpoint provides a comprehensive overview of stock performance metrics. ```bash curl "http://localhost:5000/static" ``` -------------------------------- ### Get RSI/IFR2 for Single Stock Source: https://context7.com/rafaelquintanilha/quantbrasil-api/llms.txt Returns the current 2-period RSI (IFR2) value for a specific stock. Useful for mean-reversion strategies. ```bash # Get IFR2 for Vale (VALE3) curl "http://localhost:5000/ifr2/VALE3" ``` -------------------------------- ### Get Stock Price History Source: https://context7.com/rafaelquintanilha/quantbrasil-api/llms.txt Retrieves historical OHLC price data for a specific Brazilian stock within a date range. Uses the '.SA' suffix for tickers. ```bash # Get price history for Petrobras (PETR4) from January to March 2024 curl "http://localhost:5000/price/PETR4?start=2024-01-01&end=2024-03-31" ``` -------------------------------- ### Get Stock Price History Source: https://context7.com/rafaelquintanilha/quantbrasil-api/llms.txt Retrieves historical OHLC price data for a specific Brazilian stock within a date range using Yahoo Finance. ```APIDOC ## GET /price/{ticker} ### Description Retrieves historical OHLC price data for a specific Brazilian stock within a date range. ### Method GET ### Endpoint `/price/{ticker}` ### Parameters #### Path Parameters - **ticker** (string) - Required - The stock ticker symbol (e.g., PETR4). #### Query Parameters - **start** (string) - Required - The start date for the historical data (YYYY-MM-DD). - **end** (string) - Required - The end date for the historical data (YYYY-MM-DD). ### Response #### Success Response (200) - **schema** (object) - Contains the schema definition for the data. - **fields** (array) - Array of field objects describing the data columns. - **name** (string) - The name of the field (e.g., 'Date', 'Open', 'High', 'Close'). - **type** (string) - The data type of the field (e.g., 'datetime', 'number'). - **data** (array) - An array of historical price data objects. - **Date** (datetime) - The date of the trading day. - **Open** (number) - The opening price. - **High** (number) - The highest price of the day. - **Close** (number) - The closing price. ### Request Example ```bash curl "http://localhost:5000/price/PETR4?start=2024-01-01&end=2024-03-31" ``` ### Response Example ```json { "schema": { "fields": [ {"name": "Date", "type": "datetime"}, {"name": "Open", "type": "number"}, {"name": "High", "type": "number"}, {"name": "Close", "type": "number"} ] }, "data": [ {"Date": "2024-01-02T00:00:00.000Z", "Open": 36.50, "High": 37.20, "Close": 36.95}, {"Date": "2024-01-03T00:00:00.000Z", "Open": 36.80, "High": 37.50, "Close": 37.15} ] } ``` ``` -------------------------------- ### Get RSI/IFR2 for Single Stock Source: https://context7.com/rafaelquintanilha/quantbrasil-api/llms.txt Returns the current 2-period RSI (IFR2) value for a specific stock. IFR2 is commonly used in Brazilian market analysis for mean-reversion strategies. ```APIDOC ## GET /ifr2/{ticker} ### Description Returns the current 2-period RSI (IFR2) value for a specific stock. ### Method GET ### Endpoint `/ifr2/{ticker}` ### Parameters #### Path Parameters - **ticker** (string) - Required - The stock ticker symbol (e.g., VALE3). ### Response #### Success Response (200) - **ifr2** (number) - The calculated 2-period RSI value. ### Request Example ```bash curl "http://localhost:5000/ifr2/VALE3" ``` ### Response Example ```json { "ifr2": 45 } ``` ``` -------------------------------- ### Database Connection Source: https://context7.com/rafaelquintanilha/quantbrasil-api/llms.txt Establishes a PostgreSQL connection using environment variables for credential management. Requires a .env file with database credentials. ```python from db import connect_to_db # Requires .env file with: DB_USER_NAME, DB_PASSWORD, DB_ENDPOINT, DB_PORT, DB_NAME engine = connect_to_db() # Use with pandas for SQL queries import pandas as pd df = pd.read_sql("SELECT * FROM asset LIMIT 10", engine) ``` -------------------------------- ### Backtest Trading Strategy Source: https://context7.com/rafaelquintanilha/quantbrasil-api/llms.txt Runs a backtest of an IFR2-based trading strategy with buy/sell signal generation. Requires historical OHLC data and calculates strategy performance statistics. ```python from utils import ( rsi, strategy_points, backtest_algorithm, strategy_test, get_data, get_interval ) # Fetch historical data (500 days for meaningful backtest) start, end = get_interval(500) df = get_data( tickers="BBDC4.SA", columns=["Open", "High", "Close", "Adj Close"], start=start, end=end ) # Calculate IFR2 and generate strategy signals df["IFR2"] = rsi(df, column="Adj Close", window=2) df = strategy_points(data=df, rsi_parameter=30) # Buy when RSI <= 30 # Run backtest with R$10,000 initial capital all_profits, total_capital = backtest_algorithm(df, initial_capital=10000) statistics = strategy_test(all_profits, total_capital) print(f"Total Operations: {statistics['num_operations']}") print(f"Win Rate: {statistics['pct_gains']:.0f}%") print(f"Total Profit: R${statistics['total_profit']:.2f}") print(f"Max Drawdown: {statistics['drawdown']:.2f}%") ``` -------------------------------- ### Backtest IFR2 Strategy Source: https://context7.com/rafaelquintanilha/quantbrasil-api/llms.txt Runs a historical backtest of the IFR2 mean-reversion strategy on a specific stock. Allows custom entry thresholds. ```bash # Backtest IFR2 strategy for Itaú (ITUB4) with default entry at RSI <= 30 curl "http://localhost:5000/backtest/ifr2/ITUB4" ``` ```bash # Backtest with custom entry threshold at RSI <= 25 curl "http://localhost:5000/backtest/ifr2/ITUB4?entry=25" ``` -------------------------------- ### Calculate Beta Coefficient Source: https://context7.com/rafaelquintanilha/quantbrasil-api/llms.txt Computes beta, correlation, and volatility metrics against a benchmark. Requires historical data for both the asset and the benchmark. ```python from utils import get_beta, get_data, get_interval # Fetch data for asset and benchmark start, end = get_interval(365) tickers = ["MGLU3.SA", "^BVSP"] df = get_data(tickers=tickers, columns=["Adj Close"], start=start, end=end)["Adj Close"] df.dropna(inplace=True) # Calculate beta against IBOV beta, corr, std_asset, std_bench = get_beta(df["MGLU3.SA"], df["^BVSP"]) print(f"Beta: {beta:.2f}") # Output: Beta: 1.45 print(f"Correlation: {corr:.2f}") # Output: Correlation: 0.72 ``` -------------------------------- ### Calculate Bollinger Bands Source: https://context7.com/rafaelquintanilha/quantbrasil-api/llms.txt Computes Bollinger Bands with configurable standard deviation multiplier and period. Requires price data. ```python from utils import bb, get_data, get_interval # Fetch price data start, end = get_interval(50) df = get_data(tickers="VALE3.SA", columns=["Adj Close"], start=start, end=end) # Calculate Bollinger Bands (k=2 std deviations, n=20 period) bb_df = bb(df, k=2, n=20) print(f"Upper Band: {bb_df['Upper Band'][-1]:.2f}") print(f"Middle Band: {bb_df['Middle Band'][-1]:.2f}") print(f"Lower Band: {bb_df['Lower Band'][-1]:.2f}") ``` -------------------------------- ### Calculate Stochastic Oscillator Source: https://context7.com/rafaelquintanilha/quantbrasil-api/llms.txt Calculates fast and slow stochastic oscillators with configurable windows. Requires OHLC data. ```python from utils import stochastic, get_data, get_interval # Fetch OHLC data start, end = get_interval(365) df = get_data(tickers="ITUB4.SA", columns=["High", "Low", "Adj Close"], start=start, end=end) # Calculate stochastic (k_window=8, mma_window=3) stoch_df = stochastic(df, k_window=8, mma_window=3) print(f"Fast %K: {int(round(stoch_df['%K'][-1]))}") print(f"Fast %D: {int(round(stoch_df['%D'][-1]))}") print(f"Slow %K: {int(round(stoch_df['Slow %K'][-1]))}") print(f"Slow %D: {int(round(stoch_df['Slow %D'][-1]))}") ``` -------------------------------- ### Backtest IFR2 Strategy Source: https://context7.com/rafaelquintanilha/quantbrasil-api/llms.txt Runs a historical backtest of the IFR2 mean-reversion strategy on a specific stock, returning performance statistics. ```APIDOC ## GET /backtest/ifr2/{ticker} ### Description Runs a historical backtest of the IFR2 mean-reversion strategy on a specific stock, returning performance statistics. ### Method GET ### Endpoint `/backtest/ifr2/{ticker}` ### Parameters #### Path Parameters - **ticker** (string) - Required - The stock ticker symbol (e.g., ITUB4). #### Query Parameters - **entry** (number) - Optional - The RSI entry threshold for the strategy. Defaults to 30. ### Response #### Success Response (200) - **num_operations** (integer) - The total number of operations performed during the backtest. - **gains** (integer) - The number of profitable operations. - **pct_gains** (number) - The percentage of profitable operations. - **losses** (integer) - The number of losing operations. - **pct_losses** (number) - The percentage of losing operations. - **total_profit** (number) - The total profit generated by the strategy. - **pct_profit** (number) - The total percentage profit generated. - **drawdown** (number) - The maximum drawdown experienced during the backtest. ### Request Example ```bash # Backtest with default entry threshold curl "http://localhost:5000/backtest/ifr2/ITUB4" # Backtest with custom entry threshold curl "http://localhost:5000/backtest/ifr2/ITUB4?entry=25" ``` ### Response Example ```json { "num_operations": 45, "gains": 32, "pct_gains": 71.0, "losses": 13, "pct_losses": 29.0, "total_profit": 2350.50, "pct_profit": 23.51, "drawdown": 8.45 } ``` ``` -------------------------------- ### Calculate RSI Source: https://context7.com/rafaelquintanilha/quantbrasil-api/llms.txt Calculates the Relative Strength Index (RSI) using the Wilder smoothing method. Requires price data and specifies the lookback window. ```python from utils import rsi, get_data, get_interval # Fetch price data for the last 50 days start, end = get_interval(50) df = get_data(tickers="PETR4.SA", columns=["Adj Close"], start=start, end=end) # Calculate 2-period RSI (IFR2) rsi_values = rsi(df, column="Adj Close", window=2) current_rsi = int(round(rsi_values[-1])) print(f"Current IFR2: {current_rsi}") # Output: Current IFR2: 45 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.