### Initialize Pandas TA and Dependencies Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/PandasTA_Strategy_Examples.ipynb Initializes the Pandas TA library and other necessary dependencies like datetime, tqdm, pandas, and AlphaVantage. It also prints the installed Pandas TA version and provides an installation command. The `%matplotlib inline` and `%pylab inline` magic commands are used for plotting within an interactive environment. ```python %matplotlib inline import datetime as dt from tqdm import tqdm import pandas as pd import pandas_ta as ta from alphaVantageAPI.alphavantage import AlphaVantage # pip install alphaVantage-api from watchlist import Watchlist # Is this failing? If so, copy it locally. See above. print(f"\nPandas TA v{ta.version}\nTo install the Latest Version:\n$ pip install -U git+https://github.com/twopirllc/pandas-ta\n") %pylab inline ``` -------------------------------- ### Install Required Packages for Strategy Analysis Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/AIExample.ipynb Installs essential Python packages for financial data analysis and strategy development using libraries like NumPy, Pandas, mplfinance, pandas-datareader, and others. Uncomment specific lines to install the packages as needed. ```python #!pip install numpy #!pip install pandas #!pip install mplfinance #!pip install pandas-datareader #!pip install requests_cache #!pip install tqdm #!pip install alphaVantage-api # Required for Watchlist ``` -------------------------------- ### Import Libraries and Setup Environment for Financial Analysis Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/AIExample.ipynb Imports necessary libraries including pylab, datetime, random, sys, tqdm, NumPy, Pandas, mplfinance, and pandas_ta. It also configures Pandas display options and prints version information for key libraries. This setup is crucial for financial data manipulation and technical analysis. ```python %pylab inline import datetime as dt import random as rnd from sys import float_info as sflt from tqdm import tqdm import numpy as np import pandas as pd pd.set_option("max_rows", 100) pd.set_option("max_columns", 20) import mplfinance as mpf import pandas_ta as ta from tqdm.notebook import trange, tqdm from watchlist import colors, Watchlist # Is this failing? If so, copy it locally. See above. print(f"Numpy v{np.__version__}") print(f"Pandas v{pd.__version__}") print(f"mplfinance v{mpf.__version__}") print(f"\nPandas TA v{ta.version}\nTo install the Latest Version:\n$ pip install -U git+https://github.com/twopirllc/pandas-ta ") %matplotlib inline ``` -------------------------------- ### Install and Check Package Versions (Python) Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb Imports necessary libraries for data analysis and backtesting, prints installed package versions, and provides instructions for updating pandas_ta. Dependencies include asyncio, itertools, datetime, IPython, numpy, pandas, pandas_ta, and vectorbt. ```python import asyncio import itertools from datetime import datetime from IPython import display import numpy as np import pandas as pd import pandas_ta as ta import vectorbt as vbt import plotly.graph_objects as go print("Package Versions:") print(f"Numpy v{np.__version__}") print(f"Pandas v{pd.__version__}") print(f"vectorbt >= v0.18.1") print(f"\nPandas TA v{ta.version}\nTo install the Latest Version:\n$ pip install -U git+https://github.com/twopirllc/pandas-ta\n") %matplotlib inline ``` -------------------------------- ### Setup and Version Check for Pandas TA Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/example.ipynb This snippet sets up the environment for technical analysis using pandas_ta. It imports necessary libraries, checks the installed pandas_ta version, and provides instructions for updating to the latest version. It also configures matplotlib for inline plotting. ```python %matplotlib inline import datetime as dt import random as rnd from tqdm import tqdm import numpy as np import pandas as pd import matplotlib.ticker as ticker import mplfinance as mpf from alphaVantageAPI.alphavantage import AlphaVantage import pandas_ta as ta from watchlist import colors # Is this failing? If so, copy it locally. See above. print(f"\nPandas TA v{ta.version}\nTo install the Latest Version:\n$ pip install -U git+https://github.com/twopirllc/pandas-ta\n") %pylab inline ``` -------------------------------- ### Get Help for Pandas TA EMA Indicator Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/example.ipynb This snippet shows how to access the help documentation for a specific indicator within the pandas_ta library, using the Exponential Moving Average (EMA) as an example. It details the indicator's purpose, calculation methods, arguments, and return values. ```python help(ta.ema) ``` -------------------------------- ### Download Financial Ticker Data with Pandas-TA Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb Downloads historical price data for one or more tickers using Pandas-TA. It supports optional arguments for data fetching and can align the start dates of multiple tickers if requested. Useful for preparing data for technical analysis or backtesting. ```python def dl(tickers: list, same_start: bool = False, **kwargs): if isinstance(tickers, str): tickers = [tickers] if not isinstance(tickers, list) or len(tickers) == 0: print("Must be a non-empty list of tickers or symbols") return if "limit" in kwargs and kwargs["limit"] and len(tickers) > kwargs["limit"]: from itertools import islice tickers = list(islice(tickers, kwargs["limit"])) print(f"[!] Too many assets to compare. Using the first {kwargs['limit']}: {', '.join(tickers)}") print(f"[i] Downloading: {', '.join(tickers)}") received = {} if len(tickers): _df = pd.DataFrame() for ticker in tickers: received[ticker] = _df.ta.ticker(ticker, **kwargs) print(f"[+] {ticker}{received[ticker].shape} {ta.get_time(full=False, to_string=True)}") if same_start and len(tickers) > 1: earliestci = earliest_common_index(received) print(f"[i] Earliest Common Date: {earliestci}") result = {ticker:df[df.index > earliestci].copy() for ticker,df in received.items()} else: result = received print(f"[*] Download Complete\n") return result ``` -------------------------------- ### Load Single Ticker with Plotting and SMAs Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/PandasTA_Strategy_Examples.ipynb Loads data for a single ticker ('SPY') into the watchlist, with options to enable plotting and the calculation of Simple Moving Averages (SMAs). The output confirms the data loading and displays the DataFrame, similar to the previous example, but potentially with SMAs already calculated if `mas=True` triggers their computation. ```python watch.load("SPY", plot=True, mas=True) ``` -------------------------------- ### Define Testing Date Range in Python Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb Sets the start and end dates for the backtesting period using Python's datetime objects. These dates define the historical window for analysis. ```python from datetime import datetime start_date = datetime(2005, 1, 1) # Adjust as needed end_date = datetime(2010, 1, 1) # Adjust as needed ``` -------------------------------- ### Select and Filter Data for Backtesting in Python Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb Selects a specific benchmark and asset by name and filters their respective dataframes to fall within the defined start and end dates using the 'dtmask' function. This ensures backtesting is performed on the correct and relevant data. ```python benchmark_name = "SPY" # Select a Benchmark asset_name = "AAPL" # Select an Asset benchmarkdf = benchmarks[benchmark_name] assetdf = assets[asset_name] # Set True if you want to constrain Data between start_date & end_date common_range = True if common_range: crs = f" from {start_date} to {end_date}" benchmarkdf = dtmask(benchmarkdf, start_date, end_date) assetdf = dtmask(assetdf, start_date, end_date) ``` -------------------------------- ### Initialize Watchlist for Tickers with Specified Timeframe and Data Source Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/AIExample.ipynb Creates a Watchlist object to monitor specified stock tickers ('SPY', 'QQQ', etc.) with a daily ('D') timeframe, fetching data from Yahoo Finance. The 'timed=True' argument suggests performance timing for data loading. ```python tf = "D" tickers = ["SPY", "QQQ", "AAPL", "TSLA", "BTC-USD"] watch = Watchlist(tickers, tf=tf, ds_name="yahoo", timed=True) ``` -------------------------------- ### Benchmark Buy and Hold Strategy with VectorBT Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb This code snippet initializes a portfolio using VectorBT's `from_holding` method with benchmark data. It then prints the trade table and combines strategy statistics with benchmark data. Dependencies include vectorbt and pandas. The input is benchmark data (DataFrame) and a boolean flag for LIVE mode. ```python benchmarkpf_bnh = vbt.Portfolio.from_holding(benchmarkdf.close) print(trade_table(benchmarkpf_bnh)) combine_stats(benchmarkpf_bnh, benchmarkdf.name, "Buy and Hold", LIVE) ``` -------------------------------- ### Configure VectorBT Theme and Portfolio Settings (Python) Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb Sets up the visual theme and default portfolio parameters for vectorbt backtesting. This includes defining chart dimensions, selecting a theme (e.g., 'dark'), and configuring trading parameters like frequency, fees, and slippage. This configuration is crucial for consistent backtesting results. ```python cheight, cwidth = 500, 1000 # Adjust as needed for Chart Height and Width vbt.settings.set_theme("dark") # Options: "light" (Default), "dark" (my fav), "seaborn" # Must be set vbt.settings.portfolio["freq"] = "1D" # Daily # Predefine vectorbt Portfolio settings # vbt.settings.portfolio["init_cash"] = 100 vbt.settings.portfolio["fees"] = 0.0025 # 0.25% vbt.settings.portfolio["slippage"] = 0.0025 # 0.25% # vbt.settings.portfolio["size"] = 100 ``` -------------------------------- ### Filter DataFrame by Date Range Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb Selects rows from a Pandas DataFrame that fall within a specified start and end datetime. This function is useful for isolating data for specific trading periods or analysis windows. ```python def dtmask(df: pd.DataFrame, start: datetime, end: datetime): return df.loc[(df.index >= start) & (df.index <= end), :].copy() ``` -------------------------------- ### Load and Analyze Data with Freqtrade Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/AIExample.ipynb This code snippet demonstrates loading historical data for multiple tickers using Freqtrade's watch functionality and performing an initial analysis. It handles data downloading, saving, and provides runtime statistics for each ticker. ```python watch.load(tickers, analyze=True, verbose=False) ``` -------------------------------- ### Initialize AlphaVantage Data Source Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/PandasTA_Strategy_Examples.ipynb Initializes the AlphaVantage data source for retrieving financial data. It requires an API key and allows configuration of output size, data cleaning, and export options. The result is an AlphaVantage object configured for data retrieval. ```python AV = AlphaVantage( api_key="YOUR API KEY", premium=False, output_size='full', clean=True, export_path=".", export=True ) AV ``` -------------------------------- ### Inspect Watchlist Class Documentation Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/PandasTA_Strategy_Examples.ipynb Displays the help documentation for the Watchlist class. This provides detailed information about its constructor, methods, and data descriptors, including supported data sources and requirements for initialization. ```python help(Watchlist) ``` -------------------------------- ### Define Long Trend using EMA Crossover Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/AIExample.ipynb This Python code defines a 'long' trend condition based on the Exponential Moving Average (EMA) crossover strategy. It checks if the 8-period EMA is greater than the 21-period EMA of the asset's closing prices. This is a common trend-following indicator setup. ```python # Example Long Trends # long = ta.sma(asset.close, 50) > ta.sma(asset.close, 200) # SMA(50) > SMA(200) "Golden/Death Cross" # long = ta.sma(asset.close, 10) > ta.sma(asset.close, 20) # SMA(10) > SMA(20) long = ta.ema(asset.close, 8) > ta.ema(asset.close, 21) # EMA(8) > EMA(21) # long = ta.increasing(ta.ema(asset.close, 50)) # long = ta.macd(asset.close).iloc[:,1] > 0 # MACD Histogram is positive # long = ta.amat(asset.close, 50, 200).AMATe_LR_2 # Long Run of AMAT(50, 200) with lookback of 2 bars # long &= ta.increasing(ta.ema(asset.close, 50), 2) # Uncomment for further long restrictions, in this case when EMA(50) is increasing/sloping upwards ``` -------------------------------- ### Initialize and Analyze Buy and Hold Portfolio with Vectorbt Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb This Python code initializes a 'Buy and Hold' portfolio using vectorbt, prints the trade table, and combines performance statistics. It requires the vectorbt library and assumes assetdf is a pre-defined DataFrame containing asset data. ```python import vectorbt as vbt import pandas as pd # Assuming assetdf is a pandas DataFrame with a 'close' column and 'name' # For demonstration, let's create a dummy assetdf asset_data = { 'timestamp': pd.to_datetime(['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04', '2023-01-05']), 'open': [100, 101, 102, 103, 104], 'high': [102, 103, 104, 105, 106], 'low': [99, 100, 101, 102, 103], 'close': [101, 102, 103, 104, 105], 'volume': [1000, 1100, 1200, 1300, 1400] } assetdf = pd.DataFrame(asset_data) assetdf = assetdf.set_index('timestamp') assetdf.name = 'DUMMY' # Initialize Buy and Hold portfolio assetpf_bnh = vbt.Portfolio.from_holding(assetdf.close) # Print trade table and combine statistics # Note: 'trade_table' and 'combine_stats' are custom functions not standard in vectorbt or pandas # These would need to be defined elsewhere in the project. # print(trade_table(assetpf_bnh)) # combine_stats(assetpf_bnh, assetdf.name, "Buy and Hold", LIVE) # Assuming LIVE is defined ``` -------------------------------- ### Display Available Data Keys in Python Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb Prints the keys (symbols) of the downloaded benchmark and asset dataframes. This helps in verifying the downloaded data and selecting symbols for backtesting. ```python print("Available Data:") print("="*100) print(f"Benchmarks: {', '.join(benchmarks.keys())}") print(f"Assets: {', '.join(assets.keys())}") ``` -------------------------------- ### Create Watchlist with AlphaVantage Data Source Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/PandasTA_Strategy_Examples.ipynb Creates a Watchlist object, specifying the tickers to monitor and the data source to use (defaulting to 'av' for AlphaVantage). The 'timed' parameter controls whether time-series data is loaded. The Watchlist object is then printed to display its configuration. ```python data_source = "av" # Default # data_source = "yahoo" watch = Watchlist(["SPY", "IWM"], ds_name=data_source, timed=False) watch ``` -------------------------------- ### Apply Defined Strategy to Watchlist and Load Data (Python) Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/PandasTA_Strategy_Examples.ipynb This snippet updates the Freqtrade 'watch' object with the previously defined 'vp_ma_chain_ta' strategy and then loads the 'SPY' dataset. This demonstrates how to apply a custom strategy and load market data for analysis. ```python # Update the Watchlist watch.strategy = vp_ma_chain_ta spy = watch.load("SPY") ``` -------------------------------- ### Download Benchmark Data with Pandas-TA in Python Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb Downloads historical data for specified benchmark tickers using the 'dl' function, likely from a financial data source. It includes an option to load column names into lowercase. ```python benchmarks = dl(benchmark_tickers, lc_cols=True) ``` -------------------------------- ### Download Asset Data with Pandas-TA in Python Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb Downloads historical data for specified asset tickers using the 'dl' function, similar to benchmark data download. This prepares the data for analysis and backtesting. ```python assets = dl(asset_tickers, lc_cols=True) ``` -------------------------------- ### Filter and Prepare Asset Data for Analysis Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/AIExample.ipynb This Python code prepares a single asset's data for technical analysis by selecting a recent duration, converting column names to lowercase, dropping irrelevant columns ('dividends', 'split'), and creating a copy of the tail data. It ensures the data is clean and ready for indicator calculations. ```python duration = "1y" asset = watch.data[ticker] recent = recent_bars(asset, duration) asset.columns = asset.columns.str.lower() asset.drop(columns=["dividends", "split"], errors="ignore", inplace=True) asset = asset.copy().tail(recent) asset ``` -------------------------------- ### Generate Portfolio from Trade Signals (Python) Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb Creates a portfolio object from trade signals using VectorBT. It requires benchmark DataFrame with closing prices and a DataFrame with entry and exit signals. Outputs a portfolio object that can be further analyzed. ```python benchmarkpf_signals = vbt.Portfolio.from_signals( benchmarkdf.close, entries=benchmark_signals.TS_Entries, exits=benchmark_signals.TS_Exits, ) ``` -------------------------------- ### Create Portfolio from Signals using VectorBT Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb Generates a trading portfolio directly from entry and exit signals. It takes a DataFrame of asset data (e.g., closing prices) and signal DataFrames for entries and exits. The output is a Portfolio object that can be further analyzed. ```python assetpf_signals = vbt.Portfolio.from_signals( assetdf.close, entries=asset_signals.TS_Entries, exits=asset_signals.TS_Exits, ) trade_table(assetpf_signals, k=5) combine_stats(assetpf_signals, assetdf.name, "Long Strategy", LIVE) ``` -------------------------------- ### Compare Buy-and-Hold vs. Cumulative Active Returns (Python) Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/AIExample.ipynb Compares the cumulative performance of Buy-and-Hold strategy (based on PCTRET_1) against Cumulative Active Returns (based on ACTRET_1). The plot uses an area chart to visualize the growth of both strategies over time, highlighting the effectiveness of active trading strategies. ```python ((asset[["PCTRET_1", "ACTRET_1"]] + 1).cumprod() - 1).plot(figsize=(16, 3), kind="area", stacked=False, color=colors("GyOr"), title="B&H vs. Cum. Active Returns", alpha=.4, grid=True).axhline(0, color="black") ``` -------------------------------- ### Display Trade Table and Combine Stats (Python) Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb Visualizes the top trades from a portfolio and combines strategy statistics with benchmark data. It uses functions `trade_table` and `combine_stats` for reporting. Requires a portfolio object, benchmark DataFrame, strategy name, and a mode (e.g., LIVE). ```python trade_table(benchmarkpf_signals, k=5) combine_stats(benchmarkpf_signals, benchmarkdf.name, "Long Strategy", LIVE) ``` -------------------------------- ### Set Strategy and Load Custom Strategy Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/PandasTA_Strategy_Examples.ipynb Sets the Freqtrade strategy to 'custom_a' and then loads this custom strategy into the watchlist. This demonstrates the flexibility of swapping trading strategies within Freqtrade. ```python # Load custom_a into Watchlist and verify watch.strategy = custom_a ``` -------------------------------- ### List Available Pandas TA Indicators Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/example.ipynb This code snippet demonstrates how to retrieve and display a complete list of all available technical analysis indicators and candle patterns supported by the pandas_ta library. It's useful for understanding the library's capabilities and finding specific indicators. ```python e = pd.DataFrame() e.ta.indicators() ``` -------------------------------- ### Combine Portfolio Stats with Run Details Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb Combines key portfolio performance metrics and settings into a single Pandas Series. It includes strategy details, execution parameters like fees and slippage, and returns statistics. This function is useful for summarizing backtesting results. ```python def combine_stats(pf: vbt.portfolio.base.Portfolio, ticker: str, strategy: str, mode: int = 0): header = pd.Series({ "Run Time": ta.get_time(full=False, to_string=True), "Mode": "LIVE" if mode else "TEST", "Strategy": strategy, "Direction": vbt.settings.portfolio["signal_direction"], "Symbol": ticker.upper(), "Fees [%]": 100 * vbt.settings.portfolio["fees"], "Slippage [%]": 100 * vbt.settings.portfolio["slippage"], "Accumulate": vbt.settings.portfolio["accumulate"], }) rstats = pf.returns_stats().dropna(axis=0).T stats = pf.stats().dropna(axis=0).T joint = pd.concat([header, stats, rstats]) return joint[~joint.index.duplicated(keep="first")] ``` -------------------------------- ### Process Trend Signals into Trade Table Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/AIExample.ipynb This snippet processes the trend signals generated by `tsignals` to create a trade table. It calculates entry and exit points based on signals and asset close prices, filters out zero values, and constructs a DataFrame summarizing trades. It also calculates and prints trade statistics like total trades, round trip trades, and trade coverage. ```python import numpy as np import pandas as pd entries = trendy.TS_Entries * asset.close entries = entries[~np.isclose(entries, 0)] entries.dropna(inplace=True) entries.name = "Entry" exits = trendy.TS_Exits * asset.close exits = exits[~np.isclose(exits, 0)] exits.dropna(inplace=True) exits.name = "Exit" total_trades = trendy.TS_Trades.abs().sum() rt_trades = int(trendy.TS_Trades.abs().sum() // 2) all_trades = trendy.TS_Trades.copy().fillna(0) all_trades = all_trades[all_trades != 0] trades = pd.DataFrame({ "Signal": all_trades, entries.name: entries, exits.name: exits }) # Show some stats if there is an active trade (when there is an odd number of round trip trades) if total_trades % 2 != 0: unrealized_pnl = asset.close.iloc[-1] - entries.iloc[-1] unrealized_pnl_pct_change = 100 * ((asset.close.iloc[-1] / entries.iloc[-1]) - 1) print("Current Trade:") print(f"Price Entry | Last:\t{entries.iloc[-1]:.4f} | {asset.close.iloc[-1]:.4f}") print(f"Unrealized PnL | %:\t{unrealized_pnl:.4f} | {unrealized_pnl_pct_change:.4f}%") print(f"\nTrades Total | Round Trip:\t{total_trades} | {rt_trades}") print(f"Trade Coverage: {100 * asset.TS_Trends.sum() / asset.shape[0]:.2f}%") trades ``` -------------------------------- ### Update Watchlist Strategy and Load Data with Pandas-TA Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/PandasTA_Strategy_Examples.ipynb This snippet updates the Freqtrade `watch.strategy` with the previously defined custom strategy. It then loads the 'SPY' dataset using `watch.load()` and displays the tail of the DataFrame, which now includes the indicators defined in the strategy. ```python # Update the Watchlist watch.strategy = params_ta_strategy watch.strategy.name spy = watch.load("SPY") spy.tail() ``` -------------------------------- ### Display Ticker Data Shape and Columns Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/AIExample.ipynb This Python code snippet retrieves data for a specific ticker from Freqtrade's watch object and prints its shape (number of rows and columns) and a list of its column names. This is useful for understanding the structure of the loaded financial data. ```python ticker = tickers[0] # change tickers by changing the index print(f"{ticker} {watch.data[ticker].shape}\nColumns: {', '.join(list(watch.data[ticker].columns))}") ``` -------------------------------- ### Load All Tickers into Watchlist Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/PandasTA_Strategy_Examples.ipynb Loads all available tickers into the Freqtrade watchlist, applying a 'Common Price and Volume SMAs' strategy. It processes multiple indicators across several chunks, utilizing available CPU cores. The output indicates successful loading and provides details about the strategy and indicator processing. ```python watch.load(verbose=True) ``` -------------------------------- ### Generate Chart with Squeeze Indicator (Lazybear Version) Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/example.ipynb Generates a financial chart with the Lazybear version of the Squeeze Indicator. This allows for a specific visualization of volatility using this variant. Dependencies include pandas, pandas-ta, alphaVantage-api, and mplfinance. ```python Chart(df, style="yahoo", title=ticker, verbose=False, last=recent_bars(df), rpad=10, clr=True, squeeze=True, lazybear=True, show_nontrading=False, # Intraday use if needed ) ``` -------------------------------- ### Specify Benchmark and Asset Tickers in Python Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb Defines lists of benchmark and asset tickers, combines them, and prints them with their respective indices. This is crucial for organizing and referencing trading instruments. ```python benchmark_tickers = ["SPY", "QQQ"] asset_tickers = ["AAPL", "TSLA", "TWTR"] all_tickers = benchmark_tickers + asset_tickers print("Tickers by index #") print("="*100) print(f"Benchmarks: {', '.join([f'{k}: {v}' for k,v in enumerate(benchmark_tickers)])}") print(f" Assets: {', '.join([f'{k}: {v}' for k,v in enumerate(asset_tickers)])}") print(f" All: {', '.join([f'{k}: {v}' for k,v in enumerate(all_tickers)])}") ``` -------------------------------- ### Display Data Summary for Tickers Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb Prints a summary for each DataFrame in a dictionary, including the ticker symbol, date range, shape, and time span in years. This provides a quick overview of the downloaded financial data. ```python def show_data(d: dict): [print(f"{t}[{df.index[0]} - {df.index[-1]}]: {df.shape} {df.ta.time_range:.2f} years") for t,df in d.items()] ``` -------------------------------- ### Format Chart Title with Time and Asset Info Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/AIExample.ipynb This Python snippet formats a title string for a chart. It includes the ticker symbol, timeframe, duration, number of bars, date range, and the last OHLCV (Open, High, Low, Close, Volume) data. It also incorporates the current time obtained using `ta.get_time()`. ```python # Assuming 'ta', 'asset', 'ticker', 'tf', 'duration', 'recent' are defined elsewhere # extime = ta.get_time(to_string=True) # first_date, last_date = asset.index[0], asset.index[-1] # f_date = f"{first_date.day_name()} {first_date.month}-{first_date.day}-{first_date.year}" # l_date = f"{last_date.day_name()} {last_date.month}-{last_date.day}-{last_date.year}" # last_ohlcv = f"Last OHLCV: ({asset.iloc[-1].open:.4f}, {asset.iloc[-1].high:.4f}, {asset.iloc[-1].low:.4f}, {asset.iloc[-1].close:.4f}, {int(asset.iloc[-1].volume)})" # ptitle = f"\n{ticker} [{tf} for {duration}({recent} bars)] from {f_date} to {l_date}\n{last_ohlcv}\n{extime}" ``` -------------------------------- ### Select Specific Benchmark and Asset in Python Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb Selects a single benchmark and asset ticker from predefined lists using their indices. This allows for focused backtesting on a specific pair of instruments. ```python benchmark = benchmark_tickers[0] # Change index for different benchmark asset = asset_tickers[2] # Change index for different symbol print(f"Selected Benchmark | Asset: {benchmark} | {asset}") ``` -------------------------------- ### Generate Chart with Squeeze Indicator (Standard) Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/example.ipynb Generates a financial chart displaying the Squeeze Indicator using the Chart class. This function visualizes price action and includes the squeeze indicator. Dependencies include pandas, pandas-ta, alphaVantage-api, and mplfinance. ```python # help(ta.squeeze) Chart(df, style="yahoo", title=ticker, verbose=False, last=recent_bars(df), rpad=10, clr=True, squeeze=True, show_nontrading=False, # Intraday use if needed ) ``` -------------------------------- ### Access Built-in AllStrategy Properties Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/PandasTA_Strategy_Examples.ipynb Retrieves and prints the properties of the built-in `AllStrategy` from the Pandas TA library. This strategy includes all indicators with their default settings. ```python AllStrategy = ta.AllStrategy print("name =", AllStrategy.name) print("description =", AllStrategy.description) print("created =", AllStrategy.created) print("ta =", AllStrategy.ta) ``` -------------------------------- ### Calculate EMA and Percent Return with Pandas TA Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/AIExample.ipynb This snippet demonstrates how to append Exponential Moving Averages (EMA) with different lengths and calculate the percentage return for an asset using the pandas-ta library. The results are appended directly to the asset DataFrame. It assumes an 'asset' DataFrame with OHLCV data is already available. ```python asset.ta.ema(length=8, sma=False, append=True) asset.ta.ema(length=21, sma=False, append=True) asset.ta.ema(length=50, sma=False, append=True) asset.ta.percent_return(append=True) print("TA Columns Added:") print(asset[asset.columns[5:]].tail()) ``` -------------------------------- ### Generate Chart with Archer On Balance Volume Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/example.ipynb Generates a financial chart displaying Archer On Balance Volume (AOBV) and its associated moving averages. The chart includes OBV, OBV min/max, and fast/slow OBV MAs. Dependencies include pandas, pandas-ta, alphaVantage-api, and mplfinance. ```python Chart(df, style="yahoo", title=ticker, verbose=False, last=recent_bars(df), rpad=10, volume=True, midpoint=False, ohlc4=False, rsi=False, clr=True, macd=False, zscore=False, squeeze=False, lazybear=False, archermas=False, archerobv=True, show_nontrading=False, # Intraday use if needed ) ``` -------------------------------- ### Define Custom Strategy with Pandas-TA Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/PandasTA_Strategy_Examples.ipynb This code defines a custom trading strategy named 'EMA, MACD History, Outter BBands, Log Returns' using `ta.Strategy`. It specifies a list of technical indicators (EMA, MACD, BBands, Log Returns) with their respective parameters and desired output columns. The `params_ta_strategy` object encapsulates this configuration. ```python params_ta = [ {"kind":"ema", "params": (10,)}, # params sets MACD's keyword arguments: fast=9, slow=19, signal=10 # and returning the 2nd column: histogram {"kind":"macd", "params": (9, 19, 10), "col_numbers": (1,)}, # Selects the Lower and Upper Bands and renames them LB and UB, ignoring the MB {"kind":"bbands", "col_numbers": (0,2), "col_names": ("LB", "UB")}, {"kind":"log_return", "params": (5, False)}, ] params_ta_strategy = ta.Strategy( "EMA, MACD History, Outter BBands, Log Returns", # name params_ta, # ta "EMA, MACD History, BBands(LB, UB), and Log Returns Strategy" # description ) params_ta_strategy ``` -------------------------------- ### Load and Display Strategy A with SMA Indicators Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/PandasTA_Strategy_Examples.ipynb Loads a trading strategy named 'A' with Simple Moving Average (SMA) indicators of lengths 50 and 200. It then loads the 'IWM' stock data and displays the resulting DataFrame with calculated SMA values. This demonstrates basic strategy loading and data processing. ```python watch.load("IWM") ``` -------------------------------- ### Calculate and Plot Active Returns (Python) Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/AIExample.ipynb Calculates and plots 'Active Returns' (ACTRET_1), which represent returns made during the course of a trend, by multiplying trend signals with daily percentage returns (PCTRET_1). It also plots the original daily percentage returns for comparison. ```python asset["ACTRET_1"] = trendy.TS_Trends.shift(1) * asset.PCTRET_1 asset[["PCTRET_1", "ACTRET_1"]].plot(figsize=(16, 3), color=colors("GyOr"), alpha=1, grid=True).axhline(0, color="black") ``` -------------------------------- ### Charting Class for Technical Analysis and Plotting (Python) Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/example.ipynb A Python class designed for creating financial charts using pandas-TA for technical analysis and mplfinance for plotting. It initializes with a pandas DataFrame and a strategy, validates charting configurations, applies technical indicators, and generates plots. Dependencies include pandas, pandas-ta, and mplfinance. ```python import pandas as pd import pandas_ta as ta import mplfinance as mpf import numpy as np import random as rnd def recent_bars(df: pd.DataFrame): return df.shape[0] // 5 class Chart(object): def __init__(self, df: pd.DataFrame = None, strategy: ta.Strategy = ta.CommonStrategy, *args, **kwargs): self.verbose = kwargs.pop("verbose", False) if isinstance(df, pd.DataFrame) and df.ta.datetime_ordered: self.df = df if self.df.name is not None and self.df.name != "": df_name = str(self.df.name) else: df_name = "DataFrame" if self.verbose: print(f"[i] Loaded {df_name}{self.df.shape}") else: print(f"[X] Oops! Missing 'ohlcv' data or index is not datetime ordered.\n") return None self._validate_mpf_kwargs(**kwargs) self._validate_chart_kwargs(**kwargs) self._validate_ta_strategy(strategy) # Build TA and Plot self.df.ta.strategy(self.strategy, verbose=self.verbose) self._plot(**kwargs) def _validate_ta_strategy(self, strategy): if strategy is not None or isinstance(strategy, ta.Strategy): self.strategy = strategy elif len(self.strategy_ta) > 0: print(f"[+] Strategy: {self.strategy_name}") else: self.strategy = ta.CommonStrategy def _validate_chart_kwargs(self, **kwargs): """Chart Settings""" self.config = {} self.config["last"] = kwargs.pop("last", recent_bars(self.df)) self.config["rpad"] = kwargs.pop("rpad", 10) self.config["title"] = kwargs.pop("title", "Asset") self.config["volume"] = kwargs.pop("volume", True) def _validate_mpf_kwargs(self, **kwargs): # mpf global chart settings default_chart = mpf.available_styles()[-1] default_mpf_width = { 'candle_linewidth': 0.6, 'candle_width': 0.525, 'volume_width': 0.525 } mpfchart = {} mpf_style = kwargs.pop("style", "") if mpf_style == "" or mpf_style.lower() == "random": mpf_styles = mpf.available_styles() mpfchart["style"] = mpf_styles[rnd.randrange(len(mpf_styles))] elif mpf_style.lower() in mpf.available_styles(): mpfchart["style"] = mpf_style mpfchart["figsize"] = kwargs.pop("figsize", (12, 10)) mpfchart["non_trading"] = kwargs.pop("nontrading", False) mpfchart["rc"] = kwargs.pop("rc", {'figure.facecolor': '#EDEDED'}) mpfchart["plot_ratios"] = kwargs.pop("plot_ratios", (12, 1.7)) mpfchart["scale_padding"] = kwargs.pop("scale_padding", {'left': 1, 'top': 4, 'right': 1, 'bottom': 1}) mpfchart["tight_layout"] = kwargs.pop("tight_layout", True) mpfchart["type"] = kwargs.pop("type", "candle") mpfchart["width_config"] = kwargs.pop("width_config", default_mpf_width) mpfchart["xrotation"] = kwargs.pop("xrotation", 15) self.mpfchart = mpfchart def _attribution(self): print(f"\nPandas v: {pd.__version__} [pip install pandas] https://github.com/pandas-dev/pandas") print(f"Data from AlphaVantage v: 1.0.19 [pip install alphaVantage-api] http://www.alphavantage.co https://github.com/twopirllc/AlphaVantageAPI") print(f"Technical Analysis with Pandas TA v: {ta.version} [pip install pandas_ta] https://github.com/twopirllc/pandas-ta") print(f"Charts by Matplotlib Finance v: {mpf.__version__} [pip install mplfinance] https://github.com/matplotlib/mplfinance\n") def _right_pad_df(self, rpad: int, delta_unit: str = "D", range_freq: str = "B"): if rpad > 0: dfpad = self.df[-rpad:].copy() dfpad.iloc[:,:] = np.NaN df_frequency = self.df.index.value_counts().mode()[0] # Most common frequency freq_delta = pd.Timedelta(df_frequency, unit=delta_unit) new_dr = pd.date_range(start=self.df.index[-1] + freq_delta, periods=rpad, freq=range_freq) dfpad.index = new_dr # Update the padded index with new dates self.df = self.df.append(dfpad) def _plot(self, **kwargs): if not isinstance(self.mpfchart["plot_ratios"], tuple): print(f"[X] plot_ratios must be a tuple") return # Override Chart Title Option chart_title = self.config["title"] if "title" in kwargs and isinstance(kwargs["title"], str): chart_title = kwargs.pop("title") # Override Right Bar Padding Option rpad = self.config["rpad"] if "rpad" in kwargs and kwargs["rpad"] > 0: rpad = int(kwargs["rpad"]) def cpanel(): return len(self.mpfchart["plot_ratios"]) # Last Second Default TA Indicators linreg = kwargs.pop("linreg", False) linreg_name = self.df.ta.linreg(append=True).name if linreg else "" midpoint = kwargs.pop("midpoint", False) # Add all indicators from the strategy addplot = [] if hasattr(self.strategy, "ta"): for indicator in self.strategy.ta: if isinstance(indicator, dict): params = indicator.get("params", {}) kwargs_ = {**params, **kwargs} df_ta = self.df.ta(kind=indicator["kind"], **kwargs_) if isinstance(df_ta, pd.DataFrame): for col in df_ta.columns: addplot.append(mpf.make_addplot(df_ta[col], panel=cpanel(), color='blue', secondary_y=False)) else: addplot.append(mpf.make_addplot(df_ta, panel=cpanel(), color='blue', secondary_y=False)) else: df_ta = self.df.ta(kind=indicator, verbose=self.verbose) if isinstance(df_ta, pd.DataFrame): for col in df_ta.columns: addplot.append(mpf.make_addplot(df_ta[col], panel=cpanel(), color='blue', secondary_y=False)) else: addplot.append(mpf.make_addplot(df_ta, panel=cpanel(), color='blue', secondary_y=False)) # Add custom indicators if any if linreg_name and linreg_name in self.df.columns: addplot.append(mpf.make_addplot(self.df[linreg_name], panel=cpanel(), color='orange', secondary_y=False)) if midpoint: self.df['midpoint'] = (self.df['open'] + self.df['high'] + self.df['low'] + self.df['close']) / 4 addplot.append(mpf.make_addplot(self.df['midpoint'], panel=cpanel(), color='purple', secondary_y=False)) # Plotting mpf.plot( self.df, title=chart_title, addplot=addplot, volume=self.config['volume'], style=self.mpfchart['style'], figsize=self.mpfchart['figsize'], type=self.mpfchart['type'], width_config=self.mpfchart['width_config'], xrotation=self.mpfchart['xrotation'], scale_padding=self.mpfchart['scale_padding'], tight_layout=self.mpfchart['tight_layout'], plot_ratios=self.mpfchart['plot_ratios'], non_trading=self.mpfchart['non_trading'], rc=self.mpfchart['rc'] ) self._attribution() ``` -------------------------------- ### Add and Remove DataFrame Constants Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/example.ipynb Demonstrates how to add custom constant columns to a DataFrame for charting purposes using `df.ta.constants`. It also shows how to remove specific constants. ```python # help(df.ta.constants) # for more info chart_lines = np.append(np.arange(-5, 6, 1), np.arange(-100, 110, 10)) df.ta.constants(True, chart_lines) # Adding the constants for the charts df.ta.constants(False, np.array([-60, -40, 40, 60])) # Removing some constants from the DataFrame print(f"Columns: {', '.join(list(df.columns))}") ``` -------------------------------- ### Load Daily Ticker Data with yfinance Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/example.ipynb Loads daily ticker data using the yfinance library and processes it to extract company and market information, including price history. ```python # help(e.ta.ticker) # Recent Data ticker = "BTC-USD" ticker = "SPY" df = e.ta.ticker(ticker, kind="info", lc_cols=True) recent_startdate = df.tail(recent_bars(df)).index[0] recent_enddate = df.tail(recent_bars(df)).index[-1] print(f"{df.name}{df.tail(recent_bars(df)).shape} from {recent_startdate} to {recent_enddate}") df.tail(recent_bars(df)).head() ``` -------------------------------- ### Apply Constants to DataFrame with Pandas-TA Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/PandasTA_Strategy_Examples.ipynb This snippet demonstrates how to apply predefined constants to a DataFrame using the `ta.constants()` method from the Pandas-TA library. It's useful for adding fixed values or thresholds to your indicator data. The `spy.tail()` call shows the resulting DataFrame with the added constants. ```python spy.ta.constants(True, [0, 30, 70]) spy.tail() ``` -------------------------------- ### Load Custom Strategy and Handle Runtime Errors (Python) Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/PandasTA_Strategy_Examples.ipynb This snippet demonstrates how to load a custom strategy named 'custom_run_failure' and then attempts to load the 'IWM' dataset. It includes error handling for 'AttributeError', which might occur if the strategy or its indicators are not properly defined or loaded. ```python watch.strategy = custom_run_failure try: iwm = watch.load("IWM") except AttributeError as error: print(f"[X] Oops! {error}") ``` -------------------------------- ### Plot Asset Chart with EMAs (Python) Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/AIExample.ipynb Plots a financial asset's closing price along with Exponential Moving Averages (EMAs) for specified periods. This helps visualize short-term and long-term trends. Requires 'asset' DataFrame with 'close' prices and pandas_ta indicators. ```python chart = asset[["close", "EMA_8", "EMA_21", "EMA_50"]] chart.plot(figsize=(16, 10), color=colors("BkGrOrRd"), title=ptitle, grid=True) ``` -------------------------------- ### Load Data with Freqtrade Watchlist Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/PandasTA_Strategy_Examples.ipynb Loads historical data for a given ticker symbol using Freqtrade's watchlist functionality. This is a prerequisite for applying any technical analysis. ```python spy = watch.load("SPY") spy ``` -------------------------------- ### Create MACD and Bollinger Bands Strategy (Python) Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/PandasTA_Strategy_Examples.ipynb This code defines a technical analysis strategy where Bollinger Bands are applied to the MACD signal line. It specifies the MACD indicator and then configures BBANDS to use the 'MACD_12_26_9' output as its input, with a 'MACD' prefix for clarity. The strategy is named 'MACD BBands'. ```python # MACD is the initial indicator that BBANDS depends on. # Set BBANDS's 'close' to MACD's main signal, in this case 'MACD_12_26_9' and add a prefix (or suffix) so it's easier to identify macd_bands_ta = [ {"kind":"macd"}, {"kind":"bbands", "close": "MACD_12_26_9", "length": 20, "ddof": 0, "prefix": "MACD"} ] macd_bands_ta = ta.Strategy("MACD BBands", macd_bands_ta, f"BBANDS_{macd_bands_ta[1]['length']} applied to MACD") ``` -------------------------------- ### Display Ticker and DataFrame Shapes Source: https://github.com/freqtrade/pandas-ta/blob/main/examples/PandasTA_Strategy_Examples.ipynb Prints a string representation of the tickers and their corresponding DataFrame shapes currently loaded in the Freqtrade watchlist. This is useful for quickly verifying the data that has been loaded and its dimensions. ```python ", ".join([f"{t}: {d.shape}" for t,d in watch.data.items()]) ```