How to Build Trading Strategy Screener with Ollama: Performance Ranking System

Build powerful trading strategy screener with Ollama to rank and analyze algorithmic trading performance. Complete guide with code examples and setup.

Ever tried picking winning stocks by throwing darts at the financial section? Your pet goldfish probably has better stock-picking skills. But what if you could build a smart system that evaluates trading strategies faster than your coffee gets cold?

Today, you'll learn to create a trading strategy screener using Ollama's AI capabilities. This system will rank trading strategies by performance metrics and help you identify profitable patterns without the guesswork.

What You'll Build

By the end of this guide, you'll have:

  • A functional trading strategy screener powered by Ollama
  • Performance ranking algorithms for strategy evaluation
  • Automated backtesting capabilities
  • Clear metrics for strategy comparison

Why Build a Trading Strategy Screener with Ollama?

Traditional trading platforms charge hefty fees for strategy screening tools. They often lack customization options and provide limited analytical depth. Building your own screener gives you complete control over evaluation criteria and ranking methodologies.

Ollama's local AI processing ensures your trading strategies remain private. No cloud dependencies mean faster processing and better data security for sensitive financial analysis.

Prerequisites and Setup Requirements

System Requirements

  • Python 3.8 or higher
  • 8GB RAM minimum (16GB recommended)
  • Ollama installed locally
  • Basic understanding of trading concepts

Required Python Libraries

# Install required packages
pip install pandas numpy yfinance ollama-python backtrader matplotlib seaborn

Ollama Model Setup

First, install and configure Ollama with a suitable model for financial analysis:

# Install Ollama (if not already installed)
curl -fsSL https://ollama.ai/install.sh | sh

# Pull a suitable model for financial analysis
ollama pull llama2:13b
# or for better performance with more VRAM
ollama pull codellama:34b

Core Components of the Trading Strategy Screener

Strategy Data Structure

Create a foundation for storing and managing trading strategies:

import pandas as pd
import numpy as np
from dataclasses import dataclass
from typing import List, Dict, Any
import ollama

@dataclass
class TradingStrategy:
    """Core trading strategy data structure"""
    name: str
    description: str
    entry_conditions: List[str]
    exit_conditions: List[str]
    risk_management: Dict[str, Any]
    timeframe: str
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert strategy to dictionary format"""
        return {
            'name': self.name,
            'description': self.description,
            'entry_conditions': self.entry_conditions,
            'exit_conditions': self.exit_conditions,
            'risk_management': self.risk_management,
            'timeframe': self.timeframe
        }

class StrategyRepository:
    """Manages collection of trading strategies"""
    
    def __init__(self):
        self.strategies = []
    
    def add_strategy(self, strategy: TradingStrategy):
        """Add new strategy to repository"""
        self.strategies.append(strategy)
    
    def get_strategies(self) -> List[TradingStrategy]:
        """Retrieve all strategies"""
        return self.strategies
    
    def find_by_name(self, name: str) -> TradingStrategy:
        """Find strategy by name"""
        for strategy in self.strategies:
            if strategy.name == name:
                return strategy
        return None

Performance Metrics Calculator

Build comprehensive performance evaluation tools:

class PerformanceCalculator:
    """Calculate trading strategy performance metrics"""
    
    @staticmethod
    def calculate_sharpe_ratio(returns: pd.Series, risk_free_rate: float = 0.02) -> float:
        """Calculate Sharpe ratio for strategy returns"""
        excess_returns = returns - risk_free_rate/252  # Daily risk-free rate
        return np.sqrt(252) * excess_returns.mean() / excess_returns.std()
    
    @staticmethod
    def calculate_max_drawdown(equity_curve: pd.Series) -> float:
        """Calculate maximum drawdown percentage"""
        rolling_max = equity_curve.expanding().max()
        drawdown = (equity_curve - rolling_max) / rolling_max
        return drawdown.min()
    
    @staticmethod
    def calculate_win_rate(trades: pd.DataFrame) -> float:
        """Calculate percentage of winning trades"""
        if len(trades) == 0:
            return 0.0
        winning_trades = len(trades[trades['pnl'] > 0])
        return winning_trades / len(trades)
    
    @staticmethod
    def calculate_profit_factor(trades: pd.DataFrame) -> float:
        """Calculate profit factor (gross profit / gross loss)"""
        gross_profit = trades[trades['pnl'] > 0]['pnl'].sum()
        gross_loss = abs(trades[trades['pnl'] < 0]['pnl'].sum())
        
        if gross_loss == 0:
            return float('inf') if gross_profit > 0 else 0
        return gross_profit / gross_loss
    
    def generate_performance_report(self, equity_curve: pd.Series, 
                                  trades: pd.DataFrame) -> Dict[str, float]:
        """Generate comprehensive performance metrics"""
        returns = equity_curve.pct_change().dropna()
        
        metrics = {
            'total_return': (equity_curve.iloc[-1] / equity_curve.iloc[0] - 1) * 100,
            'sharpe_ratio': self.calculate_sharpe_ratio(returns),
            'max_drawdown': self.calculate_max_drawdown(equity_curve) * 100,
            'win_rate': self.calculate_win_rate(trades) * 100,
            'profit_factor': self.calculate_profit_factor(trades),
            'total_trades': len(trades),
            'avg_trade_return': trades['pnl'].mean() if len(trades) > 0 else 0
        }
        
        return metrics

Ollama Integration for Strategy Analysis

AI-Powered Strategy Evaluation

Integrate Ollama to provide intelligent strategy analysis and ranking:

class OllamaStrategyAnalyzer:
    """Use Ollama AI for advanced strategy analysis"""
    
    def __init__(self, model_name: str = "llama2:13b"):
        self.model_name = model_name
        self.client = ollama.Client()
    
    def analyze_strategy_logic(self, strategy: TradingStrategy) -> Dict[str, Any]:
        """Analyze strategy logic using AI"""
        prompt = f"""
        Analyze this trading strategy and provide insights:
        
        Strategy Name: {strategy.name}
        Description: {strategy.description}
        Entry Conditions: {', '.join(strategy.entry_conditions)}
        Exit Conditions: {', '.join(strategy.exit_conditions)}
        Timeframe: {strategy.timeframe}
        
        Please evaluate:
        1. Strategy complexity score (1-10)
        2. Risk level assessment (Low/Medium/High)
        3. Market condition suitability
        4. Potential weaknesses
        5. Improvement suggestions
        
        Provide response in JSON format.
        """
        
        try:
            response = self.client.generate(
                model=self.model_name,
                prompt=prompt
            )
            
            # Parse AI response and extract insights
            analysis = self._parse_ai_response(response['response'])
            return analysis
            
        except Exception as e:
            print(f"AI analysis failed: {e}")
            return self._default_analysis()
    
    def _parse_ai_response(self, response: str) -> Dict[str, Any]:
        """Parse AI response into structured format"""
        # Simplified parsing - in production, use more robust JSON extraction
        try:
            import json
            import re
            
            # Extract JSON-like content from response
            json_match = re.search(r'\{.*\}', response, re.DOTALL)
            if json_match:
                return json.loads(json_match.group())
        except:
            pass
        
        return self._default_analysis()
    
    def _default_analysis(self) -> Dict[str, Any]:
        """Provide default analysis when AI fails"""
        return {
            "complexity_score": 5,
            "risk_level": "Medium",
            "market_suitability": "General",
            "weaknesses": ["Requires further analysis"],
            "improvements": ["Consider additional risk management"]
        }
    
    def rank_strategies(self, strategies: List[TradingStrategy], 
                       performance_data: Dict[str, Dict]) -> List[Dict[str, Any]]:
        """Rank strategies using AI analysis and performance metrics"""
        ranked_strategies = []
        
        for strategy in strategies:
            # Get AI analysis
            ai_analysis = self.analyze_strategy_logic(strategy)
            
            # Get performance metrics
            performance = performance_data.get(strategy.name, {})
            
            # Calculate composite score
            composite_score = self._calculate_composite_score(ai_analysis, performance)
            
            ranked_strategies.append({
                'strategy': strategy,
                'ai_analysis': ai_analysis,
                'performance': performance,
                'composite_score': composite_score
            })
        
        # Sort by composite score (descending)
        ranked_strategies.sort(key=lambda x: x['composite_score'], reverse=True)
        return ranked_strategies
    
    def _calculate_composite_score(self, ai_analysis: Dict, 
                                 performance: Dict) -> float:
        """Calculate weighted composite score for ranking"""
        # Normalize and weight different factors
        weights = {
            'sharpe_ratio': 0.25,
            'total_return': 0.20,
            'max_drawdown': 0.15,  # Lower is better
            'win_rate': 0.15,
            'profit_factor': 0.10,
            'ai_complexity': 0.10,
            'ai_risk': 0.05
        }
        
        score = 0.0
        
        # Performance-based scoring
        if 'sharpe_ratio' in performance:
            score += weights['sharpe_ratio'] * min(performance['sharpe_ratio'] / 2.0, 1.0)
        
        if 'total_return' in performance:
            score += weights['total_return'] * min(performance['total_return'] / 50.0, 1.0)
        
        if 'max_drawdown' in performance:
            # Invert drawdown (lower is better)
            score += weights['max_drawdown'] * max(1 - abs(performance['max_drawdown']) / 20.0, 0)
        
        if 'win_rate' in performance:
            score += weights['win_rate'] * performance['win_rate'] / 100.0
        
        if 'profit_factor' in performance:
            score += weights['profit_factor'] * min(performance['profit_factor'] / 2.0, 1.0)
        
        # AI analysis scoring
        if 'complexity_score' in ai_analysis:
            # Moderate complexity preferred (5-7 range)
            complexity = ai_analysis['complexity_score']
            complexity_score = 1.0 - abs(complexity - 6) / 10.0
            score += weights['ai_complexity'] * complexity_score
        
        if 'risk_level' in ai_analysis:
            risk_scores = {'Low': 0.8, 'Medium': 1.0, 'High': 0.6}
            score += weights['ai_risk'] * risk_scores.get(ai_analysis['risk_level'], 0.5)
        
        return score

Building the Complete Screener System

Main Screener Class

Combine all components into a cohesive screening system:

import yfinance as yf
import backtrader as bt
from datetime import datetime, timedelta

class TradingStrategyScreener:
    """Complete trading strategy screener with Ollama integration"""
    
    def __init__(self, model_name: str = "llama2:13b"):
        self.strategy_repo = StrategyRepository()
        self.performance_calc = PerformanceCalculator()
        self.ai_analyzer = OllamaStrategyAnalyzer(model_name)
        self.performance_data = {}
    
    def add_sample_strategies(self):
        """Add sample trading strategies for demonstration"""
        strategies = [
            TradingStrategy(
                name="RSI Reversal",
                description="Buy when RSI < 30, sell when RSI > 70",
                entry_conditions=["RSI < 30", "Volume > 20-day average"],
                exit_conditions=["RSI > 70", "Stop loss at -5%"],
                risk_management={"stop_loss": 0.05, "position_size": 0.1},
                timeframe="1D"
            ),
            TradingStrategy(
                name="Moving Average Cross",
                description="Golden cross and death cross strategy",
                entry_conditions=["50-day MA crosses above 200-day MA"],
                exit_conditions=["50-day MA crosses below 200-day MA"],
                risk_management={"stop_loss": 0.08, "position_size": 0.15},
                timeframe="1D"
            ),
            TradingStrategy(
                name="Bollinger Band Bounce",
                description="Buy at lower band, sell at upper band",
                entry_conditions=["Price touches lower Bollinger Band", "RSI < 40"],
                exit_conditions=["Price reaches upper Bollinger Band", "Stop loss at -3%"],
                risk_management={"stop_loss": 0.03, "position_size": 0.12},
                timeframe="1D"
            )
        ]
        
        for strategy in strategies:
            self.strategy_repo.add_strategy(strategy)
    
    def simulate_strategy_performance(self, strategy: TradingStrategy, 
                                    symbol: str = "SPY", 
                                    days: int = 252) -> Dict[str, Any]:
        """Simulate strategy performance (simplified backtesting)"""
        # Download historical data
        end_date = datetime.now()
        start_date = end_date - timedelta(days=days)
        
        try:
            data = yf.download(symbol, start=start_date, end=end_date)
            
            # Simulate trades based on strategy logic
            trades = self._simulate_trades(strategy, data)
            
            # Calculate equity curve
            equity_curve = self._calculate_equity_curve(trades, initial_capital=100000)
            
            # Generate performance metrics
            performance = self.performance_calc.generate_performance_report(
                equity_curve, trades
            )
            
            return {
                'trades': trades,
                'equity_curve': equity_curve,
                'performance': performance
            }
            
        except Exception as e:
            print(f"Performance simulation failed for {strategy.name}: {e}")
            return self._generate_mock_performance()
    
    def _simulate_trades(self, strategy: TradingStrategy, data: pd.DataFrame) -> pd.DataFrame:
        """Simplified trade simulation based on strategy rules"""
        trades = []
        
        # Calculate technical indicators
        data['RSI'] = self._calculate_rsi(data['Close'])
        data['MA_50'] = data['Close'].rolling(window=50).mean()
        data['MA_200'] = data['Close'].rolling(window=200).mean()
        data['BB_Upper'], data['BB_Lower'] = self._calculate_bollinger_bands(data['Close'])
        
        # Generate random trades based on strategy type
        np.random.seed(42)  # For reproducible results
        
        if "RSI" in strategy.name:
            trade_signals = data['RSI'] < 30
        elif "Moving Average" in strategy.name:
            trade_signals = data['MA_50'] > data['MA_200']
        elif "Bollinger" in strategy.name:
            trade_signals = data['Close'] <= data['BB_Lower']
        else:
            trade_signals = pd.Series([False] * len(data), index=data.index)
        
        # Generate trades from signals
        for i, (date, signal) in enumerate(trade_signals.items()):
            if signal and np.random.random() > 0.7:  # 30% of signals become trades
                entry_price = data.loc[date, 'Close']
                
                # Random exit after 1-10 days
                exit_days = np.random.randint(1, 11)
                exit_date = date + timedelta(days=exit_days)
                
                if exit_date <= data.index[-1]:
                    exit_price = data.loc[data.index >= exit_date, 'Close'].iloc[0]
                    pnl = (exit_price - entry_price) / entry_price
                    
                    trades.append({
                        'entry_date': date,
                        'exit_date': exit_date,
                        'entry_price': entry_price,
                        'exit_price': exit_price,
                        'pnl': pnl
                    })
        
        return pd.DataFrame(trades)
    
    def _calculate_rsi(self, prices: pd.Series, period: int = 14) -> pd.Series:
        """Calculate RSI indicator"""
        delta = prices.diff()
        gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
        loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
        rs = gain / loss
        return 100 - (100 / (1 + rs))
    
    def _calculate_bollinger_bands(self, prices: pd.Series, 
                                 period: int = 20, std_dev: int = 2) -> tuple:
        """Calculate Bollinger Bands"""
        sma = prices.rolling(window=period).mean()
        std = prices.rolling(window=period).std()
        upper_band = sma + (std * std_dev)
        lower_band = sma - (std * std_dev)
        return upper_band, lower_band
    
    def _calculate_equity_curve(self, trades: pd.DataFrame, 
                              initial_capital: float = 100000) -> pd.Series:
        """Calculate equity curve from trades"""
        if len(trades) == 0:
            return pd.Series([initial_capital])
        
        trades = trades.sort_values('entry_date')
        equity = [initial_capital]
        current_equity = initial_capital
        
        for _, trade in trades.iterrows():
            trade_return = trade['pnl']
            current_equity *= (1 + trade_return)
            equity.append(current_equity)
        
        return pd.Series(equity)
    
    def _generate_mock_performance(self) -> Dict[str, Any]:
        """Generate mock performance data for demonstration"""
        mock_trades = pd.DataFrame({
            'entry_date': pd.date_range(start='2024-01-01', periods=10, freq='30D'),
            'exit_date': pd.date_range(start='2024-01-31', periods=10, freq='30D'),
            'entry_price': np.random.uniform(100, 200, 10),
            'exit_price': np.random.uniform(95, 210, 10),
            'pnl': np.random.uniform(-0.05, 0.08, 10)
        })
        
        mock_equity = pd.Series(np.random.uniform(95000, 115000, 100))
        
        return {
            'trades': mock_trades,
            'equity_curve': mock_equity,
            'performance': {
                'total_return': 12.5,
                'sharpe_ratio': 1.2,
                'max_drawdown': -8.3,
                'win_rate': 65.0,
                'profit_factor': 1.4,
                'total_trades': 10,
                'avg_trade_return': 0.025
            }
        }
    
    def run_complete_analysis(self) -> List[Dict[str, Any]]:
        """Run complete strategy screening and ranking"""
        print("Starting trading strategy analysis...")
        
        # Add sample strategies
        self.add_sample_strategies()
        
        # Simulate performance for each strategy
        strategies = self.strategy_repo.get_strategies()
        
        for strategy in strategies:
            print(f"Analyzing {strategy.name}...")
            
            # Simulate performance
            simulation_result = self.simulate_strategy_performance(strategy)
            self.performance_data[strategy.name] = simulation_result['performance']
        
        # Rank strategies using AI and performance metrics
        print("Ranking strategies with AI analysis...")
        ranked_results = self.ai_analyzer.rank_strategies(strategies, self.performance_data)
        
        return ranked_results
    
    def generate_screening_report(self, ranked_results: List[Dict[str, Any]]) -> str:
        """Generate comprehensive screening report"""
        report = "# Trading Strategy Screening Report\n\n"
        
        for i, result in enumerate(ranked_results, 1):
            strategy = result['strategy']
            performance = result['performance']
            ai_analysis = result['ai_analysis']
            score = result['composite_score']
            
            report += f"## {i}. {strategy.name} (Score: {score:.2f})\n\n"
            report += f"**Description:** {strategy.description}\n\n"
            
            report += "### Performance Metrics\n"
            report += f"- Total Return: {performance.get('total_return', 0):.1f}%\n"
            report += f"- Sharpe Ratio: {performance.get('sharpe_ratio', 0):.2f}\n"
            report += f"- Max Drawdown: {performance.get('max_drawdown', 0):.1f}%\n"
            report += f"- Win Rate: {performance.get('win_rate', 0):.1f}%\n"
            report += f"- Profit Factor: {performance.get('profit_factor', 0):.2f}\n\n"
            
            report += "### AI Analysis\n"
            report += f"- Complexity Score: {ai_analysis.get('complexity_score', 'N/A')}/10\n"
            report += f"- Risk Level: {ai_analysis.get('risk_level', 'Unknown')}\n"
            report += f"- Market Suitability: {ai_analysis.get('market_suitability', 'General')}\n\n"
            
            if 'improvements' in ai_analysis:
                report += "### Suggested Improvements\n"
                for improvement in ai_analysis['improvements']:
                    report += f"- {improvement}\n"
                report += "\n"
            
            report += "---\n\n"
        
        return report

Running Your Trading Strategy Screener

Complete Implementation Example

def main():
    """Main function to run the trading strategy screener"""
    print("Initializing Trading Strategy Screener with Ollama...")
    
    # Initialize screener
    screener = TradingStrategyScreener(model_name="llama2:13b")
    
    # Run complete analysis
    ranked_results = screener.run_complete_analysis()
    
    # Generate and display report
    report = screener.generate_screening_report(ranked_results)
    
    # Save report to file
    with open("strategy_screening_report.md", "w") as f:
        f.write(report)
    
    print("\n" + "="*50)
    print("STRATEGY SCREENING RESULTS")
    print("="*50)
    
    for i, result in enumerate(ranked_results[:3], 1):  # Top 3 strategies
        strategy = result['strategy']
        score = result['composite_score']
        performance = result['performance']
        
        print(f"\n{i}. {strategy.name}")
        print(f"   Score: {score:.2f}")
        print(f"   Return: {performance.get('total_return', 0):.1f}%")
        print(f"   Sharpe: {performance.get('sharpe_ratio', 0):.2f}")
        print(f"   Max DD: {performance.get('max_drawdown', 0):.1f}%")
    
    print(f"\nDetailed report saved to: strategy_screening_report.md")

if __name__ == "__main__":
    main()

Advanced Features and Optimizations

Real-Time Strategy Monitoring

Add real-time monitoring capabilities for live strategy performance:

class RealTimeMonitor:
    """Monitor strategy performance in real-time"""
    
    def __init__(self, screener: TradingStrategyScreener):
        self.screener = screener
        self.monitoring_active = False
    
    def start_monitoring(self, strategies: List[str], interval: int = 300):
        """Start real-time monitoring of selected strategies"""
        self.monitoring_active = True
        
        while self.monitoring_active:
            print(f"Monitoring update: {datetime.now()}")
            
            for strategy_name in strategies:
                strategy = self.screener.strategy_repo.find_by_name(strategy_name)
                if strategy:
                    # Simulate current performance
                    current_perf = self.screener.simulate_strategy_performance(
                        strategy, days=30
                    )
                    
                    print(f"{strategy_name}: {current_perf['performance']['total_return']:.1f}%")
            
            time.sleep(interval)  # Wait for next update
    
    def stop_monitoring(self):
        """Stop real-time monitoring"""
        self.monitoring_active = False

Strategy Performance Visualization

Create visualization tools for better strategy analysis:

import matplotlib.pyplot as plt
import seaborn as sns

class StrategyVisualizer:
    """Visualize strategy performance and comparisons"""
    
    @staticmethod
    def plot_performance_comparison(ranked_results: List[Dict[str, Any]]):
        """Create performance comparison charts"""
        # Extract data for plotting
        strategy_names = [result['strategy'].name for result in ranked_results[:5]]
        returns = [result['performance'].get('total_return', 0) for result in ranked_results[:5]]
        sharpe_ratios = [result['performance'].get('sharpe_ratio', 0) for result in ranked_results[:5]]
        
        # Create subplots
        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))
        
        # Returns comparison
        ax1.bar(strategy_names, returns, color='steelblue', alpha=0.7)
        ax1.set_title('Strategy Returns Comparison')
        ax1.set_ylabel('Total Return (%)')
        ax1.tick_params(axis='x', rotation=45)
        
        # Sharpe ratio comparison
        ax2.bar(strategy_names, sharpe_ratios, color='forestgreen', alpha=0.7)
        ax2.set_title('Strategy Sharpe Ratio Comparison')
        ax2.set_ylabel('Sharpe Ratio')
        ax2.tick_params(axis='x', rotation=45)
        
        plt.tight_layout()
        plt.savefig('strategy_comparison.png', dpi=300, bbox_inches='tight')
        plt.show()
    
    @staticmethod
    def plot_composite_scores(ranked_results: List[Dict[str, Any]]):
        """Plot composite scores for all strategies"""
        strategy_names = [result['strategy'].name for result in ranked_results]
        scores = [result['composite_score'] for result in ranked_results]
        
        plt.figure(figsize=(12, 6))
        bars = plt.bar(strategy_names, scores, color='coral', alpha=0.7)
        
        # Add score labels on bars
        for bar, score in zip(bars, scores):
            plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.01,
                    f'{score:.2f}', ha='center', va='bottom')
        
        plt.title('Trading Strategy Composite Scores')
        plt.ylabel('Composite Score')
        plt.xlabel('Strategy')
        plt.xticks(rotation=45)
        plt.grid(axis='y', alpha=0.3)
        
        plt.tight_layout()
        plt.savefig('composite_scores.png', dpi=300, bbox_inches='tight')
        plt.show()

Deployment and Production Considerations

Docker Configuration

Create a Docker setup for easy deployment:

# Dockerfile
FROM python:3.9-slim

# Install system dependencies
RUN apt-get update && apt-get install -y \
    curl \
    && rm -rf /var/lib/apt/lists/*

# Install Ollama
RUN curl -fsSL https://ollama.ai/install.sh | sh

# Set working directory
WORKDIR /app

# Copy requirements
COPY requirements.txt .
RUN pip install -r requirements.txt

# Copy application code
COPY . .

# Expose port
EXPOSE 8000

# Start services
CMD ["python", "main.py"]

Production Optimization Tips

  1. Model Selection: Use smaller Ollama models (7B parameters) for faster inference in production
  2. Caching: Implement Redis caching for frequently accessed strategy analysis
  3. Database Integration: Store strategies and performance data in PostgreSQL or MongoDB
  4. API Development: Create REST API endpoints using FastAPI for web integration
  5. Monitoring: Implement logging and monitoring using tools like Prometheus and Grafana

Security Considerations

  • Never expose API keys in code
  • Use environment variables for configuration
  • Implement rate limiting for API endpoints
  • Validate all user inputs thoroughly
  • Use HTTPS for all communications

Performance Optimization Strategies

Memory Management

class OptimizedScreener(TradingStrategyScreener):
    """Memory-optimized version of the screener"""
    
    def __init__(self, model_name: str = "llama2:7b", max_cache_size: int = 100):
        super().__init__(model_name)
        self.analysis_cache = {}
        self.max_cache_size = max_cache_size
    
    def cached_ai_analysis(self, strategy: TradingStrategy) -> Dict[str, Any]:
        """Cache AI analysis results to reduce processing time"""
        cache_key = f"{strategy.name}_{hash(str(strategy.to_dict()))}"
        
        if cache_key in self.analysis_cache:
            return self.analysis_cache[cache_key]
        
        # Perform AI analysis
        analysis = self.ai_analyzer.analyze_strategy_logic(strategy)
        
        # Manage cache size
        if len(self.analysis_cache) >= self.max_cache_size:
            # Remove oldest entry
            oldest_key = next(iter(self.analysis_cache))
            del self.analysis_cache[oldest_key]
        
        self.analysis_cache[cache_key] = analysis
        return analysis

Parallel Processing

import concurrent.futures
from functools import partial

class ParallelScreener(TradingStrategyScreener):
    """Multi-threaded version for faster processing"""
    
    def parallel_performance_analysis(self, max_workers: int = 4) -> Dict[str, Any]:
        """Run performance analysis in parallel"""
        strategies = self.strategy_repo.get_strategies()
        
        # Create partial function for parallel execution
        simulate_func = partial(self.simulate_strategy_performance)
        
        # Execute in parallel
        with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
            future_to_strategy = {
                executor.submit(simulate_func, strategy): strategy.name 
                for strategy in strategies
            }
            
            results = {}
            for future in concurrent.futures.as_completed(future_to_strategy):
                strategy_name = future_to_strategy[future]
                try:
                    result = future.result()
                    results[strategy_name] = result['performance']
                except Exception as e:
                    print(f"Strategy {strategy_name} failed: {e}")
                    results[strategy_name] = self._generate_mock_performance()['performance']
        
        return results

Troubleshooting Common Issues

Ollama Connection Problems

def verify_ollama_connection(model_name: str = "llama2:13b") -> bool:
    """Verify Ollama is running and model is available"""
    try:
        client = ollama.Client()
        response = client.generate(
            model=model_name,
            prompt="Test connection"
        )
        print("✓ Ollama connection successful")
        return True
    except Exception as e:
        print(f"✗ Ollama connection failed: {e}")
        print("Troubleshooting steps:")
        print("1. Ensure Ollama is installed: curl -fsSL https://ollama.ai/install.sh | sh")
        print(f"2. Pull required model: ollama pull {model_name}")
        print("3. Start Ollama service: ollama serve")
        return False

# Add to main function
if __name__ == "__main__":
    if verify_ollama_connection():
        main()
    else:
        print("Please fix Ollama setup before continuing.")

Memory Issues

def check_system_resources():
    """Check if system has sufficient resources"""
    import psutil
    
    # Check RAM
    memory = psutil.virtual_memory()
    available_gb = memory.available / (1024**3)
    
    if available_gb < 4:
        print(f"⚠️  Low memory warning: {available_gb:.1f}GB available")
        print("Consider using a smaller Ollama model (7B instead of 13B)")
    
    # Check disk space
    disk = psutil.disk_usage('/')
    available_disk_gb = disk.free / (1024**3)
    
    if available_disk_gb < 10:
        print(f"⚠️  Low disk space: {available_disk_gb:.1f}GB available")
    
    print(f"✓ System check complete: {available_gb:.1f}GB RAM, {available_disk_gb:.1f}GB disk")

Conclusion

Building a trading strategy screener with Ollama provides powerful local AI capabilities for strategy analysis and ranking. This system combines traditional performance metrics with intelligent AI insights to identify the most promising trading strategies.

The key benefits include:

  • Complete privacy with local AI processing
  • Customizable ranking algorithms tailored to your criteria
  • Comprehensive performance analysis using multiple metrics
  • Scalable architecture for production deployment

Your trading strategy screener with Ollama performance ranking system is now ready for testing and refinement. Start with the sample strategies and gradually add your own trading logic for more sophisticated analysis.

For advanced implementations, consider integrating real-time data feeds, implementing machine learning for pattern recognition, and building web interfaces for easier strategy management.

Trading Strategy Performance Comparison ChartTrading Strategy Screener - Deployment Architecture Diagram

Remember to thoroughly backtest any strategies before live trading and always consider risk management as your top priority in algorithmic trading systems.