### Install Quantdom from PyPI Source: https://github.com/constverum/quantdom/blob/master/README.rst Install the last stable release of Quantdom using pip. ```bash pip install quantdom ``` -------------------------------- ### Quantdom CLI Commands Source: https://context7.com/constverum/quantdom/llms.txt Provides examples of using the Quantdom command-line interface to launch the GUI, enable debug mode, set logging levels, and display version or help information. ```bash # Launch Quantdom GUI quantdom ``` ```bash # Run with debug mode enabled quantdom --debug ``` ```bash # Run with specific logging level quantdom --log DEBUG quantdom --log INFO quantdom --log WARNING ``` ```bash # Show version quantdom --version ``` ```bash # Show help quantdom --help ``` -------------------------------- ### Install Quantdom Development Version Source: https://github.com/constverum/quantdom/blob/master/README.rst Install the latest development version directly from GitHub using pip. ```bash pip install -U git+https://github.com/constverum/Quantdom.git ``` -------------------------------- ### Run Quantdom Application Source: https://github.com/constverum/quantdom/blob/master/README.rst Execute the Quantdom application after installation. ```bash quantdom ``` -------------------------------- ### Access Portfolio Performance Metrics Source: https://context7.com/constverum/quantdom/llms.txt Demonstrates how to access and print various performance metrics from a backtested portfolio. Metrics include net profit, trade statistics, risk measures, and profit ratios, categorized by 'All', 'Long', 'Short', and 'Market'. ```python from quantdom import Portfolio # After running a backtest and calling Portfolio.summarize() # Access performance metrics by category: perf = Portfolio.performance # Net profit metrics print(f"Net Profit ($): {perf['All'].net_profit_abs:.2f}") print(f"Net Profit (%): {perf['All'].net_profit_perc:.2f}%") print(f"Annualized Return: {perf['All'].year_profit:.2f}%") print(f"Monthly Return: {perf['All'].month_profit:.2f}%") # Trade statistics print(f"Total Trades: {perf['All'].total_trades}") print(f"Winning Trades: {perf['All'].win_trades_abs} ({perf['All'].win_trades_perc}%)") print(f"Losing Trades: {perf['All'].loss_trades_abs} ({perf['All'].loss_trades_perc}%)") # Risk metrics print(f"Max Drawdown ($): {perf['All'].max_drawdown_abs:.2f}") print(f"Max Drawdown (%): {perf['All'].max_drawdown_perc:.2f}%") print(f"Sharpe Ratio: {perf['All'].sharpe_ratio:.2f}") print(f"Sortino Ratio: {perf['All'].sortino_ratio:.2f}") # Profit ratios print(f"Profit Factor: {perf['All'].profit_factor:.2f}") print(f"Recovery Factor: {perf['All'].recovery_factor:.2f}") print(f"Payoff Ratio: {perf['All'].payoff_ratio:.2f}") # Compare long vs short performance print(f"Long Profit: {perf['Long'].net_profit_abs:.2f}") print(f"Short Profit: {perf['Short'].net_profit_abs:.2f}") print(f"Buy & Hold: {perf['Market'].net_profit_abs:.2f}") # Available categories: 'All', 'Long', 'Short', 'Market' (buy & hold) ``` -------------------------------- ### Implement Momentum Trading Strategy in Python Source: https://context7.com/constverum/quantdom/llms.txt Extend AbstractStrategy to create a momentum trading strategy. Initialize parameters in `init()` and define trading logic in `handle()`. Requires `quantdom` library. ```python from quantdom import AbstractStrategy, Order, Portfolio class MomentumStrategy(AbstractStrategy): """A simple momentum-based trading strategy.""" def init(self, lookback=10, threshold=0.02): # Initialize portfolio and strategy parameters Portfolio.initial_balance = 100_000 self.lookback = lookback self.threshold = threshold self.prices = [] self.last_position = None self.volume = 100 # shares per trade def handle(self, quote): # Collect price data self.prices.append(quote.close) # Need enough data for lookback period if len(self.prices) < self.lookback: return # Calculate momentum as percentage change momentum = (self.prices[-1] - self.prices[-self.lookback]) / self.prices[-self.lookback] # Trading logic if momentum > self.threshold and not self.last_position: # Open long position self.last_position = Order.open( symbol=self.symbol, otype=Order.BUY, price=quote.open, volume=self.volume, time=quote.time, ) elif momentum < -self.threshold and self.last_position: # Close position Order.close(self.last_position, price=quote.open, time=quote.time) self.last_position = None ``` -------------------------------- ### Implement Three Bar Trading Strategy in Python Source: https://context7.com/constverum/quantdom/llms.txt Extend AbstractStrategy to implement a trading strategy based on consecutive bullish or bearish bars. Initialize parameters in `init()` and define trading logic in `handle()`. Requires `quantdom` library. ```python from quantdom import AbstractStrategy, Order, Portfolio class ThreeBarStrategy(AbstractStrategy): """Trade based on consecutive bullish/bearish bars.""" def init(self, high_bars=3, low_bars=3): Portfolio.initial_balance = 100_000 self.seq_low_bars = 0 self.seq_high_bars = 0 self.signal = None self.last_position = None self.volume = 100 self.high_bars = high_bars self.low_bars = low_bars def handle(self, quote): # Execute pending signals if self.signal: props = { 'symbol': self.symbol, 'otype': self.signal, 'price': quote.open, 'volume': self.volume, 'time': quote.time, } if not self.last_position: # Open new position self.last_position = Order.open(**props) elif self.last_position.type != self.signal: # Close existing and reverse Order.close(self.last_position, price=quote.open, time=quote.time) self.last_position = Order.open(**props) self.signal = False self.seq_high_bars = self.seq_low_bars = 0 # Count consecutive bars if quote.close > quote.open: self.seq_high_bars += 1 self.seq_low_bars = 0 else: self.seq_high_bars = 0 self.seq_low_bars += 1 # Generate signals if self.seq_high_bars == self.high_bars: self.signal = Order.BUY elif self.seq_low_bars == self.low_bars: self.signal = Order.SELL ``` -------------------------------- ### Define and Optimize a Trading Strategy Source: https://context7.com/constverum/quantdom/llms.txt Defines an optimizable trading strategy with tunable parameters (fast_period, slow_period, threshold) using the AbstractStrategy class. Includes logic for opening and closing orders based on moving average crossovers. Shows how to define parameter ranges for grid search optimization. ```python from quantdom import AbstractStrategy, Order, Portfolio class OptimizableStrategy(AbstractStrategy): """Strategy with tunable parameters for optimization.""" def init(self, fast_period=5, slow_period=20, threshold=0.01): Portfolio.initial_balance = 100_000 self.fast_period = fast_period self.slow_period = slow_period self.threshold = threshold self.prices = [] self.last_position = None self.volume = 100 def handle(self, quote): self.prices.append(quote.close) if len(self.prices) < self.slow_period: return fast_ma = sum(self.prices[-self.fast_period:]) / self.fast_period slow_ma = sum(self.prices[-self.slow_period:]) / self.slow_period signal = (fast_ma - slow_ma) / slow_ma if signal > self.threshold and not self.last_position: self.last_position = Order.open( symbol=self.symbol, otype=Order.BUY, price=quote.open, volume=self.volume, time=quote.time ) elif signal < -self.threshold and self.last_position: Order.close(self.last_position, price=quote.open, time=quote.time) self.last_position = None # Define optimization parameter ranges optimization_params = { 'fast_period': [3, 5, 8, 10], 'slow_period': [15, 20, 30, 50], 'threshold': [0.005, 0.01, 0.02], } # Run optimization (performed by GUI or manually) # Portfolio.run_optimization(strategy, optimization_params) # Results stored in Portfolio.brief_performance with metrics: # - net_profit_abs, net_profit_perc, year_profit # - win_trades_abs, win_trades_perc # - profit_factor, recovery_factor, payoff_ratio # - max_drawdown_abs ``` -------------------------------- ### Three-Bar Trading Strategy Implementation Source: https://github.com/constverum/quantdom/blob/master/README.rst A Python implementation of a simple trading strategy based on consecutive bullish or bearish bars. Requires importing AbstractStrategy, Order, and Portfolio from quantdom. ```python from quantdom import AbstractStrategy, Order, Portfolio class ThreeBarStrategy(AbstractStrategy): def init(self, high_bars=3, low_bars=3): Portfolio.initial_balance = 100000 # default value self.seq_low_bars = 0 self.seq_high_bars = 0 self.signal = None self.last_position = None self.volume = 100 # shares self.high_bars = high_bars self.low_bars = low_bars def handle(self, quote): if self.signal: props = { 'symbol': self.symbol, # current selected symbol 'otype': self.signal, 'price': quote.open, 'volume': self.volume, 'time': quote.time, } if not self.last_position: self.last_position = Order.open(**props) elif self.last_position.type != self.signal: Order.close(self.last_position, price=quote.open, time=quote.time) self.last_position = Order.open(**props) self.signal = False self.seq_high_bars = self.seq_low_bars = 0 if quote.close > quote.open: ``` -------------------------------- ### Contributing to Quantdom Source: https://github.com/constverum/quantdom/blob/master/README.rst Standard Git commands for contributing to the Quantdom project. This involves forking the repository, creating a feature branch, committing changes, and submitting a pull request. ```bash git checkout -b my-new-feature git commit -am 'Add some feature' git push origin my-new-feature ``` -------------------------------- ### Import Indicator and Charting Libraries Source: https://context7.com/constverum/quantdom/llms.txt Imports necessary classes and constants for defining custom technical indicators and working with charting types in Quantdom. ```python from quantdom.lib import Indicator, Quotes from quantdom.lib.const import ChartType import numpy as np ``` -------------------------------- ### Define a Risk Managed Strategy with Portfolio Source: https://context7.com/constverum/quantdom/llms.txt Implement a trading strategy that manages position sizing based on portfolio risk percentage. Requires importing AbstractStrategy, Order, and Portfolio. ```python from quantdom import AbstractStrategy, Order, Portfolio class RiskManagedStrategy(AbstractStrategy): """Strategy with portfolio-based position sizing.""" def init(self, risk_percent=2.0): Portfolio.initial_balance = 50_000 self.risk_percent = risk_percent self.last_position = None def handle(self, quote): # Calculate position size based on portfolio balance risk_amount = Portfolio.balance * (self.risk_percent / 100) position_size = int(risk_amount / quote.close) # Simple moving average crossover logic if quote.close > quote.open * 1.01: # 1% up day if not self.last_position: self.last_position = Order.open( symbol=self.symbol, otype=Order.BUY, price=quote.open, volume=position_size, time=quote.time, sl=quote.open * 0.98, # 2% stop loss tp=quote.open * 1.05, # 5% take profit ) elif self.last_position and quote.close < quote.open: Order.close(self.last_position, price=quote.open, time=quote.time) self.last_position = None # After backtest, access portfolio metrics # Portfolio.summarize() # Called automatically by the framework # Portfolio.performance['All'].net_profit_abs # Total profit in currency # Portfolio.performance['All'].sharpe_ratio # Annualized Sharpe ratio # Portfolio.performance['All'].profit_factor # Gross profit / Gross loss # Portfolio.position_count() # Total number of trades # Portfolio.position_count(Order.BUY) # Long trades only # Portfolio.position_count(Order.SELL) # Short trades only ``` -------------------------------- ### Trading Logic Implementation Source: https://github.com/constverum/quantdom/blob/master/README.rst This Python code snippet implements trading logic based on sequential high and low bars. It determines buy or sell signals when a specified number of consecutive high or low bars are met. Ensure 'Order' enum is defined elsewhere. ```python self.seq_high_bars += 1 self.seq_low_bars = 0 else: self.seq_high_bars = 0 self.seq_low_bars += 1 if self.seq_high_bars == self.high_bars: self.signal = Order.BUY elif self.seq_low_bars == self.low_bars: self.signal = Order.SELL ``` -------------------------------- ### Access OHLCV Data from Quotes Singleton Source: https://context7.com/constverum/quantdom/llms.txt Interact with the Quotes singleton, a NumPy recarray storing market data. Access individual bars and specific fields like close price and volume. ```python from quantdom.lib import Quotes import numpy as np # After loading data, access quote properties # Quotes is a numpy recarray with fields: id, time, open, high, low, close, volume # Access individual bars last_bar = Quotes[-1] print(f"Last close: {last_bar.close}") print(f"Last volume: {last_bar.volume}") ``` -------------------------------- ### Create SMA Indicator Source: https://context7.com/constverum/quantdom/llms.txt Instantiates a Simple Moving Average (SMA) indicator with specified parameters. This indicator can be added to charts for technical analysis. ```python sma_20 = Indicator( label='SMA(20)', window=20, data=calculate_sma(20), tp=ChartType.LINE, color='blue', linewidth=1.5, ) ``` -------------------------------- ### Calculate Bollinger Bands Source: https://context7.com/constverum/quantdom/llms.txt Calculates Bollinger Bands, which consist of a Simple Moving Average (SMA) and upper/lower bands based on standard deviations. Requires a period and standard deviation multiplier. ```python def calculate_bollinger(period=20, std_dev=2): sma = calculate_sma(period) rolling_std = np.array([ np.std(Quotes.close[max(0, i-period):i+1]) for i in range(len(Quotes)) ]) upper = sma + (std_dev * rolling_std) lower = sma - (std_dev * rolling_std) return sma, upper, lower ``` -------------------------------- ### Fetch Historical Quotes with get_quotes Source: https://context7.com/constverum/quantdom/llms.txt Load historical market data using the get_quotes function, which automatically attempts multiple data sources. Specify symbol, date range, and optionally a specific loader. ```python from datetime import date from quantdom.lib import ( get_quotes, get_symbols, YahooQuotesLoader, StooqQuotesLoader, IEXQuotesLoader, ) # Get available NASDAQ symbols symbols = get_symbols() # Returns DataFrame with columns: Symbol, Security Name # Automatic multi-source quote fetching (tries Yahoo, IEX, Stooq) quotes = get_quotes( symbol='AAPL', date_from=date(2023, 1, 1), date_to=date(2023, 12, 31), ) # Returns Quotes recarray with: id, time, open, high, low, close, volume # Direct loader usage for specific source quotes = YahooQuotesLoader.get_quotes( symbol='MSFT', date_from=date(2023, 1, 1), date_to=date(2023, 12, 31), ) # Available loaders: # - YahooQuotesLoader - Yahoo Finance (most reliable) # - StooqQuotesLoader - Stooq.com data # - IEXQuotesLoader - IEX Cloud # - GoogleQuotesLoader - Google Finance (may have issues) # - QuandleQuotesLoader - Quandl data # - AlphaVantageQuotesLoader - Alpha Vantage (requires API key) ``` -------------------------------- ### Define Market Instruments with Symbol Class Source: https://context7.com/constverum/quantdom/llms.txt Define market instruments like stocks, FOREX pairs, and futures contracts using the Symbol class. Specify ticker, mode, and tick size for accurate trading calculations. ```python from quantdom.lib import Symbol # Define a stock symbol stock = Symbol( ticker='AAPL', mode=Symbol.SHARES, tick_size=0.01, # Minimum price movement ) # Define a FOREX pair forex_pair = Symbol( ticker='EUR/USD', mode=Symbol.FOREX, tick_size=0.0001, # pip size ) # forex_pair.contract_size = 100_000 # Standard lot size (auto-set) # Define a futures contract futures = Symbol( ticker='ES', # E-mini S&P 500 mode=Symbol.FUTURES, tick_size=0.25, tick_value=12.50, # Dollar value per tick ) # Symbol types available: # Symbol.FOREX - Currency pairs with contract size calculation # Symbol.CFD - Contracts for difference # Symbol.FUTURES - Futures contracts with tick value # Symbol.SHARES - Stocks and ETFs (default) ``` -------------------------------- ### Calculate Simple Moving Average Source: https://context7.com/constverum/quantdom/llms.txt Defines a function to calculate the Simple Moving Average (SMA) for a given period using NumPy's convolution. This is useful for smoothing price data. ```python def calculate_sma(period): weights = np.ones(period) / period return np.convolve(Quotes.close, weights, mode='same') ``` -------------------------------- ### Calculate Vectorized Operations and SMA Source: https://context7.com/constverum/quantdom/llms.txt Performs vectorized calculations for returns and volatility. Defines a function to compute Simple Moving Average (SMA) using convolution. Slices quotes for recent data and extracts max/min values. Converts Unix timestamp to datetime objects. ```python returns = np.diff(Quotes.close) / Quotes.close[:-1] volatility = np.std(returns) * np.sqrt(252) ``` ```python def sma(period): return np.convolve(Quotes.close, np.ones(period)/period, mode='valid') ``` ```python recent_quotes = Quotes[-20:] # Last 20 bars high_of_period = recent_quotes.high.max() low_of_period = recent_quotes.low.min() ``` ```python from datetime import datetime bar_time = datetime.fromtimestamp(Quotes[0].time) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.