### Install fastquant Python Package Source: https://github.com/enzoampil/fastquant/blob/master/docs/docusaurus/docs/getting_started.md This code installs the fastquant library using pip. It is a prerequisite for using the library's functionalities. No specific inputs or outputs are associated with the installation command itself, beyond the success or failure of the pip operation. ```shell pip install fastquant or python -m pip install fastquant ``` -------------------------------- ### Install Fastquant from GitHub Source: https://github.com/enzoampil/fastquant/blob/master/examples/backtest_news_sentiment.ipynb This code snippet shows how to install the fastquant library directly from its GitHub repository. It is commented out by default and intended for use in environments like Google Colab. ```python # uncomment to install in colab # !pip install -e git+https://github.com/enzoampil/fastquant.git@master#egg=fastquant ``` -------------------------------- ### Multi-Strategy Backtesting with SMAC and RSI Source: https://github.com/enzoampil/fastquant/blob/master/docs/docusaurus/docs/getting_started.md This example shows how to combine multiple trading strategies (Simple Moving Average Crossover and Relative Strength Index) for backtesting. It illustrates both using a single set of parameters and performing an auto grid search for optimal parameters. ```python df = get_stock_data("JFC", "2018-01-01", "2019-01-01") # Utilize single set of parameters strats = { "smac": {"fast_period": 35, "slow_period": 50}, "rsi": {"rsi_lower": 30, "rsi_upper": 70} } res = backtest("multi", df, strats=strats) res.shape # (1, 16) # Utilize auto grid search strats_opt = { "smac": {"fast_period": 35, "slow_period": [40, 50]}, "rsi": {"rsi_lower": [15, 30], "rsi_upper": 70} } res_opt = backtest("multi", df, strats=strats_opt) res_opt.shape # (4, 16) ``` -------------------------------- ### Get Help for get_company_disclosures - Python Source: https://github.com/enzoampil/fastquant/blob/master/lessons/fastquant_lesson1_accessing_pse_data.ipynb This example demonstrates how to access the documentation and usage information for the `get_company_disclosures` function using Python's built-in `help()` function. This is useful for understanding the function's parameters and expected data types. ```python help(get_company_disclosures) ``` -------------------------------- ### Get Help for get_pse_data Function Source: https://github.com/enzoampil/fastquant/blob/master/lessons/fastquant_lesson1_accessing_pse_data.ipynb Displays the help documentation for the `get_pse_data` function from the fastquant library. This provides detailed information on its parameters, functionality, and return values. Dependencies: fastquant. ```python help(get_pse_data) ``` -------------------------------- ### Running FastQuant in a Docker Container Source: https://github.com/enzoampil/fastquant/blob/master/docs/docusaurus/docs/getting_started.md This section provides commands for building a Docker image for FastQuant, running it as a container, accessing the container, and then using FastQuant within the Python interpreter inside the container. ```bash # Build the image docker build -t myimage . # Run the container docker run -t -d -p 5000:5000 myimage # Get the container id docker ps # SSH into the fastquant container docker exec -it /bin/bash # Run python and use fastquant python >>> from fastquant import get_stock_data >>> df = get_stock_data("TSLA", "2019-01-01", "2020-01-01") >>> df.head() ``` -------------------------------- ### Install fastquant in Colab Source: https://github.com/enzoampil/fastquant/blob/master/examples/stock_data_cache.ipynb This code snippet is intended to be uncommented and run within a Google Colab environment to install the fastquant library. It serves as a setup step for using the library's functionalities. ```python # uncomment to install in colab ``` -------------------------------- ### Get Cryptocurrency Data with fastquant Source: https://github.com/enzoampil/fastquant/blob/master/docs/docusaurus/docs/getting_started.md This Python code snippet shows how to fetch cryptocurrency data using the `get_crypto_data` function from fastquant. It requires a trading pair (e.g., 'BTC/USDT'), a start date, and an end date. The function returns a pandas DataFrame with cryptocurrency price and volume data, sourced from Binance. ```python from fastquant import get_crypto_data crypto = get_crypto_data("BTC/USDT", "2018-12-01", "2019-12-31") crypto.head() ``` -------------------------------- ### Install FastQuant from GitHub Source: https://github.com/enzoampil/fastquant/blob/master/examples/stock_data_cache.ipynb This command installs the fastquant library directly from its GitHub repository. It uses pip to clone the repository and install it in editable mode. ```bash #!/bin/bash - pip install -e git+https://github.com/enzoampil/fastquant.git@master#egg=fastquant ``` -------------------------------- ### Backtest Bollinger Bands Strategy Source: https://github.com/enzoampil/fastquant/blob/master/docs/docusaurus/docs/getting_started.md This Python code uses the `backtest` function from fastquant to simulate a Bollinger Bands trading strategy. It requires the stock data DataFrame and parameters such as `period` and `devfactor`. The output indicates the starting and final portfolio values after applying the strategy. ```python backtest('bbands', df, period=20, devfactor=2.0) ``` -------------------------------- ### Install fastquant Library Source: https://github.com/enzoampil/fastquant/blob/master/examples/fastquant_demo.ipynb This code snippet shows how to install the fastquant library from its GitHub repository. It is a prerequisite for using the library's functionalities. Ensure you have pip and git installed. ```python # !pip install -e git+https://github.com/enzoampil/fastquant.git@master#egg=fastquant ``` -------------------------------- ### Backtest Simple Moving Average Crossover Strategy Source: https://github.com/enzoampil/fastquant/blob/master/docs/docusaurus/docs/getting_started.md This Python code uses the `backtest` function from fastquant to simulate a Simple Moving Average Crossover (SMAC) strategy. It requires a DataFrame containing stock data, along with parameters for the fast and slow moving average periods. The output includes the starting and final portfolio values after the backtest. ```python from fastquant import backtest backtest('smac', df, fast_period=15, slow_period=40) ``` -------------------------------- ### Install Fastquant Source: https://github.com/enzoampil/fastquant/blob/master/examples/2020-05-10-backtest_multi_strategy.ipynb This code snippet shows how to install the Fastquant library using pip. It is intended to be run in an environment like Google Colab. Ensure you have Python 3 installed. ```python # uncomment to install in colab # !pip3 install fastquant ``` -------------------------------- ### Install Fastquant Package Source: https://github.com/enzoampil/fastquant/blob/master/lessons/fastquant_lesson2_backtest_your_trading_strategy.ipynb Installs the fastquant Python package, which is necessary for using its backtesting and data fetching functionalities. This is typically the first step before importing and using the package. ```python #!pip install fastquant ``` -------------------------------- ### Get Stock Data with fastquant Source: https://github.com/enzoampil/fastquant/blob/master/docs/docusaurus/docs/getting_started.md This Python code snippet demonstrates how to retrieve historical stock data using the `get_stock_data` function from the fastquant library. It requires a stock symbol, a start date, and an end date as input. The output is a pandas DataFrame containing the stock's price data, including the closing price and date. Data is sourced from Yahoo Finance and the Philippine Stock Exchange. ```python from fastquant import get_stock_data df = get_stock_data("JFC", "2018-01-01", "2019-01-01") print(df.head()) ``` -------------------------------- ### Backtest Moving Average Convergence Divergence (MACD) Strategy Source: https://github.com/enzoampil/fastquant/blob/master/docs/docusaurus/docs/getting_started.md This Python code snippet executes a backtest for the Moving Average Convergence Divergence (MACD) strategy using the `backtest` function in fastquant. It requires the stock data DataFrame and several parameters: `fast_period`, `slow_period`, `signal_period`, `sma_period`, and `dir_period`. The result displays the starting and final portfolio values. ```python backtest('macd', df, fast_period=12, slow_period=26, signal_period=9, sma_period=30, dir_period=10) ``` -------------------------------- ### Install fastquant Package Source: https://github.com/enzoampil/fastquant/blob/master/lessons/2020-03-09-lesson2-backtest-your-trading-strategy.ipynb Installs the fastquant Python package, which is necessary for using its backtesting and data retrieval functionalities. This is typically the first step before utilizing the library. ```python #!pip install fastquant ``` -------------------------------- ### Install fastquant using pip Source: https://github.com/enzoampil/fastquant/blob/master/lessons/2020-01-26-lesson1-accessing-pse_data.ipynb This command installs the fastquant library and its dependencies using pip3. Ensure you have pip3 installed and a stable internet connection for the download. ```python !pip3 install fastquant ``` -------------------------------- ### Install Fastquant for Colab Source: https://github.com/enzoampil/fastquant/blob/master/examples/2022-02-24-backtest_crypto_exit.ipynb Provides installation commands for the fastquant library in a Google Colab environment. Use the `--update` flag for the latest version or install directly from GitHub. ```python # uncomment to install in colab # !pip3 install fastquant --update # or pip install git+https://www.github.com/enzoampil/fastquant.git@history ``` -------------------------------- ### Set up fastquant Virtual Environment and Install Dependencies Source: https://github.com/enzoampil/fastquant/blob/master/CONTRIBUTING.md These commands set up a virtual environment for the fastquant project and install its Python dependencies. This ensures a consistent development environment and avoids conflicts with other projects. ```shell git clone https://github.com/enzoampil/fastquant.git cd fastquant virtualenv env source env/bin/activate pip install -r python/requirements.txt ``` -------------------------------- ### Backtest Results and Metrics Source: https://github.com/enzoampil/fastquant/blob/master/examples/backtest_news_sentiment.ipynb This section displays the results of a backtest, including the starting portfolio value, trade executions, final profit and loss (PnL), and optimization metrics such as Sharpe ratio. The output is presented in both tabular and dictionary formats. ```python Result: ``` ```python Result: init_cash buy_prop sell_prop execution_type senti rtot ravg \ 0 100000 1 1 close 0.2 0.07953 0.000621 rnorm rnorm100 sharperatio pnl final_value 0 0.169498 16.949773 0.75839 8277.79 108277.786758 ``` -------------------------------- ### Custom Strategy Backtesting with Machine Learning Predictions (Prophet) Source: https://github.com/enzoampil/fastquant/blob/master/docs/docusaurus/docs/getting_started.md This snippet demonstrates how to backtest custom trading strategies using machine learning predictions. It uses Facebook's Prophet to forecast Bitcoin prices, converts these forecasts into trading signals (expected daily returns), and then backtests a custom strategy based on these signals. ```python from fastquant import get_crypto_data, backtest from fbprophet import Prophet from matplotlib import pyplot as plt # Pull crypto data df = get_crypto_data("BTC/USDT", "2019-01-01", "2020-05-31") # Fit model on closing prices ts = df.reset_index()[["dt", "close"]] ts.columns = ['ds', 'y'] m = Prophet(daily_seasonality=True, yearly_seasonality=True).fit(ts) forecast = m.make_future_dataframe(periods=0, freq='D') # Predict and plot pred = m.predict(forecast) fig1 = m.plot(pred) plt.title('BTC/USDT: Forecasted Daily Closing Price', fontsize=25) ``` ```python # Convert predictions to expected 1 day returns expected_1day_return = pred.set_index("ds").yhat.pct_change().shift(-1).multiply(100) # Backtest the predictions, given that we buy bitcoin when the predicted next day return is > +1.5%, and sell when it's < -1.5%. df["custom"] = expected_1day_return.multiply(-1) backtest("custom", df.dropna(),upper_limit=1.5, lower_limit=-1.5) ``` -------------------------------- ### Install fastquant with pip Source: https://github.com/enzoampil/fastquant/blob/master/lessons/fastquant_lesson1_accessing_pse_data.ipynb This code snippet demonstrates how to install the fastquant Python library using pip. It is a common command for installing packages from the Python Package Index (PyPI). No specific inputs or outputs are required beyond the command itself, and it has no known limitations. ```python !pip install fastquant ``` -------------------------------- ### Install backtrader with plotting support Source: https://github.com/enzoampil/fastquant/blob/master/examples/jfc_rsi.ipynb This command installs the backtrader library with optional plotting capabilities, useful for visualizing trading strategy performance. It uses pip for package management. ```python #!pip install backtrader[plotting] ``` -------------------------------- ### Backtest Relative Strength Index (RSI) Strategy Source: https://github.com/enzoampil/fastquant/blob/master/docs/docusaurus/docs/getting_started.md This Python code snippet performs a backtest of the Relative Strength Index (RSI) trading strategy using the `backtest` function from fastquant. It requires the stock data DataFrame and parameters such as `rsi_period`, `rsi_upper`, and `rsi_lower`. The output shows the starting and final portfolio values. ```python backtest('rsi', df, rsi_period=14, rsi_upper=70, rsi_lower=30) ``` -------------------------------- ### Backtest Exponential Moving Average Crossover (EMAC) Strategy Source: https://github.com/enzoampil/fastquant/blob/master/docs/docusaurus/docs/getting_started.md This Python code performs a backtest of the Exponential Moving Average Crossover (EMAC) strategy using fastquant's `backtest` function. It takes the stock data DataFrame and specifies `fast_period` and `slow_period` for the EMAs. The output includes the initial and final portfolio values. ```python backtest('emac', df, fast_period=10, slow_period=30) ``` -------------------------------- ### View get_stock_data Function Help Source: https://github.com/enzoampil/fastquant/blob/master/lessons/2020-01-26-lesson1-accessing-pse_data.ipynb Displays the documentation for the `get_stock_data` function, outlining its parameters, their types, descriptions, and the function's return value. This helps in understanding the available options for data retrieval. ```python help(get_stock_data) ``` -------------------------------- ### News Sentiment Strategy Backtesting with Yahoo Finance and Business Times Source: https://github.com/enzoampil/fastquant/blob/master/docs/docusaurus/docs/getting_started.md This snippet demonstrates how to perform a news sentiment-based backtest using historical stock data from Yahoo Finance and news sentiment data scraped from Business Times. It highlights potential issues with date consistency between data sources and provides a corrected approach. ```python from fastquant import get_yahoo_data, get_bt_news_sentiment data = get_yahoo_data("TSLA", "2020-01-01", "2020-07-04") sentiments = get_bt_news_sentiment(keyword="tesla", page_nums=3) backtest("sentiment", data, sentiments=sentiments, senti=0.2) # Starting Portfolio Value: 100000.00 # Final Portfolio Value: 313198.37 # Note: Unfortunately, you can't recreate this scenario due to inconsistencies in the dates and sentiments that is scraped by get_bt_news_sentiment. In order to have a quickstart with News Sentiment Strategy you need to make the dates consistent with the sentiments that you are scraping. from fastquant import get_yahoo_data, get_bt_news_sentiment from datetime import datetime, timedelta # we get the current date and delta time of 30 days current_date = datetime.now().strftime("%Y-%m-%d") delta_date = (datetime.now() - timedelta(30)).strftime("%Y-%m-%d") data = get_yahoo_data("TSLA", delta_date, current_date) sentiments = get_bt_news_news_sentiment(keyword="tesla", page_nums=3) backtest("sentiment", data, sentiments=sentiments, senti=0.2) ``` -------------------------------- ### Optimize SMAC Strategy Parameters Source: https://github.com/enzoampil/fastquant/blob/master/docs/docusaurus/docs/getting_started.md This Python code optimizes the parameters for the Simple Moving Average Crossover (SMAC) strategy using fastquant's `backtest` function. It allows specifying ranges for `fast_period` and `slow_period` to find the best combination. The output includes the optimal parameters and performance metrics, as well as a table showing the final portfolio value for different parameter combinations. ```python from fastquant import backtest res = backtest("smac", df, fast_period=range(15, 30, 3), slow_period=range(40, 55, 3), verbose=False) print(res[['fast_period', 'slow_period', 'final_value']].head()) ``` -------------------------------- ### Get Cryptocurrency Data with fastquant Source: https://github.com/enzoampil/fastquant/blob/master/README.md This example illustrates how to retrieve historical cryptocurrency data using the `get_crypto_data` function. It takes a cryptocurrency pair (e.g., 'BTC/USDT'), a start date, and an end date. The output is a pandas DataFrame with OHLCV (Open, High, Low, Close, Volume) data. ```python from fastquant import get_crypto_data crypto = get_crypto_data("BTC/USDT", "2018-12-01", "2019-12-31") crypto.head() # open high low close volume # dt # 2018-12-01 4041.27 4299.99 3963.01 4190.02 44840.073481 # 2018-12-02 4190.98 4312.99 4103.04 4161.01 38912.154790 # 2018-12-03 4160.55 4179.00 3827.00 3884.01 49094.369163 # 2018-12-04 3884.76 4085.00 3781.00 3951.64 48489.551613 # 2018-12-05 3950.98 3970.00 3745.00 3769.84 44004.799448 ``` -------------------------------- ### FastQuant Trading Environment Setup - Python Source: https://github.com/enzoampil/fastquant/blob/master/examples/backtest_disclosures.ipynb This Python script sets up and runs a trading simulation using the backtrader library. It initializes the Cerebro engine, adds a custom sentiment strategy, configures a Yahoo Finance data feed, sets initial capital, applies order sizing, and defines commission rates. Finally, it executes the strategy and prints the initial and final portfolio values. ```python if __name__ == '__main__': cerebro = bt.Cerebro() # Strategy cerebro.addstrategy(SentimentStrat) # Data Feed data = bt.feeds.YahooFinanceData( dataname = 'JBFCF', fromdate = min(date_sentiments.keys()), todate = datetime.now().date(), reverse = False ) cerebro.adddata(data) cerebro.broker.setcash(100000.0) cerebro.addsizer(bt.sizers.FixedSize, stake=10) cerebro.broker.setcommission(commission=0.001) print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue()) cerebro.run() print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue()) cerebro.plot() ``` -------------------------------- ### Perform Backtest with Sentiment Strategy Source: https://github.com/enzoampil/fastquant/blob/master/examples/backtest_news_sentiment.ipynb This example shows how to perform a backtest using the `backtest` function from fastquant. It utilizes historical stock data and pre-computed sentiment scores to simulate trading decisions based on sentiment thresholds. ```python from fastquant import backtest #initiate buy/sell if senti>0.2/senti<-0.2 backtest("sentiment", data, sentiments=sentiments, senti=0.2) ``` -------------------------------- ### Install NLTK Package Source: https://github.com/enzoampil/fastquant/blob/master/examples/backtest_disclosures.ipynb Installs the Natural Language Toolkit (NLTK) package using pip. This is a prerequisite for using NLTK functionalities, including sentiment analysis. ```python #!pip install nltk ``` -------------------------------- ### Get Stock Data with fastquant Source: https://github.com/enzoampil/fastquant/blob/master/README.md This code demonstrates how to fetch historical stock data using the `get_stock_data` function from fastquant. It requires a stock symbol, a start date, and an end date. The function returns a pandas DataFrame containing daily stock information. ```python from fastquant import get_stock_data df = get_stock_data("JFC", "2018-01-01", "2019-01-01") print(df.head()) # dt close # 2019-01-01 293.0 # 2019-01-02 292.0 # 2019-01-03 309.0 # 2019-01-06 323.0 # 2019-01-07 321.0 ``` -------------------------------- ### Optimize Trading Strategy with Grid Search using fastquant Source: https://github.com/enzoampil/fastquant/blob/master/README.md This example demonstrates how to optimize a trading strategy (Simple Moving Average Crossover) using fastquant's `backtest` function with automated grid search. It tests various combinations of `fast_period` and `slow_period` within specified ranges. The output includes optimal parameters and metrics, along with a head of the results DataFrame. ```python from fastquant import backtest res = backtest("smac", df, fast_period=range(15, 30, 3), slow_period=range(40, 55, 3), verbose=False) # Optimal parameters: {'init_cash': 100000, 'buy_prop': 1, 'sell_prop': 1, 'execution_type': 'close', 'fast_period': 15, 'slow_period': 40} # Optimal metrics: {'rtot': 0.022, 'ravg': 9.25e-05, 'rnorm': 0.024, 'rnorm100': 2.36, 'sharperatio': None, 'pnl': 2272.9, 'final_value': 102272.90} print(res[['fast_period', 'slow_period', 'final_value']].head()) # fast_period slow_period final_value #0 15 40 102272.90 #1 21 40 98847.00 #2 21 52 98796.09 #3 24 46 98008.79 #4 15 46 97452.92 ``` -------------------------------- ### Plot Daily Closing Prices Source: https://github.com/enzoampil/fastquant/blob/master/lessons/fastquant_lesson1_accessing_pse_data.ipynb Visualizes the daily closing prices of a stock using matplotlib. ```APIDOC ## POST /plot/closing-prices ### Description Generates a plot of the daily closing prices for a given stock DataFrame. ### Method POST ### Endpoint /plot/closing-prices ### Parameters #### Request Body - **dataframe** (pandas.DataFrame) - Required - The DataFrame containing the stock data, expected to have a 'close' column. - **title** (string) - Optional - The title for the plot. Defaults to 'Daily Closing Prices'. ### Request Example ```python import pandas as pd from matplotlib import pyplot as plt # Assuming 'df' is a pandas DataFrame obtained from get_pse_data data = { 'close': [255.4, 255.0, 255.0, 256.0, 255.8] } df_example = pd.DataFrame(data) plt.figure(figsize=(10, 6)) df_example.close.plot() plt.title("Daily Closing Prices of JFC") plt.show() ``` ### Response #### Success Response (200) - **image** (bytes) - The generated plot image. #### Response Example (Image output of the plot) ``` -------------------------------- ### Altair Installation and Configuration Source: https://github.com/enzoampil/fastquant/blob/master/examples/2020-06-20-basic_portfolio.ipynb Installs the Altair visualization library using pip and configures Altair to disable action buttons in rendered charts. This is useful for creating cleaner, embeddable charts. ```python !pip3 install altair import altair as alt alt.renderers.set_embed_options(actions=False) ``` -------------------------------- ### Download NLTK Data Source: https://github.com/enzoampil/fastquant/blob/master/examples/backtest_disclosures.ipynb This snippet demonstrates how to download specific data packages from the Natural Language Toolkit (NLTK) library. This is often a prerequisite for using various NLTK functionalities, such as tokenization or part-of-speech tagging. Ensure NLTK is installed before running this command. ```python import nltk nltk.download('averaged_perceptron_tagger') ``` -------------------------------- ### Web Scraping and Sentiment Analysis Setup Source: https://github.com/enzoampil/fastquant/blob/master/examples/backtest_disclosures.ipynb This Python snippet sets up sentiment analysis using NLTK's VADER and scrapes data from rappler.com. It fetches articles, extracts text, calculates sentiment scores, and stores them. Dependencies include nltk, requests, and BeautifulSoup. ```python from nltk.sentiment.vader import SentimentIntensityAnalyzer from urllib.request import urlopen from bs4 import BeautifulSoup from datetime import datetime import time # Download VADER lexicon if not already present # nltk.download('vader_lexicon') sia = SentimentIntensityAnalyzer() base_url = "http://rappler.com" page = urlopen(base_url+'/previous-articles?filterMeta=Jollibee').read() soup = BeautifulSoup(page, features="html.parser") posts = soup.findAll("div", {"class": "col-xs-12 col-sm-8"}) date_sentiments = {} for post in posts[:10]: #default up to 50 posts time.sleep(1) url = post.a['href'] #date = post.time.text date_string = post.span.text.split('-')[0].strip() date = datetime.strptime(date_string, '%b %d, %Y').date() print(date, base_url+url) try: link_page = urlopen(base_url+url).read() except: url = url[:-2] link_page = urlopen(url).read() link_soup = BeautifulSoup(link_page) sentences = link_soup.findAll("p") passage = "" for sentence in sentences: passage += sentence.text sentiment = sia.polarity_scores(passage)['compound'] date_sentiments[date] = sentiment ``` -------------------------------- ### Initialize and Run Backtrader RSI Strategy Source: https://github.com/enzoampil/fastquant/blob/master/examples/jfc_rsi.ipynb This code initializes the backtrader Cerebro engine, adds a custom RSI strategy, sets commission, loads data from a CSV file, sets initial cash, runs the backtest, and prints the starting and final portfolio values. It also includes plotting the results. ```python if __name__ == '__main__': cerebro = bt.Cerebro() cerebro.addstrategy(RSIStrategy) cerebro.broker.setcommission(commission=COMMISSION_PER_TRANSACTION) data = btfeed.GenericCSVData( dataname=DATA_FILE, fromdate=datetime.datetime(2017, 1, 1), todate=datetime.datetime(2019, 1, 1), nullvalue=0.0, dtformat=('%Y-%m-%d'), datetime=0, open=1, high=2, low=3, close=4, volume=5, openinterest=-1 ) cerebro.adddata(data) cerebro.broker.setcash(INIT_CASH) print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue()) cerebro.run() print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue()) cerebro.plot(figsize=(30, 15)) ``` -------------------------------- ### Backtest with History and Plot Return Source: https://github.com/enzoampil/fastquant/blob/master/API.md This example illustrates how to configure the backtest function to return both the transaction history and the plot of the results. This provides a comprehensive output for analyzing and visualizing trading strategy performance. ```python from fastquant import backtest res, hist, plot = backtest(..., return_history=True, return_plot=True) ``` -------------------------------- ### Backtest Multiple Strategies (Python) Source: https://github.com/enzoampil/fastquant/blob/master/examples/2020-05-20-backtest_crypto.ipynb Executes a backtest using multiple strategies simultaneously. This example defines a dictionary `strats` containing configurations for both a SMAC and an RSI strategy, allowing for the evaluation of combined or comparative trading logic within a single backtest run. ```python from fastquant import backtest strats= { 'smac': { 'fast_period': 7, 'slow_period': 60 }, 'rsi': { 'rsi_upper': 70, 'rsi_lower': 30 } } results, history = backtest('multi', crypto, strats=strats, plot=False, verbose=False, return_history=True ) ``` -------------------------------- ### Import get_company_disclosures Function - Python Source: https://github.com/enzoampil/fastquant/blob/master/lessons/fastquant_lesson1_accessing_pse_data.ipynb This snippet shows the import statement required to use the `get_company_disclosures` function from the FastQuant library. No external dependencies beyond the FastQuant library are needed for this import. ```python from fastquant import get_company_disclosures ``` -------------------------------- ### Get PSE Stock Data Source: https://github.com/enzoampil/fastquant/blob/master/lessons/fastquant_lesson1_accessing_pse_data.ipynb Retrieves historical stock data for a specified company from the Philippine Stock Exchange (PSE). Requires stock symbol, start date, and end date. ```APIDOC ## GET /pse/stock ### Description Retrieves historical pricing data for a specified stock from the PSE. Supports custom date ranges and can save/read from a local CSV file. ### Method GET ### Endpoint /pse/stock ### Parameters #### Query Parameters - **symbol** (string) - Required - The stock symbol of the company (e.g., 'JFC' for Jollibee). - **start_date** (string) - Required - The starting date for the data in 'YYYY-MM-DD' format. - **end_date** (string) - Required - The ending date for the data in 'YYYY-MM-DD' format. - **stock_table_fp** (string) - Optional - File path for the stock table CSV. Defaults to 'stock_table.csv'. - **disclosures** (boolean) - Optional - Whether to include disclosures. Defaults to false. ### Response #### Success Response (200) - **DataFrame** (pandas.DataFrame) - A DataFrame containing the stock data in OHLCV (Open, High, Low, Close, Volume) format, indexed by date. ### Request Example ```python from fastquant import get_pse_data df = get_pse_data('JFC', '2018-01-01', '2019-01-01') print(df.head()) ``` ### Response Example ``` open high low close value dt 2018-01-03 253.4 256.8 253.0 255.4 190253754.0 2018-01-04 255.4 255.4 253.0 255.0 157152856.0 2018-01-05 255.6 257.4 255.0 255.0 242201952.0 2018-01-08 257.4 259.0 253.4 256.0 216069242.0 2018-01-09 256.0 258.0 255.0 255.8 250188588.0 ``` ``` -------------------------------- ### Multi-Strategy Backtest with FastQuant Source: https://github.com/enzoampil/fastquant/blob/master/examples/2020-05-20-backtest_crypto.ipynb This example demonstrates how to perform a multi-strategy backtest using the FastQuant library. It defines two strategies, 'smac' and 'rsi', with different parameter ranges. The `backtest` function is called with these strategies and a dataset named 'crypto'. The `plot=False` and `verbose=False` arguments are used to suppress output, while `return_history=True` ensures that detailed results and order history are returned. ```python from fastquant import backtest strats= { 'smac': { 'fast_period': [7,14], 'slow_period': [30,60] }, 'rsi': { 'rsi_upper': [70,80], 'rsi_lower': [20,30] } } results, history = backtest('multi', crypto, strats=strats, plot=False, verbose=False, return_history=True ) ``` -------------------------------- ### Backtest with Transaction History Source: https://github.com/enzoampil/fastquant/blob/master/API.md This example demonstrates how to configure the backtest function to return the transaction history. The history typically includes details of buy and sell operations. This functionality is useful for detailed analysis of trading performance. ```python from fastquant import backtest res, hist = backtest(..., return_history=True) ``` -------------------------------- ### Backtest Simple Moving Average Crossover Strategy with fastquant Source: https://github.com/enzoampil/fastquant/blob/master/README.md This code snippet shows a basic backtest of a Simple Moving Average Crossover strategy using fastquant's `backtest` function. It uses a 15-day and 40-day moving average on provided stock data (`df`). The function outputs the starting and final portfolio values. ```python from fastquant import backtest backtest('smac', df, fast_period=15, slow_period=40) # Starting Portfolio Value: 100000.00 # Final Portfolio Value: 102272.90 ``` -------------------------------- ### Import pandas library for data manipulation Source: https://github.com/enzoampil/fastquant/blob/master/lessons/2020-01-26-lesson1-accessing-pse_data.ipynb Imports the pandas library, which is essential for handling and manipulating tabular data in Python. This is a foundational step for most data analysis tasks. ```python import pandas as pd ``` -------------------------------- ### Simple Moving Average Crossover Analysis Source: https://github.com/enzoampil/fastquant/blob/master/lessons/fastquant_lesson1_accessing_pse_data.ipynb Analyzes stock data by calculating and plotting a Simple Moving Average (SMA) against the closing price. ```APIDOC ## POST /analyze/smac ### Description Calculates and visualizes the Simple Moving Average (SMA) alongside the daily closing prices for technical analysis. ### Method POST ### Endpoint /analyze/smac ### Parameters #### Request Body - **dataframe** (pandas.DataFrame) - Required - The DataFrame containing the stock data, expected to have a 'close' column. - **window** (integer) - Optional - The window period for the SMA calculation. Defaults to 30 days. - **title** (string) - Optional - The title for the plot. Defaults to 'Daily Closing Prices vs SMA'. ### Request Example ```python import pandas as pd # Assuming 'df' is a pandas DataFrame obtained from get_pse_data data = { 'close': [255.4, 255.0, 255.0, 256.0, 255.8, 257.0, 258.0, 257.5, 259.0, 260.0] * 10 } df_example = pd.DataFrame(data) ma30 = df_example.close.rolling(30).mean() close_ma30 = pd.concat([df_example.close, ma30], axis=1).dropna() close_ma30.columns = ['Closing Price', 'Simple Moving Average (30 day)'] close_ma30.plot(figsize=(10, 6)) plt.title("Daily Closing Prices vs 30 day SMA") plt.show() ``` ### Response #### Success Response (200) - **DataFrame** (pandas.DataFrame) - A DataFrame containing both the 'Closing Price' and the calculated 'Simple Moving Average'. - **image** (bytes) - The generated plot image showing both trends. #### Response Example ```json { "data": [ { "Closing Price": 276.586667, "Simple Moving Average (30 day)": 276.586667 }, { "Closing Price": 277.340000, "Simple Moving Average (30 day)": 277.340000 } ] } ``` (Image output of the plot) ``` -------------------------------- ### Plot closing prices vs. 30-day SMA Source: https://github.com/enzoampil/fastquant/blob/master/lessons/2020-01-26-lesson1-accessing-pse_data.ipynb Visualizes the daily closing prices alongside the 30-day simple moving average (SMA) on a single plot. This allows for direct comparison and identification of potential trading signals based on the crossover strategy. Requires matplotlib for plotting. ```python close_ma30.plot(figsize=(10, 6)) plt.title("Daily Closing Prices vs 30 day SMA of JFC\nfrom 2018-01-01 to 2019-01-01", fontsize=20) ``` -------------------------------- ### Backtest with Plot Return Source: https://github.com/enzoampil/fastquant/blob/master/API.md This example shows how to use the backtest function to generate and return a plot of the backtest results. The returned plot object can then be saved to a file. This is useful for visualizing the performance of a trading strategy. ```python from fastquant import backtest res, plot = backtest(..., return_plot=True) # Save plot plot.savefig('example.png') ``` -------------------------------- ### Import Libraries for Financial Network Analysis Source: https://github.com/enzoampil/fastquant/blob/master/examples/2020-06-10-network_analysis.ipynb Imports various Python libraries including pathlib, numpy, matplotlib, pandas, seaborn, and networkx, along with specific functions from fastquant. This setup is for advanced financial network analysis. ```python %matplotlib inline from pathlib import Path import numpy as np import matplotlib.pyplot as pl import matplotlib as mpl import pandas as pd import seaborn as sb import networkx as nx pl.style.use("default") from fastquant import get_pse_data_cache, get_stock_data, DATA_PATH ``` -------------------------------- ### Walk Forward Split in Expanding Mode (Python) Source: https://github.com/enzoampil/fastquant/blob/master/docs/docusaurus/docs/walk_forward_data_split.md This example demonstrates the 'expanding' mode for `walk_forward_split`. In this mode, each subsequent training set includes all the data from the previous training sets, effectively expanding the training window over time. The test set size remains consistent. ```python import numpy as np from fastquant.utils.data_split import walk_forward_split X = np.random.random(100) for train_indices, test_indices in walk_forward_split(X, mode='expanding'): print("TRAIN:",len(train_indices), train_indices) print("TEST: ", len(test_indices) ,test_indices) print() ``` -------------------------------- ### Fastquant: Get Twitter Sentiment Sample Usage Source: https://github.com/enzoampil/fastquant/blob/master/python/Get Twitter API Credentials.md Example of how to use the get_twitter_sentiment function in Fastquant, which requires stock code, Twitter authentication object, and optionally a list of Twitter accounts. ```python twitter_sentiment = get_twitter_sentiment(stock_code, twitter_auth, start_date, twitter_accounts=None) ``` -------------------------------- ### Fetch Stock Data with fastquant Source: https://github.com/enzoampil/fastquant/blob/master/examples/fastquant_demo.ipynb This snippet demonstrates fetching historical stock data using the `get_stock_data` function from the fastquant library. It requires a stock ticker symbol and a start and end date. The output is a pandas DataFrame containing daily stock prices. ```python from fastquant import get_stock_data df = get_stock_data('JFC', '2018-01-01', '2019-01-01') df.head() ``` -------------------------------- ### Fetch Stock Data using Yahoo Finance Source: https://github.com/enzoampil/fastquant/blob/master/examples/backtest_news_sentiment.ipynb This snippet demonstrates how to fetch historical stock data for a given ticker symbol from Yahoo Finance using the `get_yahoo_data` function from the fastquant library. It requires a ticker symbol and a date range as input. ```python from fastquant import get_yahoo_data #TESLA=TSLA in yahoo finance data = get_yahoo_data("TSLA", "2020-01-01", "2020-07-04") ``` -------------------------------- ### Initialize Backtesting Source: https://github.com/enzoampil/fastquant/blob/master/examples/2022-03-01-backtest_crypto_short.ipynb Imports the necessary `backtest` function from the fastquant library and the `backtrader` module, which are fundamental for setting up and running backtesting simulations. ```python from fastquant import backtest ``` ```python # Import modules import backtrader as bt ``` -------------------------------- ### Get Stock Data Source: https://github.com/enzoampil/fastquant/blob/master/lessons/2020-01-26-lesson1-accessing-pse_data.ipynb Retrieves historical stock pricing data for a specified stock symbol, date range, and source. It supports fetching data from the Philippine Stock Exchange (PSE) or Yahoo Finance. ```APIDOC ## GET /stock_data ### Description Returns pricing data for a specified stock and source. ### Method GET ### Endpoint /stock_data ### Parameters #### Query Parameters - **symbol** (str) - Required - Symbol of the stock in the PSE or Yahoo. - **start_date** (str) - Required - Starting date (YYYY-MM-DD) of the period. - **end_date** (str) - Required - Ending date (YYYY-MM-DD) of the period. - **source** (str) - Optional - Source to query from ("pse", "yahoo"). Defaults to "phisix". - **format** (str) - Optional - Format of the output data. Defaults to "c". ### Request Example ```json { "symbol": "JFC", "start_date": "2018-01-01", "end_date": "2019-01-01" } ``` ### Response #### Success Response (200) - **data** (pandas.DataFrame) - Stock data for the specified company and date range. #### Response Example ```json { "data": [ {"dt": "2018-01-03", "close": 255.4}, {"dt": "2018-01-04", "close": 255.0}, {"dt": "2018-01-05", "close": 255.0}, {"dt": "2018-01-08", "close": 256.0}, {"dt": "2018-01-09", "close": 255.8} ] } ``` ``` -------------------------------- ### Access Specific Disclosure Field - Python Source: https://github.com/enzoampil/fastquant/blob/master/lessons/fastquant_lesson1_accessing_pse_data.ipynb This example shows how to access a specific field, 'Template Name', from a particular disclosure entry (the 16th entry, index 15) within the `jfc_disclosures` DataFrame. It uses pandas indexing with `.iloc[15]['Template Name']`. ```python jfc_disclosures.iloc[15]['Template Name'] ``` -------------------------------- ### Get PSE Stock Data with FastQuant Source: https://github.com/enzoampil/fastquant/blob/master/lessons/fastquant_lesson1_accessing_pse_data.ipynb Fetches historical stock data for a given symbol from the PSE. Requires the stock symbol and date range as input. Outputs a pandas DataFrame containing OHLCV data. Ensure date strings are in YYYY-MM-DD format. Dependencies: fastquant. ```python from fastquant import get_pse_data df = get_pse_data('JFC', '2018-01-01', '2019-01-01') df.head() ``` -------------------------------- ### Initialize DisclosuresPSE for JFC Trading Strategy Source: https://github.com/enzoampil/fastquant/blob/master/examples/backtest_disclosures.ipynb This Python code initializes the DisclosuresPSE class from the FastQuant library to fetch company disclosures for Jollibee Foods Corporation (JFC) starting from January 1, 2015. It requires the 'fastquant' library to be installed. The output shows the process of pulling and analyzing disclosures, including the number of pages, disclosure types, and the date range covered. ```python from fastquant import DisclosuresPSE dpse = DisclosuresPSE("JFC", start_date="01-01-2015") ``` -------------------------------- ### Portfolio Optimization with FastQuant Library Source: https://github.com/enzoampil/fastquant/blob/master/examples/2020-06-20-basic_portfolio.ipynb Initializes a Portfolio object from the fastquant library with a given list of stocks and date range. It then plots the historical data and generates portfolio simulations. Requires 'Portfolio' to be imported from 'fastquant'. ```python from fastquant import Portfolio stock_list = ['MEG', 'MAXS', 'JFC', 'ALI'] p = Portfolio(stock_list,"2017-01-01", "2020-01-01") axs = p.data.plot(subplots=True, figsize=(15,10)) fig = p.plot_portfolio(N=1000) ``` -------------------------------- ### Sentiment Analysis Initialization - Python Source: https://github.com/enzoampil/fastquant/blob/master/examples/backtest_disclosures.ipynb This Python code snippet initializes the necessary libraries for sentiment analysis and data handling. It imports modules for web requests, HTML parsing, date/time manipulation, natural language processing (nltk), and specifically configures the VADER sentiment intensity analyzer. Warnings are suppressed to keep the output clean. ```python from urllib.request import urlopen from bs4 import BeautifulSoup from datetime import datetime import time import nltk import warnings warnings.filterwarnings('ignore') from nltk.sentiment.vader import SentimentIntensityAnalyzer ``` -------------------------------- ### Compare Basic vs. Optimized Grid Search Time Source: https://github.com/enzoampil/fastquant/blob/master/examples/2020-04-20-backtest_with_grid_search.ipynb Calculates and displays the ratio between the time taken for a basic loop-based grid search and the optimized built-in grid search in FastQuant, demonstrating the performance improvement. ```python #time time_basic/time_optimized ``` -------------------------------- ### Install TA Library for Technical Analysis Source: https://github.com/enzoampil/fastquant/blob/master/examples/feature_extraction_crypto_20200824.ipynb Installs the 'ta' library, which provides a wide range of technical analysis indicators. This is a prerequisite for adding TA features to financial dataframes. ```python !pip3 install ta ``` -------------------------------- ### Backtest EMAC Strategy with FastQuant Source: https://github.com/enzoampil/fastquant/blob/master/examples/2022-03-01-backtest_crypto_short.ipynb This Python code snippet demonstrates how to perform a backtest using the EMACStrategy with specific parameters. It utilizes the `backtest` function from FastQuant, specifying the strategy, data, custom periods, and output options. The function returns results and history, including order details. ```python results, history = backtest(EMACStrategy, crypto, fast_period = 20, slow_period = 50, plot=False, verbose=False, return_history=True, # allow_short=True, ) ``` -------------------------------- ### Import Fastquant Functions Source: https://github.com/enzoampil/fastquant/blob/master/lessons/2020-03-09-lesson2-backtest-your-trading-strategy.ipynb Imports the 'backtest' and 'get_stock_data' functions from the fastquant library. These are essential for performing backtests and retrieving stock market data, respectively. ```python from fastquant import backtest, get_stock_data ``` -------------------------------- ### Clone fastquant Repository Source: https://github.com/enzoampil/fastquant/blob/master/CONTRIBUTING.md This command clones the fastquant repository from GitHub to your local machine. It's the first step in setting up the project for local development. ```shell git clone git@github.com:your_name_here/fastquant.git ``` -------------------------------- ### Summarize Trading Strategy Profit Percentages Source: https://github.com/enzoampil/fastquant/blob/master/examples/2022-03-01-backtest_crypto_short.ipynb This Python code provides a summary of profit percentages for different trading approaches: buy and hold, long only, and long and short. It rounds the percentages to two decimal places for clarity and prints them with descriptive labels. This allows for a quick comparison of strategy effectiveness. ```python print(f"Buy and hold profit %: {round((crypto.iloc[-1, 3] - crypto.iloc[0, 3])/crypto.iloc[0, 3]*100, 2)}%") print(f"Long only profit %: {round(profit, 2)}%") print(f"Long and Short profit %: {round(profit2, 2)}%") ```