### Basic Portfolio Backtest Source: https://vectorbt.dev/?q= This example demonstrates a basic backtest using VectorBT. It downloads BTC-USD data, calculates the closing price, initializes a portfolio with a starting cash amount, and prints the total profit. ```python >>> import vectorbt as vbt >>> data = vbt.YFData.download("BTC-USD") >>> price = data.get("Close") >>> pf = vbt.Portfolio.from_holding(price, init_cash=100) >>> print(pf.total_profit()) 17089.25554191831 ``` -------------------------------- ### Portfolio Creation with Basic Signals (Incomplete Example) Source: https://vectorbt.dev/api/portfolio/base?q= This example demonstrates creating a portfolio with basic entry and exit signals, but the code is incomplete. ```python >>> pf = vbt.Portfolio.from_signals( ... close, ... entries=pd.Series([True, True, True, False, False]), ... exits=pd.Series([False, False, True, True, True]), ``` -------------------------------- ### Install VectorBT from Repository Source: https://vectorbt.dev/getting-started/contributing?q= Install VectorBT in editable mode after cloning the repository. This is the first step for setting up the development environment. ```bash pip uninstall vectorbt git clone https://github.com/polakowo/vectorbt.git cd vectorbt pip install -e . ``` -------------------------------- ### Prepare DataFrame and Series for Examples Source: https://vectorbt.dev/api/generic/accessors?q= Sets up a sample pandas DataFrame and Series with datetime indices for use in subsequent examples. Requires importing pandas, numpy, numba, and datetime. ```python import vectorbt as vbt import numpy as np import pandas as pd from numba import njit from datetime import datetime, timedelta df = pd.DataFrame({ 'a': [1, 2, 3, 4, 5], 'b': [5, 4, 3, 2, 1], 'c': [1, 2, 3, 2, 1] }, index=pd.Index([ datetime(2020, 1, 1), datetime(2020, 1, 2), datetime(2020, 1, 3), datetime(2020, 1, 4), datetime(2020, 1, 5) ])) df index = [datetime(2020, 1, 1) + timedelta(days=i) for i in range(10)] sr = pd.Series(np.arange(len(index)), index=index) sr ``` -------------------------------- ### Install VectorBT with all integrations and Rust engine Source: https://vectorbt.dev/getting-started/installation Install VectorBT with both all optional integrations and the Rust engine. This is the most complete installation option. ```bash pip install -U "vectorbt[full,rust]" ``` -------------------------------- ### Install VectorBT with pip Source: https://vectorbt.dev/getting-started/installation Use this command to install the base VectorBT package. Ensure pip is up-to-date. ```bash pip install -U vectorbt ``` -------------------------------- ### Install VectorBT with all optional integrations Source: https://vectorbt.dev/getting-started/installation Install VectorBT with all optional integrations, such as TA-Lib and Pandas TA. This provides the most comprehensive feature set. ```bash pip install -U "vectorbt[full]" ``` -------------------------------- ### Example Usage of MSTD Plot Source: https://vectorbt.dev/api/indicators/basic Example demonstrating how to run and plot the MSTD indicator with a specified window. ```python >>> vbt.MSTD.run(ohlcv['Close'], 10).plot() ``` -------------------------------- ### ScheduleManager.start Method Source: https://vectorbt.dev/api/utils/schedule_ Starts running pending jobs in a loop. ```APIDOC ## ScheduleManager.start Method ### Description Run pending jobs in a loop. ### Parameters - **sleep** (int) - The time in seconds to sleep between checking for pending jobs. Defaults to 1. ### Method `start(sleep=1)` ``` -------------------------------- ### Install VectorBT from local clone Source: https://vectorbt.dev/getting-started/installation Installs the VectorBT package in editable mode after cloning the repository. This allows for direct code modifications. ```bash pip install -e vectorbt ``` -------------------------------- ### ScheduleManager.async_start Method Source: https://vectorbt.dev/api/utils/schedule_ Starts running pending jobs asynchronously in a loop. ```APIDOC ## ScheduleManager.async_start Method ### Description Async run pending jobs in a loop. ### Parameters - **sleep** (int) - The time in seconds to sleep between checking for pending jobs. Defaults to 1. ### Method `async_start(sleep=1)` ``` -------------------------------- ### partition_ranges method usage example Source: https://vectorbt.dev/api/signals/accessors Wraps the result of `partition_ranges_nb()` with Ranges. It identifies the start and end timestamps of signal partitions. ```python >>> mask_sr = pd.Series([True, True, True, False, True, True]) >>> mask_sr.vbt.signals.partition_ranges().records_readable Range Id Column Start Timestamp End Timestamp Status 0 0 0 0 3 Closed 1 1 0 4 5 Open ``` -------------------------------- ### Initialize Portfolio with Logging Source: https://vectorbt.dev/api/portfolio/logs?q= Demonstrates how to initialize a VectorBT Portfolio from price and size data, enabling logging with fees and a specified frequency. ```python import pandas as pd import numpy as np from datetime import datetime, timedelta import vectorbt as vbt np.random.seed(42) price = pd.DataFrame({ 'a': np.random.uniform(1, 2, size=100), 'b': np.random.uniform(1, 2, size=100) }, index=[datetime(2020, 1, 1) + timedelta(days=i) for i in range(100)]) size = pd.DataFrame({ 'a': np.random.uniform(-100, 100, size=100), 'b': np.random.uniform(-100, 100, size=100), }, index=[datetime(2020, 1, 1) + timedelta(days=i) for i in range(100)]) pf = vbt.Portfolio.from_orders(price, size, fees=0.01, freq='d', log=True) logs = pf.logs ``` -------------------------------- ### Generate stats for ranges of a specific column Source: https://vectorbt.dev/api/generic/ranges Use the `.stats()` method on a specific column's ranges to get detailed statistics. This includes information on start, end, period, total records, coverage, overlap, and duration metrics. Ensure the DataFrame has a frequency set using `.vbt(freq='d')`. ```python df = pd.DataFrame({ 'a': [1, 2, np.nan, np.nan, 5, 6], 'b': [np.nan, 2, np.nan, 4, np.nan, 6] }) ranges = df.vbt(freq='d').ranges print(ranges['a'].stats()) ``` -------------------------------- ### Serve Documentation Locally Source: https://vectorbt.dev/getting-started/contributing?q= Build and serve the documentation locally using mkdocs. This allows you to preview changes before deploying them. ```bash cd docs mkdocs serve ``` -------------------------------- ### QSAdapter Usage Example Source: https://vectorbt.dev/api/returns/qs_adapter?q= Demonstrates how to access quantstats metrics through vectorbt's ReturnsAccessor, showing default parameter handling and direct overrides. ```APIDOC ## QSAdapter Usage Example ### Description This example illustrates how to use the `QSAdapter` to access `quantstats` metrics via `vectorbt`'s `ReturnsAccessor`. It shows how defaults can be set and overridden. ### Method N/A (Illustrative Example) ### Endpoint N/A (Illustrative Example) ### Parameters N/A ### Request Example ```python import numpy as np import pandas as pd import vectorbt as vbt import quantstats as qs np.random.seed(42) rets = pd.Series(np.random.uniform(-0.1, 0.1, size=(100,))) benchmark_rets = pd.Series(np.random.uniform(-0.1, 0.1, size=(100,))) # Using ReturnsAccessor with quantstats adapter ret_acc = rets.vbt.returns( benchmark_rets=benchmark_rets, freq='d', year_freq='365d', defaults=dict(risk_free=0.001) ) # Accessing a quantstats metric print(ret_acc.qs.r_squared()) print(ret_acc.qs.sharpe()) # Overriding defaults directly in the adapter ret_acc_qs = rets.vbt.returns.qs(defaults=dict(benchmark=benchmark_rets, periods=365, periods_per_year=365, rf=0.001)) print(ret_acc_qs.r_squared()) print(ret_acc_qs.sharpe()) # Overriding arguments directly in the function call print(rets.vbt.returns.qs(defaults=dict(periods=252)).sharpe()) print(rets.vbt.returns.qs.sharpe(periods=252)) ``` ### Response #### Success Response (200) N/A (Illustrative Example) #### Response Example ``` 0.0011582111228735541 -1.9158923252075455 0.0011582111228735541 -1.9158923252075455 -1.5912029345745982 -1.5912029345745982 ``` ``` -------------------------------- ### Custom Method Decorator Usage Example Source: https://vectorbt.dev/api/utils/decorators?q= Example of using the custom_method decorator, both directly and with arguments to specify flags. ```python >>> @cached_method def user_function(): pass >>> @cached_method(maxsize=128, typed=False, a=0, b=0) # flags def user_function(): pass ``` -------------------------------- ### Create Portfolio from Returns Source: https://vectorbt.dev/api/returns/qs_adapter?q= Creates a simulated portfolio from a series of returns. Allows setting the starting balance and rounding options. ```python QSAdapter.make_portfolio( *, start_balance=100000.0, mode='comp', round_to=None ) ``` -------------------------------- ### Creating Portfolio with Open Position Source: https://vectorbt.dev/api/portfolio/trades Sets up portfolio arguments to demonstrate an open position scenario. Includes closing price, size, and fixed fees. ```python >>> pf_kwargs = dict( ... close=pd.Series([1., 2., 3., 4., 5.]), ... size=pd.Series([1., 0., 0., 0., 0.]), ... fixed_fees=1. ... ) ``` -------------------------------- ### Plot Ranges Example Source: https://vectorbt.dev/api/generic/ranges Example usage of the plot method for Ranges. Requires importing vectorbt, datetime, timedelta, and pandas. ```python import vectorbt as vbt from datetime import datetime, timedelta import pandas as pd price = pd.Series([1, 2, 1, 2, 3, 2, 1, 2], name='Price') price.index = [datetime(2020, 1, 1) + timedelta(days=i) for i in range(len(price))] vbt.Ranges.from_ts(price >= 2, wrapper_kwargs=dict(freq='1 day')).plot() ``` -------------------------------- ### Configuring QSAdapter Defaults and Overrides Source: https://vectorbt.dev/api/returns/qs_adapter Shows how to configure global settings or pass specific overrides to quantstats functions when using the adapter. ```python vbt.settings.array_wrapper['freq'] = 'h' vbt.settings.returns['year_freq'] = '365d' # Using adapter with custom overrides print(rets.vbt.returns.qs(defaults=dict(periods=252)).sharpe()) # Direct argument override print(rets.vbt.returns.qs.sharpe(periods=252)) ``` -------------------------------- ### Portfolio Initialization with Order Function and Templates Source: https://vectorbt.dev/api/portfolio/base?q= Initializes a portfolio using a custom order function, demonstrating the use of templates for dynamic argument preparation and broadcasting for flexible parameter management. Use when defining complex order logic that depends on broadcasted arguments. ```python size_template = vbt.RepEval('np.asarray(1 / group_lens[0])') pf = vbt.Portfolio.from_order_func( close, order_func_nb, size_template, # order_args as *args vbt.Rep('price'), vbt.Rep('size_type'), vbt.Rep('direction'), vbt.Rep('fees'), vbt.Rep('fixed_fees'), vbt.Rep('slippage'), segment_mask=2, # rebalance every second tick pre_group_func_nb=pre_group_func_nb, pre_segment_func_nb=pre_segment_func_nb, pre_segment_args=( size_template, vbt.Rep('price'), vbt.Rep('size_type'), vbt.Rep('direction') ), broadcast_named_args=dict( # broadcast against each other price=close, size_type=SizeType.TargetPercent, direction=Direction.LongOnly, fees=0.001, fixed_fees=1., slippage=0.001 ), template_mapping=dict(np=np), # required by size_template cash_sharing=True, group_by=True, # one group with cash sharing ) ``` -------------------------------- ### Install VectorBT with Rust engine Source: https://vectorbt.dev/getting-started/installation Install VectorBT with the optional Rust engine for performance improvements. This command includes the necessary dependencies. ```bash pip install -U "vectorbt[rust]" ``` -------------------------------- ### Volume Class Initialization Source: https://vectorbt.dev/api/generic/plotting Demonstrates the initialization of the Volume class with various parameters. ```APIDOC ## Volume Class Initialization ### Description Initializes a Volume object for creating 3D volume plots. Accepts data, axis labels, and plotting configuration arguments. ### Method __init__ ### Parameters #### Args - **data** (array_like) - Required - Data in any format that can be converted to NumPy. Must be a 3-dim array. - **x_labels** (array_like) - Optional - X-axis labels. - **y_labels** (array_like) - Optional - Y-axis labels. - **z_labels** (array_like) - Optional - Z-axis labels. - **trace_kwargs** (dict) - Optional - Keyword arguments passed to `plotly.graph_objects.Volume`. - **add_trace_kwargs** (dict) - Optional - Keyword arguments passed to `add_trace`. - **scene_name** (str) - Optional - Reference to the 3D scene. Defaults to 'scene'. - **fig** (Figure or FigureWidget) - Optional - Figure to add traces to. - **layout_kwargs** - Optional - Keyword arguments for layout. ### Request Example ```python import vectorbt as vbt import numpy as np volume = vbt.plotting.Volume( data=np.random.randint(1, 10, size=(3, 3, 3)), x_labels=['a', 'b', 'c'], y_labels=['d', 'e', 'f'], z_labels=['g', 'h', 'i'] ) ``` ### Response #### Success Response (200) Returns the initialized Volume object. #### Response Example ```python # The volume object itself is returned upon successful initialization. # Accessing the figure attribute: print(volume.fig) ``` ``` -------------------------------- ### Initialize Portfolio Class Source: https://vectorbt.dev/api/portfolio/base Use this constructor to initialize a Portfolio object. It requires essential parameters like wrapper, close prices, order and log records, initial cash, and cash sharing settings. Other parameters allow for fine-tuning simulation behavior. ```python Portfolio( wrapper, close, order_records, log_records, init_cash, cash_sharing, call_seq=None, fillna_close=None, trades_type=None, engine=None ) ``` -------------------------------- ### SignalsAccessor.norm_avg_index Usage Examples Source: https://vectorbt.dev/api/signals/accessors Examples demonstrating the usage of SignalsAccessor.norm_avg_index. Returns -1.0 for the first signal, 1.0 for the last, and 0.0 for a symmetric distribution. ```python pd.Series([True, False, False, False]).vbt.signals.norm_avg_index() ``` ```python pd.Series([False, False, False, True]).vbt.signals.norm_avg_index() ``` ```python pd.Series([True, False, False, True]).vbt.signals.norm_avg_index() ``` -------------------------------- ### Portfolio Initialization with Costs Source: https://vectorbt.dev/api/portfolio/base?q= Initializes a portfolio with specified trading costs and parameters. Used for setting up simulation environments. ```python Portfolio.from_signals( close, n=10, seed=1, call_seq='auto', # first sell then buy group_by=True, # one group cash_sharing=True, # assets share the same cash fees=0.001, fixed_fees=1., slippage=0.001 # costs ) ``` -------------------------------- ### Buy 10 units each tick Source: https://vectorbt.dev/api/portfolio/base?q= This example demonstrates how to buy a fixed number of units (10) for each asset on every tick. It initializes a portfolio with a given closing price series and a fixed order size. ```python >>> close = pd.Series([1, 2, 3, 4, 5]) >>> pf = vbt.Portfolio.from_orders(close, 10) >>> pf.assets() 0 10.0 1 20.0 2 30.0 3 40.0 4 40.0 dtype: float64 >>> pf.cash() 0 90.0 1 70.0 2 40.0 3 0.0 4 0.0 dtype: float64 ``` -------------------------------- ### Example Usage of Cached Method Source: https://vectorbt.dev/api/utils/decorators Example of using the cached_method decorator on a user-defined function. Caching can be configured with arguments like maxsize and typed. ```python @cached_method def user_function(): pass ``` ```python @cached_method(maxsize=128, typed=False, a=0, b=0) # flags def user_function(): pass ``` -------------------------------- ### ScheduleManager start Method Source: https://vectorbt.dev/api/utils/schedule_ Starts the execution of pending jobs in a loop. It takes an optional sleep interval to control the loop's frequency. ```python ScheduleManager.start( sleep=1 ) Run pending jobs in a loop. ``` -------------------------------- ### Create Portfolio from Orders and Plot Trades Source: https://vectorbt.dev/api/portfolio/trades Demonstrates creating a portfolio from price data and orders, then plotting the trades. Requires pandas and datetime. ```python import pandas as pd from datetime import datetime, timedelta import vectorbt as vbt price = pd.Series([1., 2., 3., 4., 3., 2., 1.], name='Price') price.index = [datetime(2020, 1, 1) + timedelta(days=i) for i in range(len(price))] orders = pd.Series([1., -0.5, -0.5, 2., -0.5, -0.5, -0.5]) pf = vbt.Portfolio.from_orders(price, orders) pf.trades.plot() ``` -------------------------------- ### Portfolio Initialization with Different Grouping Source: https://vectorbt.dev/api/portfolio/base Demonstrates how to reconfigure portfolio grouping and input data to create different allocation scenarios. Change `group_by` and `close` to alter the number of groups and their composition. ```python close = np.random.uniform(1, 10, size=(5, 6)) # 6 columns instead of 3 group_by = ['g1', 'g1', 'g1', 'g2', 'g2', 'g2'] # 2 groups instead of 1 ``` -------------------------------- ### OHLCV Accessor Plot Usage Example Source: https://vectorbt.dev/api/ohlcv_accessors Example of how to use the plot method to visualize OHLCV data. Requires importing vectorbt and downloading data. ```python import vectorbt as vbt >>> vbt.YFData.download("BTC-USD").get().vbt.ohlcv.plot() ``` -------------------------------- ### Simulate portfolio from orders with various parameters Source: https://vectorbt.dev/api/portfolio/base?q= Demonstrates the use of Portfolio.from_orders() to simulate trades. Supports flexible input formats for price, size, direction, and fees, leveraging broadcasting for efficiency. Use when orders are predefined and no custom logic is needed. ```python size = pd.Series([1, -1, 1, -1]) # per row price = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [4, 3, 2, 1]}) # per element direction = ['longonly', 'shortonly'] # per column fees = 0.01 # per frame pf = vbt.Portfolio.from_orders(price, size, direction=direction, fees=fees) print(pf.orders.records_readable) ``` -------------------------------- ### Manage TelegramBot lifecycle Source: https://vectorbt.dev/api/messaging/telegram Methods to start and stop the bot instance. The start method supports background execution and passes configuration to the underlying updater. ```python TelegramBot.start(in_background=False, **kwargs) TelegramBot.stop() ``` -------------------------------- ### Portfolio with Standard Entry/Exit Signals Source: https://vectorbt.dev/api/portfolio/base Example of a portfolio using standard entry and exit signals. Ensure the price used for signals occurs after the signal itself. ```python >>> pf = vbt.Portfolio.from_signals( ... close, ... entries=pd.Series([True, True, True, False, False]), ... exits=pd.Series([False, False, True, True, True]), ``` -------------------------------- ### Get Raw Outputs from Indicator Source: https://vectorbt.dev/api/indicators/factory?q= Use `return_raw=True` to get raw calculation artifacts. Pass the returned tuple to `use_raw` to reuse these artifacts in subsequent calculations. ```python >>> raw = vbt.MA.run(price, 2, [False, True], return_raw=True) >>> raw ([array([[ nan, nan, nan, nan], [1.5 , 4.5 , 1.66666667, 4.33333333], [2.5 , 3.5 , 2.55555556, 3.44444444], [3.5 , 2.5 , 3.51851852, 2.48148148], [4.5 , 1.5 , 4.50617284, 1.49382716]])], [(2, False), (2, True)], 2, []) ``` ```python >>> vbt.MA.run(price, 2, True, use_raw=raw).ma ma_window 2 ma_ewm True a b 2020-01-01 NaN NaN 2020-01-02 1.666667 4.333333 2020-01-03 2.555556 3.444444 2020-01-04 3.518519 2.481481 2020-01-05 4.506173 1.493827 ``` -------------------------------- ### Using QSAdapter for Quantstats Metrics with Vectorbt Source: https://vectorbt.dev/api/returns/qs_adapter?q= Demonstrates how to use the QSAdapter to access quantstats metrics through vectorbt's ReturnsAccessor. It shows how to define benchmark returns and other parameters once and reuse them across multiple quantstats functions. This approach avoids repetitive parameter passing and allows for automatic translation of parameters for quantstats. ```python import numpy as np import pandas as pd import vectorbt as vbt import quantstats as qs np.random.seed(42) rets = pd.Series(np.random.uniform(-0.1, 0.1, size=(100,))) benchmark_rets = pd.Series(np.random.uniform(-0.1, 0.1, size=(100,))) # Using QSAdapter via ReturnsAccessor ret_acc = rets.vbt.returns( benchmark_rets=benchmark_rets, freq='d', year_freq='365d', defaults=dict(risk_free=0.001) ) print(ret_acc.qs.r_squared()) print(ret_acc.qs.sharpe()) # Directly using QSAdapter with quantstats defaults qs_defaults = dict( benchmark=benchmark_rets, periods=365, periods_per_year=365, rf=0.001 ) ret_acc_qs = rets.vbt.returns.qs(defaults=qs_defaults) print(ret_acc_qs.r_squared()) print(ret_acc_qs.sharpe()) # Overriding arguments print(rets.vbt.returns.qs(defaults=dict(periods=252)).sharpe()) print(rets.vbt.returns.qs.sharpe(periods=252)) print(qs.stats.sharpe(rets)) ``` -------------------------------- ### Get Cash Flow - Portfolio Source: https://vectorbt.dev/api/portfolio/base?q= Retrieves the cash flow series per column/group. Use `free` to get the flow of free cash, which is capped at the initial level. ```python Portfolio.cash_flow( group_by=None, free=False, wrap_kwargs=None, engine=None ) ``` -------------------------------- ### QSAdapter Method: best Source: https://vectorbt.dev/api/returns/qs_adapter?q= Finds the best period returns using quantstats.stats.best. It supports aggregation and options for compounded returns and return preparation. ```python def best( self, *, aggregate=None, compounded=True, prepare_returns=True ): """See `quantstats.stats.best`.""" pass ``` -------------------------------- ### Get Aggregated Portfolio Statistics Source: https://vectorbt.dev/api/portfolio/base Call `pf.stats()` without arguments to get aggregated statistics across all columns. A UserWarning is issued if the object has multiple columns and `agg_func` is not specified. ```python >>> pf.stats() UserWarning: Object has multiple columns. Aggregating using . Pass column to select a single column/group. Start 2020-01-01 00:00:00+00:00 End 2020-09-01 00:00:00+00:00 Period 244 days 00:00:00 Start Value 100.0 End Value 138.746495 Total Return [%] 38.746495 Benchmark Return [%] 66.252621 Max Gross Exposure [%] 100.0 Total Fees Paid 0.0 Max Drawdown [%] 20.35869 Max Drawdown Duration 93 days 00:00:00 Total Trades 15.0 Total Closed Trades 15.0 Total Open Trades 0.0 Open Trade PnL 0.0 Win Rate [%] 65.0 Best Trade [%] 16.82609 Worst Trade [%] -9.701273 Avg Winning Trade [%] 5.445408 Avg Losing Trade [%] -4.740956 Avg Winning Trade Duration 8 days 19:25:42.857142857 Avg Losing Trade Duration 9 days 07:00:00 Profit Factor 2.186957 Expectancy 2.105364 Sharpe Ratio 1.165695 Calmar Ratio 3.541079 Omega Ratio 1.331624 Sortino Ratio 2.084565 Name: agg_func_mean, dtype: object ``` -------------------------------- ### Accessing quantstats via ReturnsAccessor Source: https://vectorbt.dev/api/returns/qs_adapter Demonstrates how to use the QSAdapter to calculate statistics like R-squared and Sharpe ratio directly from a ReturnsAccessor object, leveraging vectorbt's automatic parameter handling. ```python import numpy as np import pandas as pd import vectorbt as vbt import quantstats as qs np.random.seed(42) rets = pd.Series(np.random.uniform(-0.1, 0.1, size=(100,))) benchmark_rets = pd.Series(np.random.uniform(-0.1, 0.1, size=(100,))) # Direct access via ReturnsAccessor print(rets.vbt.returns.qs.r_squared(benchmark=benchmark_rets)) # Using defaults for cleaner calls ret_acc = rets.vbt.returns( benchmark_rets=benchmark_rets, freq='d', year_freq='365d', defaults=dict(risk_free=0.001) ) print(ret_acc.qs.r_squared()) print(ret_acc.qs.sharpe()) ``` -------------------------------- ### Get Projected Return of Buy Orders Source: https://vectorbt.dev/getting-started/features Calculate the projected return of each buy order from random signals. This requires downloading price data and using Portfolio.from_random_signals to get entry trades. ```python >>> price = vbt.YFData.download('BTC-USD').get('Close') >>> entry_trades = vbt.Portfolio.from_random_signals(price, n=5).entry_trades >>> returns_pd = entry_trades.returns.to_pd() >>> returns_pd[~returns_pd.isnull()] ``` -------------------------------- ### Reverse each position by first closing it Source: https://vectorbt.dev/api/portfolio/base?q= This example shows how to reverse each position by first closing the existing one and then opening a new one in the opposite direction. It uses 'targetpercent' to define the size of the orders as a percentage of the portfolio value. ```python >>> size = [1, 0, -1, 0, 1] >>> pf = vbt.Portfolio.from_orders(close, size, size_type='targetpercent') >>> pf.assets() 0 100.000000 1 0.000000 2 -66.666667 3 0.000000 4 26.666667 dtype: float64 >>> pf.cash() 0 0.000000 1 200.000000 2 400.000000 3 133.333333 4 0.000000 dtype: float64 ``` -------------------------------- ### get_multiindex_series Source: https://vectorbt.dev/api/base/reshape_fns?q= Gets a Series with a multi-index. ```APIDOC ## get_multiindex_series ### Description Get Series with a multi-index. If DataFrame has been passed, should at maximum have one row or column. ### Parameters * **arg** (array_like) - The input array or DataFrame. ``` -------------------------------- ### Get Indicator Run Method Help Source: https://vectorbt.dev/api/indicators/factory?q= Use the `help` function to get detailed information about the arguments accepted by an indicator's `run` method. This includes inputs, parameters, outputs, and options for hiding parameter columns. ```python >>> help(MyInd.run) Help on method run: run(price, window, short_name='custom', hide_params=None, hide_default=True, **kwargs) method of builtins.type instance Run `Indicator` indicator. * Inputs: `price` * Parameters: `window` * Outputs: `ma` Pass a list of parameter names as `hide_params` to hide their column levels. Set `hide_default` to False to show the column levels of the parameters with a default value. Other keyword arguments are passed to `vectorbt.indicators.factory.run_pipeline`. ``` -------------------------------- ### Visualize Performance with QuantStats Source: https://vectorbt.dev/getting-started/features Use QuantStats to visualize performance metrics. Requires downloading price data and converting it to returns. ```python >>> price = vbt.YFData.download('BTC-USD').get('Close') >>> returns = price.vbt.to_returns() >>> returns.vbt.returns.qs.plot_snapshot() ``` -------------------------------- ### benchmark_rets Property Source: https://vectorbt.dev/api/returns/accessors Gets the benchmark returns. ```APIDOC ## benchmark_rets Property ### Description Benchmark returns. ### Property Type Accessor ``` -------------------------------- ### RPROBX Class Constructor Source: https://vectorbt.dev/api/signals/generators?q= Initializes RPROBX with wrapper, input/output lists, parameter mappings, and naming conventions. See RPROB for parameter details. ```python RPROBX( wrapper, input_list, input_mapper, in_output_list, output_list, param_list, mapper_list, short_name, level_names ) ``` -------------------------------- ### SegmentContext.call_seq_now Example Source: https://vectorbt.dev/api/portfolio/enums?q= Illustrates the usage of the `call_seq_now` attribute within SegmentContext. This attribute determines the order in which columns within a group are processed. An example `[2, 0, 1]` shows processing column 2 first, then 0, and finally 1. ```python # Example: [2, 0, 1] would first call column 2, then 0, and finally 1. ``` -------------------------------- ### QSAdapter Method: basic_report Source: https://vectorbt.dev/api/returns/qs_adapter?q= Generates a basic performance report using quantstats.reports.basic. This method allows customization of benchmark, risk-free rate, colors, figure size, and compounding, among other options. ```python def basic_report( self, *, benchmark=None, rf=0.0, grayscale=False, figsize=(8, 5), display=True, compounded=True, periods_per_year=252, match_dates=True, **kwargs ): """See `quantstats.reports.basic`.""" pass ``` -------------------------------- ### Define Initial Cash Configuration Source: https://vectorbt.dev/api/portfolio/enums Examples of setting initial cash based on group structures and cash sharing settings. ```python # With cash sharing: one group of two columns ($200) and one column ($100) init_cash_shared = np.array([200, 100]) # Without cash sharing: three columns with $100 each init_cash_no_share = np.array([100, 100, 100]) ``` -------------------------------- ### get_ranges_arr Source: https://vectorbt.dev/api/utils/array_ Builds an array from start and end indices. ```APIDOC ## get_ranges_arr ### Description Builds an array from start and end indices based on stackoverflow.com/a/37626057. ### Parameters #### Arguments - **starts** (array) - Required - Start indices - **ends** (array) - Required - End indices ### Response - **result** (array) - The constructed range array ``` -------------------------------- ### BinanceData.download class method Source: https://vectorbt.dev/api/data/custom?q= Overrides Data.download() to instantiate a Binance client. ```APIDOC ## BinanceData.download class method ### Description Overrides Data.download() to instantiate a Binance client. ### Method CLASS METHOD ### Endpoint N/A (Class Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response None ``` -------------------------------- ### Portfolio.final_value Source: https://vectorbt.dev/api/portfolio/base?q= Get total profit per column/group. ```APIDOC ## Portfolio.final_value ### Description Get total profit per column/group. ### Method Portfolio.final_value ### Parameters #### Path Parameters None #### Query Parameters - **group_by** (Optional) - Description for group_by - **wrap_kwargs** (Optional) - Description for wrap_kwargs - **engine** (Optional) - Description for engine ### Request Example ```json { "group_by": null, "wrap_kwargs": null, "engine": null } ``` ### Response #### Success Response (200) - **final_profit** (float) - The total profit per column/group. #### Response Example ```json { "final_profit": 100.5 } ``` ``` -------------------------------- ### ann_factor Property Source: https://vectorbt.dev/api/returns/accessors Gets the annualization factor for the returns. ```APIDOC ## ann_factor Property ### Description Get annualization factor. ### Property Type Accessor ``` -------------------------------- ### Simulate, Save, and Load Portfolio Source: https://vectorbt.dev/getting-started/features Simulates a portfolio, saves it to a file using .save(), and then loads it back using .load(). Requires the 'vectorbt' library. The file will be saved as 'my_pf.pkl'. ```python import vectorbt as vbt price = vbt.YFData.download('BTC-USD').get('Close') pf = vbt.Portfolio.from_random_signals(price, n=5) pf.save('my_pf.pkl') pf = vbt.Portfolio.load('my_pf.pkl') pf.total_return() ``` -------------------------------- ### ATR Statistics Source: https://vectorbt.dev/api/indicators/basic Method to get statistics for ATR. ```APIDOC ## ATR.atr_stats ### Description Stats of `atr` as generic. ### Method N/A (Method of a class) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) Statistical data for ATR. #### Response Example None ``` -------------------------------- ### is_rust_available function Source: https://vectorbt.dev/api/_engine?q= Checks if the `vectorbt-rust` package is installed and version-compatible. ```APIDOC ## is_rust_available function ### Description Return whether `vectorbt-rust` is installed and version-compatible. ### Method N/A (Function definition) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (200) Boolean indicating Rust availability and compatibility. #### Response Example None ``` -------------------------------- ### Create Portfolio from Signals Source: https://vectorbt.dev/api/portfolio/base?q= Use `Portfolio.from_signals` to automate trading based on entry and exit signals. It handles position management and stop-loss/take-profit orders by default. Requires price data, entry/exit signals, and optional parameters like size, direction, and fees. ```python >>> entries = pd.Series([True, False, True, False]) >>> exits = pd.Series([False, True, False, True]) >>> pf = vbt.Portfolio.from_signals(price, entries, exits, size=1, direction=direction, fees=fees) >>> pf.orders.records_readable Order Id Column Timestamp Size Price Fees Side 0 0 a 0 1.0 1.0 0.01 Buy 1 1 a 1 1.0 2.0 0.02 Sell 2 2 a 2 1.0 3.0 0.03 Buy 3 3 a 3 1.0 4.0 0.04 Sell 4 4 b 0 1.0 4.0 0.04 Sell 5 5 b 1 1.0 3.0 0.03 Buy 6 6 b 2 1.0 2.0 0.02 Sell 7 7 b 3 1.0 1.0 0.01 Buy ``` -------------------------------- ### OHLCSTX Usage Example Source: https://vectorbt.dev/api/signals/generators?q= Demonstrates how to use the OHLCSTX class to generate entries and exits based on price data and various stop loss/take profit configurations. Shows how to access properties like entries, exits, stop_price, and stop_type_readable. ```python import vectorbt as vbt import pandas as pd import numpy as np entries = pd.Series([True, False, False, False, False, False]) price = pd.DataFrame({ 'open': [10, 11, 12, 11, 10, 9], 'high': [11, 12, 13, 12, 11, 10], 'low': [9, 10, 11, 10, 9, 8], 'close': [10, 11, 12, 11, 10, 9] }) ohlcstx = vbt.OHLCSTX.run( entries, price['open'], price['high'], price['low'], price['close'], sl_stop=[0.1, 0.1, np.nan], sl_trail=[False, True, False], tp_stop=[np.nan, np.nan, 0.1]) print(ohlcstx.entries) print(ohlcstx.exits) print(ohlcstx.stop_price) print(ohlcstx.stop_type_readable) ``` -------------------------------- ### Build Field Configuration Documentation Source: https://vectorbt.dev/api/records/base A class method to construct documentation for the field configuration. ```python Records.build_field_config_doc( source_cls=None ) ``` -------------------------------- ### get_ranges_arr Source: https://vectorbt.dev/api/utils/array_?q= Builds an array of indices from start and end points. ```APIDOC ## GET /array/ranges ### Description Generates an array of indices based on provided start and end points. ### Method GET ### Endpoint /array/ranges ### Parameters #### Query Parameters - **starts** (array) - Required - Array of starting indices - **ends** (array) - Required - Array of ending indices ### Request Example { "starts": [0, 5], "ends": [2, 7] } ### Response #### Success Response (200) - **result** (array) - The constructed range array #### Response Example { "result": [0, 1, 5, 6] } ``` -------------------------------- ### Create Portfolio from Returns Source: https://vectorbt.dev/api/returns/qs_adapter Generates a portfolio value series based on initial balance and calculation mode. Useful for converting return streams into equity curves. ```python QSAdapter.make_portfolio(start_balance=100000.0, mode='comp', round_to=None) ``` -------------------------------- ### SignalsAccessor.pos_rank_mapped Source: https://vectorbt.dev/api/signals/accessors Gets a mapped array of signal position ranks. ```APIDOC ## SignalsAccessor.pos_rank_mapped ### Description Gets a mapped array of signal position ranks. See SignalsAccessor.pos_rank(). ### Method N/A (Method of SignalsAccessor) ### Parameters #### Path Parameters None #### Query Parameters - **group_by** (bool or array-like) - Optional - Whether to group the results. - **kwargs** - Additional keyword arguments. ### Request Example ```python SignalsAccessor.pos_rank_mapped( group_by=None, **kwargs ) ``` ### Response Returns a mapped array of signal position ranks. ``` -------------------------------- ### SignalsAccessor.partition_pos_rank_mapped Source: https://vectorbt.dev/api/signals/accessors Gets a mapped array of partition position ranks. ```APIDOC ## SignalsAccessor.partition_pos_rank_mapped ### Description Gets a mapped array of partition position ranks. See SignalsAccessor.partition_pos_rank(). ### Method N/A (Method of SignalsAccessor) ### Parameters #### Path Parameters None #### Query Parameters - **group_by** (bool or array-like) - Optional - Whether to group the results. - **kwargs** - Additional keyword arguments. ### Request Example ```python SignalsAccessor.partition_pos_rank_mapped( group_by=None, **kwargs ) ``` ### Response Returns a mapped array of partition position ranks. ``` -------------------------------- ### Example Usage of Data.plot Source: https://vectorbt.dev/api/data/base?q= Demonstrates downloading historical stock data for multiple cryptocurrencies and plotting the 'Close' price with a base of 1. ```python >>> import vectorbt as vbt >>> start = '2021-01-01 UTC' # crypto is in UTC >>> end = '2021-06-01 UTC' >>> data = vbt.YFData.download(['BTC-USD', 'ETH-USD', 'ADA-USD'], start=start, end=end) >>> data.plot(column='Close', base=1) ``` -------------------------------- ### Get Labels Stats Source: https://vectorbt.dev/api/labels/generators?q= Retrieves statistics for `labels` as generic. ```python BOLB.labels_stats( *args, **kwargs ) ``` -------------------------------- ### Simulate Portfolio from Holding - Portfolio Source: https://vectorbt.dev/api/portfolio/base?q= Simulates a portfolio from holding data. Based on Portfolio.from_signals(). Requires a pandas Series for closing prices. ```python Portfolio.from_holding( close, **kwargs ) ``` ```python close = pd.Series([1, 2, 3, 4, 5]) pf = vbt.Portfolio.from_holding(close) pf.final_value() ``` -------------------------------- ### GET /reports/full Source: https://vectorbt.dev/api/returns/qs_adapter Generates a full performance report for the strategy. ```APIDOC ## GET /reports/full ### Description Generates a comprehensive performance tearsheet report. ### Method GET ### Endpoint /reports/full ### Parameters #### Query Parameters - **benchmark** (string) - Optional - Benchmark symbol for comparison. - **rf** (float) - Optional - Risk-free rate. Default: 0.0 - **grayscale** (boolean) - Optional - Whether to use grayscale plots. Default: False - **periods_per_year** (integer) - Optional - Number of trading periods per year. Default: 252 ### Response #### Success Response (200) - **report** (binary) - The generated report content. ``` -------------------------------- ### Backtest Strategy with Portfolio Source: https://vectorbt.dev/ Creates a portfolio from price data and generated entry/exit signals to backtest the strategy. The `freq` parameter is important for accurate performance metrics when dealing with non-standard time series. ```python pf = vbt.Portfolio.from_signals(comb_price, entries, exits) ``` -------------------------------- ### RPROBX Class Constructor Source: https://vectorbt.dev/api/signals/generators Initializes the RPROBX class with wrapper, input/output lists, parameter lists, and naming conventions. See RPROB for parameter details. ```python RPROBX( wrapper, input_list, input_mapper, in_output_list, output_list, param_list, mapper_list, short_name, level_names ) ``` -------------------------------- ### get_return function Source: https://vectorbt.dev/api/returns/dispatch?q= Gets the return, an engine-neutral wrapper for get_return_nb(). ```APIDOC ## get_return function ### Description Engine-neutral get_return_nb(). ### Parameters - **input_value** (type) - Description - **output_value** (type) - Description - **engine** (type) - Optional - Description ``` -------------------------------- ### Get All TA-Lib Indicators Source: https://vectorbt.dev/api/indicators/factory?q= Retrieves a list of all TA-Lib indicators. ```python IndicatorFactory.get_talib_indicators() ``` -------------------------------- ### Creating a Records Instance in VectorBT Source: https://vectorbt.dev/api/records/base?q= Demonstrates the setup for creating a Records object in vectorbt, including defining the data type, sample records array, and an ArrayWrapper. ```python >>> import numpy as np >>> import pandas as pd >>> from numba import njit >>> from collections import namedtuple >>> import vectorbt as vbt >>> example_dt = np.dtype([ ... ('id', np.int64), ... ('col', np.int64), ... ('idx', np.int64), ... ('some_field', np.float64) ... ]) >>> records_arr = np.array([ ... (0, 0, 0, 10.), ... (1, 0, 1, 11.), ... (2, 0, 2, 12.), ... (3, 1, 0, 13.), ... (4, 1, 1, 14.), ... (5, 1, 2, 15.), ... (6, 2, 0, 16.), ... (7, 2, 1, 17.), ... (8, 2, 2, 18.) ... ], dtype=example_dt) >>> wrapper = vbt.ArrayWrapper(index=['x', 'y', 'z'], ... columns=['a', 'b', 'c'], ndim=2, freq='1 day') >>> records = vbt.Records(wrapper, records_arr) ``` -------------------------------- ### GenericAccessor.ranges Source: https://vectorbt.dev/api/generic/accessors?q= Gets the ranges using GenericAccessor.get_ranges() with default arguments. ```APIDOC ## GenericAccessor.ranges ### Description Gets the ranges using GenericAccessor.get_ranges() with default arguments. ### Method GenericAccessor.ranges ### Endpoint GenericAccessor.ranges ### Parameters This property does not take any parameters. ### Response Returns the ranges. ### Response Example (Example output would depend on the underlying data and default get_ranges behavior) ``` -------------------------------- ### Simulate portfolio with random signals Source: https://vectorbt.dev/api/portfolio/base?q= Download historical closing prices and simulate a portfolio using random signals. This is useful for testing and demonstrating portfolio behavior. ```python >>> close = vbt.YFData.download( ... "BTC-USD", ... start='2020-01-01 UTC', ... end='2020-09-01 UTC' ... ).get('Close') >>> pf = vbt.Portfolio.from_random_signals(close, n=[10, 20], seed=42) >>> pf.wrapper.columns Index([10, 20], dtype='int64', name='rand_n') ```