### Complete AlphaFlow Backtest Setup and Execution Source: https://github.com/brandonschabell/alphaflow/blob/main/docs/getting_started.md A comprehensive example demonstrating the full setup of an AlphaFlow backtest. It includes importing necessary modules, configuring cash, time periods, benchmark, universe, data feeds, strategies, brokers, analyzers, and finally running the backtest. ```python import os from datetime import datetime import alphaflow as af from alphaflow.analyzers import DefaultAnalyzer from alphaflow.brokers import SimpleBroker from alphaflow.data_feeds import FMPDataFeed from alphaflow.strategies import BuyAndHoldStrategy # Set FinancialModelingPrep API key os.environ["FMP_API_KEY"] = "" # Create flow flow = af.AlphaFlow() # Set cash and backtest time period flow.set_cash(100000) flow.set_backtest_start_timestamp(datetime(2000, 1, 1)) flow.set_backtest_end_timestamp(datetime(2025, 1, 1)) # Set benchmark flow.set_benchmark("SPY") # Set universe flow.add_equity("BRK-B") flow.add_equity("BND") # Add datafeed flow.set_data_feed(FMPDataFeed()) # Add strategies flow.add_strategy( BuyAndHoldStrategy(symbol="BRK-B", target_weight=0.75, min_dollar_delta=500, share_quantization=1), ) flow.add_strategy( BuyAndHoldStrategy(symbol="BND", target_weight=0.25, min_dollar_delta=500, share_quantization=1), ) # Set broker flow.set_broker(SimpleBroker()) # Add analyzer flow.add_analyzer(DefaultAnalyzer(plot_path="example_analysis.png", plot_title="Example Analysis")) # Run backtest flow.run() ``` -------------------------------- ### Run AlphaFlow Backtest Source: https://github.com/brandonschabell/alphaflow/blob/main/docs/getting_started.md Executes the configured backtest simulation within the AlphaFlow framework. This function triggers the strategy execution, data processing, and result generation based on the prior setup. ```python flow.run() ``` -------------------------------- ### Configure Backtest Parameters Source: https://github.com/brandonschabell/alphaflow/blob/main/docs/getting_started.md Sets fundamental backtest parameters including initial cash, start and end timestamps, and a benchmark for performance comparison. These settings define the financial and temporal scope of the backtest. ```python flow.set_cash(100000) # Sets the initial portfolio cash to $100,000. from datetime import datetime flow.set_backtest_start_timestamp(datetime(2000, 1, 1)) flow.set_backtest_end_timestamp(datetime(2025, 1, 1)) flow.set_benchmark("SPY") ``` -------------------------------- ### Add Trading Strategies Source: https://github.com/brandonschabell/alphaflow/blob/main/docs/getting_started.md Implements trading strategies that generate order events based on predefined logic. This example uses BuyAndHoldStrategy to maintain specific target weights for assets, with options for minimum trade value and share quantization. ```python from alphaflow.strategies import BuyAndHoldStrategy flow.add_strategy( BuyAndHoldStrategy(symbol="BRK-B", target_weight=0.75, min_dollar_delta=500, share_quantization=1), ) flow.add_strategy( BuyAndHoldStrategy(symbol="BND", target_weight=0.25, min_dollar_delta=500, share_quantization=1), ) ``` -------------------------------- ### Initialize AlphaFlow Source: https://github.com/brandonschabell/alphaflow/blob/main/docs/getting_started.md Creates the main AlphaFlow object, which acts as the central hub for backtesting configurations and components. This is the foundational step for any AlphaFlow backtest. ```python import alphaflow as af flow = af.AlphaFlow() ``` -------------------------------- ### Set Data Feed Source: https://github.com/brandonschabell/alphaflow/blob/main/docs/getting_started.md Configures the data source for the backtest, such as market price information. This example uses FMPDataFeed, requiring an API key which can be provided directly or via an environment variable. ```python from alphaflow.data_feeds import FMPDataFeed flow.set_data_feed(FMPDataFeed(api_key="")) # The API key can also be set via environment variable: # export FMP_API_KEY="" ``` -------------------------------- ### Basic AlphaFlow Backtest Example Source: https://github.com/brandonschabell/alphaflow/blob/main/README.md Demonstrates a fundamental AlphaFlow backtest setup. This includes initializing AlphaFlow, setting cash and backtest dates, configuring a data feed, defining an equity universe, adding trading strategies, setting up a broker, and running the backtest simulation. ```python from datetime import datetime import alphaflow as af # 1. Initialize AlphaFlow flow = af.AlphaFlow() flow.set_cash(100000) flow.set_backtest_start_timestamp(datetime(1990, 2, 10)) flow.set_backtest_end_timestamp(datetime(2025, 1, 5)) # 2. Create DataFeed (e.g., CSV-based daily bars) flow.set_data_feed( af.data_feeds.CSVDataFeed( file_path="historical_data.csv", ) ) # 3. Set Equity Universe flow.add_equity("BND") flow.add_equity("SPY") # 4. Initialize Strategy flow.add_strategy( af.strategies.BuyAndHoldStrategy( symbol="SPY", target_weight=0.9 ) ) flow.add_strategy( af.strategies.BuyAndHoldStrategy( symbol="BND", target_weight=0.1 ) ) # 5. Create Broker flow.set_broker( af.brokers.SimpleBroker() ) # 6. Run the backtest flow.run() ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/brandonschabell/alphaflow/blob/main/docs/contributing.md Steps to clone the AlphaFlow repository and install its dependencies using uv. This is the initial setup for development. ```bash git clone https://github.com/YOUR_USERNAME/alphaflow.git cd alphaflow uv sync --all-extras ``` -------------------------------- ### Set Broker for Trade Execution Source: https://github.com/brandonschabell/alphaflow/blob/main/docs/getting_started.md Configures the broker responsible for executing trades based on order events generated by strategies. The SimpleBroker simulates immediate trade execution for demonstration purposes. ```python from alphaflow.brokers import SimpleBroker flow.set_broker(SimpleBroker()) ``` -------------------------------- ### Attach Default Analyzer to AlphaFlow Strategy Source: https://github.com/brandonschabell/alphaflow/blob/main/docs/getting_started.md Attaches the `DefaultAnalyzer` to an AlphaFlow instance to evaluate strategy performance. It requires the `alphaflow.analyzers` module and outputs analysis plots and metrics. The `plot_path` and `plot_title` parameters customize the output. ```python from alphaflow.analyzers import DefaultAnalyzer flow.add_analyzer(DefaultAnalyzer(plot_path="example_analysis.png", plot_title="Example Analysis")) ``` -------------------------------- ### Define Stock Universe Source: https://github.com/brandonschabell/alphaflow/blob/main/docs/getting_started.md Specifies the universe of stock tickers for which data will be pulled during the backtest. This includes adding individual equities and potentially auto-added tickers from benchmarks. ```python flow.add_equity("BRK-B") flow.add_equity("BND") ``` -------------------------------- ### Install AlphaFlow using pip Source: https://github.com/brandonschabell/alphaflow/blob/main/README.md Installs the AlphaFlow library using pip, the Python package installer. Ensure you have Python and pip set up on your system. ```bash pip install alphaflow ``` -------------------------------- ### Create Order Events (Python) Source: https://context7.com/brandonschabell/alphaflow/llms.txt This example demonstrates the creation of OrderEvent objects, which are used to represent trading instructions from strategies to brokers. It shows how to define both market buy orders and limit sell orders, specifying symbol, side, quantity, order type, and optionally a limit price. It requires OrderEvent, Side, OrderType from alphaflow.events and alphaflow.enums, and datetime. ```python from alphaflow.events import OrderEvent from alphaflow.enums import Side, OrderType from datetime import datetime # Market buy order buy_order = OrderEvent( timestamp=datetime(2024, 1, 1, 9, 30), symbol="AAPL", side=Side.BUY, qty=100, order_type=OrderType.MARKET ) # Limit sell order sell_order = OrderEvent( timestamp=datetime(2024, 1, 1, 14, 30), symbol="AAPL", side=Side.SELL, qty=50, order_type=OrderType.LIMIT, limit_price=180.0 ) ``` -------------------------------- ### Load Historical Data with AlphaFlow CSVDataFeed Source: https://context7.com/brandonschabell/alphaflow/llms.txt This Python example demonstrates using AlphaFlow's CSVDataFeed to load historical market data. It shows how to initialize the data feed, specifying the file path and custom column names for timestamp, symbol, open, high, low, close, and volume. The code iterates through the loaded data for a specific symbol and date range, printing timestamp and closing price. ```python from alphaflow.data_feeds import CSVDataFeed from datetime import datetime # Initialize CSV data feed with custom column names data_feed = CSVDataFeed( file_path="market_data.csv", col_timestamp="Date", col_symbol="Symbol", col_open="Open", col_high="High", col_low="Low", col_close="Close", col_volume="Volume" ) # Load data for a symbol for event in data_feed.run( symbol="AAPL", start_timestamp=datetime(2020, 1, 1), end_timestamp=datetime(2024, 1, 1) ): print(f"{event.timestamp}: {event.symbol} close={event.close}") ``` -------------------------------- ### Build and Serve Documentation Source: https://github.com/brandonschabell/alphaflow/blob/main/docs/contributing.md Commands to build static documentation and serve it locally for preview using MkDocs. Essential for checking documentation changes. ```bash uv run mkdocs serve uv run mkdocs build ``` -------------------------------- ### Initialize and Run AlphaFlow Backtest Simulation Source: https://context7.com/brandonschabell/alphaflow/llms.txt This Python snippet demonstrates how to initialize and run a complete backtest simulation using the AlphaFlow framework. It covers setting initial cash, backtest date range, configuring data feeds, defining the trading universe, adding strategies, setting a broker, and adding an analyzer for performance metrics. It requires the 'alphaflow' library. ```python from datetime import datetime import alphaflow as af # Initialize backtest engine flow = af.AlphaFlow() flow.set_cash(100000) flow.set_backtest_start_timestamp(datetime(1990, 2, 10)) flow.set_backtest_end_timestamp(datetime(2025, 1, 5)) # Configure data source flow.set_data_feed( af.data_feeds.CSVDataFeed( file_path="historical_data.csv" ) ) # Define trading universe flow.add_equity("SPY") flow.add_equity("BND") flow.set_benchmark("SPY") # Add strategies flow.add_strategy( af.strategies.BuyAndHoldStrategy( symbol="SPY", target_weight=0.9 ) ) flow.add_strategy( af.strategies.BuyAndHoldStrategy( symbol="BND", target_weight=0.1 ) ) # Set broker for order execution flow.set_broker(af.brokers.SimpleBroker()) # Add analyzer for performance metrics flow.add_analyzer( af.analyzers.DefaultAnalyzer( plot_path="backtest_results.png", plot_title="Portfolio Performance" ) ) # Run backtest flow.run() ``` -------------------------------- ### Python: Multi-Strategy Backtest with AlphaFlow Source: https://context7.com/brandonschabell/alphaflow/llms.txt Sets up and runs a comprehensive backtest using AlphaFlow. This involves initializing the backtester, configuring cash, backtest period, data feed, portfolio with multiple assets and strategies, benchmark, broker with margin, and performance analyzers. Finally, it executes the backtest and notes the expected output metrics. ```python from datetime import datetime from pathlib import Path import alphaflow as af # Initialize backtest flow = af.AlphaFlow() flow.set_cash(100000) flow.set_backtest_start_timestamp(datetime(2007, 6, 1)) flow.set_backtest_end_timestamp(datetime(2024, 12, 31)) # Configure data feed flow.set_data_feed(af.data_feeds.CSVDataFeed(file_path="market_data.csv")) # Build portfolio with multiple assets assets = { "SPY": 0.50, # 50% S&P 500 "BND": 0.30, # 30% Bonds "GLD": 0.15, # 15% Gold "VNQ": 0.05 # 5% Real Estate } for symbol, weight in assets.items(): flow.add_equity(symbol) flow.add_strategy( af.strategies.BuyAndHoldStrategy( symbol=symbol, target_weight=weight, share_quantization=1, min_dollar_delta=100 ) ) # Set benchmark for comparison flow.set_benchmark("SPY") # Configure broker with margin flow.set_broker(af.brokers.SimpleBroker(margin=1.0)) # Add performance analyzer flow.add_analyzer( af.analyzers.DefaultAnalyzer( plot_path=Path("portfolio_performance.png"), plot_title="Multi-Asset Portfolio vs SPY Benchmark" ) ) # Run backtest flow.run() # Output includes: # - Max Drawdown: 0.1523 (Benchmark: 0.3389) # - Sharpe Ratio: 1.2456 (Benchmark: 0.8932) # - Sortino Ratio: 1.8765 (Benchmark: 1.2341) # - Annualized Return: 0.0987 (Benchmark: 0.0923) # - Total Return: 2.4567 (Benchmark: 2.1234) # - Plot saved to portfolio_performance.png ``` -------------------------------- ### Configure SimpleBroker with Margin in AlphaFlow Source: https://context7.com/brandonschabell/alphaflow/llms.txt This Python code demonstrates configuring the SimpleBroker in AlphaFlow, including support for margin trading. It shows how to initialize a SimpleBroker with a specified margin multiplier (e.g., 2.0 for 2x margin, allowing portfolio value * 2 for buying). It also shows how to create a broker that only uses available cash (margin=1.0). ```python from alphaflow.brokers import SimpleBroker from alphaflow import AlphaFlow flow = AlphaFlow() # Broker with 2x margin (can use portfolio value * 2 for buying) broker = SimpleBroker(margin=2.0) flow.set_broker(broker) # Broker with no margin (cash only) broker_no_margin = SimpleBroker(margin=1.0) ``` -------------------------------- ### Calculate Performance Metrics with DefaultAnalyzer (Python) Source: https://context7.com/brandonschabell/alphaflow/llms.txt This snippet demonstrates how to initialize and use the DefaultAnalyzer to calculate comprehensive performance metrics and generate visualizations for a trading strategy. It requires the AlphaFlow and DefaultAnalyzer classes, and specifies an output path and title for the performance plot. ```python from alphaflow.analyzers import DefaultAnalyzer from alphaflow import AlphaFlow from pathlib import Path flow = AlphaFlow() # Analyzer with plot output analyzer = DefaultAnalyzer( plot_path=Path("performance.png"), plot_title="Strategy Performance vs Benchmark" ) flow.add_analyzer(analyzer) # After backtest completes, analyzer prints: # - Max Drawdown # - Sharpe Ratio # - Sortino Ratio # - Annualized Return # - Total Return # And generates a plot with portfolio value over time ``` -------------------------------- ### Manage Portfolio State with AlphaFlow (Python) Source: https://context7.com/brandonschabell/alphaflow/llms.txt This code illustrates how to manage the portfolio's state within the AlphaFlow framework. It covers setting initial cash, querying current cash and position values, and calculating buying power, including margin considerations. It utilizes the AlphaFlow and Portfolio classes. ```python from alphaflow import AlphaFlow, Portfolio from datetime import datetime flow = AlphaFlow() portfolio = flow.portfolio # Set initial cash portfolio.set_cash(100000) # Query portfolio state cash = portfolio.get_cash() position = portfolio.get_position("AAPL") position_value = portfolio.get_position_value("AAPL", datetime.now()) total_value = portfolio.get_portfolio_value(datetime.now()) # Check buying power with margin buying_power = portfolio.get_buying_power(margin=2.0, timestamp=datetime.now()) print(f"Cash: ${cash:,.2f}") print(f"AAPL shares: {position}") print(f"Portfolio value: ${total_value:,.2f}") print(f"Buying power: ${buying_power:,.2f}") ``` -------------------------------- ### AlphaFlow EventBus Publish-Subscribe System Source: https://context7.com/brandonschabell/alphaflow/llms.txt This Python code illustrates the EventBus, AlphaFlow's central event routing mechanism for decoupled component communication. It shows how to create an EventBus, define a subscriber that reads specific event types (like MarketDataEvent), subscribe to topics, and publish events. It also covers enabling and processing events in queue mode for chronological simulation. ```python from alphaflow.event_bus.event_bus import EventBus from alphaflow.enums import Topic from alphaflow.events import MarketDataEvent, OrderEvent, FillEvent from alphaflow.event_bus.subscriber import Subscriber from alphaflow.events.event import Event from datetime import datetime # Create event bus bus = EventBus() # Define a subscriber class MyStrategy(Subscriber): def read_event(self, event: Event) -> None: if isinstance(event, MarketDataEvent): print(f"Received price data: {event.symbol} @ {event.close}") # Subscribe to topics strategy = MyStrategy() bus.subscribe(Topic.MARKET_DATA, strategy) # Publish events (immediate mode) event = MarketDataEvent( timestamp=datetime(2024, 1, 1), symbol="AAPL", open=150.0, high=155.0, low=149.0, close=154.0, volume=1000000 ) bus.publish(Topic.MARKET_DATA, event) # Enable queue mode for backtesting (chronological order) bus.enable_queue_mode() bus.publish(Topic.MARKET_DATA, event) bus.process_queue() # Process all queued events bus.disable_queue_mode() ``` -------------------------------- ### Run Development Tests and Checks Source: https://github.com/brandonschabell/alphaflow/blob/main/docs/contributing.md Commands to execute tests, quality checks (linting, type checking), and code coverage reports for the AlphaFlow project. Ensures code quality and correctness. ```bash make test make check make coverage ``` -------------------------------- ### Implement Buy and Hold Strategy with Rebalancing in AlphaFlow Source: https://context7.com/brandonschabell/alphaflow/llms.txt This Python snippet shows how to define and add a BuyAndHoldStrategy to an AlphaFlow backtest simulation. It illustrates setting a target portfolio weight for a symbol (e.g., 60% for AAPL) and configuring rebalancing thresholds, including minimum dollar delta, minimum share delta, and share quantization. This allows for maintaining desired portfolio allocations while avoiding excessive trading. ```python from alphaflow import AlphaFlow from alphaflow.strategies import BuyAndHoldStrategy from datetime import datetime flow = AlphaFlow() flow.set_cash(100000) flow.set_backtest_start_timestamp(datetime(2020, 1, 1)) # Strategy with rebalancing thresholds strategy = BuyAndHoldStrategy( symbol="AAPL", target_weight=0.6, # Maintain 60% portfolio weight min_dollar_delta=100, # Only rebalance if $100+ difference min_share_delta=1, # Only trade if 1+ shares needed share_quantization=1 # Round to whole shares ) flow.add_strategy(strategy) ``` -------------------------------- ### Create Fill Event (Python) Source: https://context7.com/brandonschabell/alphaflow/llms.txt This snippet shows how to create a FillEvent object, representing an executed trade from a broker to a portfolio. It includes the timestamp, symbol, fill price, fill quantity (positive for buys, negative for sells), and commission. It requires the FillEvent class from alphaflow.events and the datetime object. ```python from alphaflow.events import FillEvent from datetime import datetime # Create fill event fill = FillEvent( timestamp=datetime(2024, 1, 1, 9, 30), symbol="AAPL", fill_price=175.50, fill_qty=100, # Positive for buys, negative for sells commission=1.0 ) print(f"Filled {fill.fill_qty} shares of {fill.symbol} @ ${fill.fill_price}") print(f"Commission: ${fill.commission}") ``` -------------------------------- ### Create and Push Feature Branch Source: https://github.com/brandonschabell/alphaflow/blob/main/docs/contributing.md Steps to create a new feature branch, make changes, commit them with clear messages, and push the branch to your forked repository. This is part of the standard Git workflow for contributions. ```bash git checkout -b feature/your-feature-name # Make your changes git commit -m "Add feature: description of what you added" git push origin feature/your-feature-name ``` -------------------------------- ### Create Market Data Event (Python) Source: https://context7.com/brandonschabell/alphaflow/llms.txt This snippet shows how to create a MarketDataEvent object, which represents OHLCV (Open, High, Low, Close, Volume) price data for a specific symbol at a given timestamp. It requires the MarketDataEvent class from alphaflow.events and the datetime object. ```python from alphaflow.events import MarketDataEvent from datetime import datetime # Create market data event event = MarketDataEvent( timestamp=datetime(2024, 1, 1, 9, 30), symbol="TSLA", open=250.0, high=255.0, low=248.0, close=253.5, volume=5000000 ) print(f"{event.symbol} closed at ${event.close} on {event.timestamp}") ``` -------------------------------- ### Python: Simple Moving Average Crossover Strategy Source: https://context7.com/brandonschabell/alphaflow/llms.txt Implements a custom trading strategy based on Simple Moving Average (SMA) crossovers. It subscribes to market data, calculates short and long SMAs, and generates buy or sell signals based on their relationship. This strategy extends the base Strategy class from alphaflow. ```python from alphaflow import Strategy from alphaflow.enums import Topic, Side, OrderType from alphaflow.events import MarketDataEvent, OrderEvent from alphaflow.events.event import Event class SimpleMovingAverageCrossover(Strategy): def __init__(self, symbol: str, short_window: int = 20, long_window: int = 50): self.symbol = symbol self.short_window = short_window self.long_window = long_window self.prices = [] def topic_subscriptions(self) -> list[Topic]: return [Topic.MARKET_DATA] def read_event(self, event: Event) -> None: if not isinstance(event, MarketDataEvent): return if event.symbol != self.symbol: return self.prices.append(event.close) if len(self.prices) < self.long_window: return # Calculate moving averages short_ma = sum(self.prices[-self.short_window:]) / self.short_window long_ma = sum(self.prices[-self.long_window:]) / self.long_window # Generate signals position = self._alpha_flow.portfolio.get_position(self.symbol) if short_ma > long_ma and position == 0: # Buy signal cash = self._alpha_flow.portfolio.get_cash() qty = int(cash / event.close) self._alpha_flow.event_bus.publish( Topic.ORDER, OrderEvent( timestamp=event.timestamp, symbol=self.symbol, side=Side.BUY, qty=qty, order_type=OrderType.MARKET ) ) elif short_ma < long_ma and position > 0: # Sell signal self._alpha_flow.event_bus.publish( Topic.ORDER, OrderEvent( timestamp=event.timestamp, symbol=self.symbol, side=Side.SELL, qty=position, order_type=OrderType.MARKET ) ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.