Building Financial Market Simulators with Mimesis

Building Financial Market Simulators with Mimesis

Financial applications require realistic market data for development, testing, and demonstration purposes. Having easy access to synthetic but realistic financial data is essential for tasks ranging from portfolio analysis to algorithmic trading development. Mimesis’s Finance API provides a powerful solution for creating structured, realistic financial data that mirrors real-world market patterns.

In this article, we’ll explore how to leverage Mimesis to generate two essential types of financial data: diversified stock portfolios and cryptocurrency trading histories. More importantly, we’ll discuss how these data generators can serve as building blocks for more sophisticated financial applications and analysis.

Building a Stock Portfolio Generator

A portfolio generator that creates realistic investment portfolios with multiple stocks, prices, and allocations enables developers and analysts to test portfolio management algorithms, develop visualization tools, create demo environments, and simulate different investment strategies. Here’s how we can build a flexible portfolio generator using Mimesis:

 
from mimesis import Field, Schema
from mimesis.locales import Locale
import random

# Set seed for reproducibility
random.seed(42)
field = Field(locale=Locale.EN, seed=42)

def portfolio_schema():
    stock_count = random.randint(5, 10)
    total_investment = 100000  # $100k portfolio
    
    # Generate list of stocks
    stocks = []
    remaining_allocation = 100
    
    for _ in range(stock*count):
        allocation = random.randint(5, remaining_allocation - (stock_count - len(stocks) - 1) * 5)
        if len(stocks) == stock_count - 1:
            allocation = remaining_allocation
            
        stock = {
            'ticker': field('finance.stock_ticker'),
            'company': field('finance.company'),
            'price': field('finance.price', minimum=10, maximum=500),
            'allocation_percentage': allocation,
            'exchange': field('finance.stock_exchange')
        }
        stocks.append(stock)
        remaining_allocation -= allocation
    
    return {
        'portfolio_id': field('random.randint', a=10000, b=99999),
        'total_value': total_investment,
        'stocks': stocks,
        'currency': field('finance.currency_iso_code'),
        'last_updated': field('datetime.datetime')
    }

# Generate a single portfolio
schema = Schema(schema=portfolio_schema)
portfolio = schema.create()[0]

# Print the result
print("Generated Portfolio:")
print(f"Portfolio ID: {portfolio['portfolio_id']}")
print(f"Total Value: ${portfolio['total_value']:,}")
print(f"Currency: {portfolio['currency']}")
print(f"Last Updated: {portfolio['last_updated']}\n")
print("Stock Allocations:")

for stock in portfolio['stocks']:
    print(f"- {stock['ticker']} ({stock['company']}):")
    print(f"  Price: ${stock['price']:.2f}")
    print(f"  Allocation: {stock['allocation_percentage']}%")
    print(f"  Exchange: {stock['exchange']}\n")

Let’s break down the key components of this generator:

1. Portfolio Structure: The generator creates a portfolio with a random number of stocks (5-10), each with its own ticker symbol, company name, price, and allocation percentage. This flexibility allows for testing various portfolio sizes and compositions.

2. Allocation Logic: The code implements a smart allocation system that ensures:

  • Each stock has a minimum 5% allocation
  • Allocations sum to exactly 100%
  • The distribution is random but reasonable

3. Market Realism: The generator uses Mimesis’s finance providers to create realistic:

  • Stock tickers (field(‘finance.stock_ticker’))
  • Company names (field(‘finance.company’))
  • Stock prices (field(‘finance.price’))
  • Exchange listings (field(‘finance.stock_exchange’))

When we run this generator, it produces detailed portfolio data that looks like this:

 
Generated Portfolio:
Portfolio ID: 93810
Total Value: $100,000
Currency: USD
Last Updated: 2025-01-24 08:15:14.146316

Stock Allocations:
- RAMP (Bradley Pharmaceuticals):
  Price: $22.26
  Allocation: 12%
  Exchange: AMEX

- EFC (Fruit of the Loom):
  Price: $78.37
  Allocation: 6%
  Exchange: NYSE

- SCCI (Wheeling-Pittsburgh Steel):
  Price: $52.60
  Allocation: 22%
  Exchange: JPX

- ALGRR (Alert Alarm Company):
  Price: $55.91
  Allocation: 12%
  Exchange: NASDAQ

- MRLN (AirTran Holdings):
  Price: $285.01
  Allocation: 12%
  Exchange: HKEX

- RF^A (Wheeling-Pittsburgh Steel):
  Price: $215.56
  Allocation: 7%
  Exchange: JPX

- PCQ (Intuit):
  Price: $406.62
  Allocation: 6%
  Exchange: NYSE

- TOL (Deere & Company):
  Price: $352.09
  Allocation: 13%
  Exchange: AMEX

- FATE (DRS Technologies):
  Price: $115.50
  Allocation: 5%
  Exchange: Euronext

- GMHI (BlackRock):
  Price: $55.45
  Allocation: 5%
  Exchange: NYSE

The generated portfolio data enables comprehensive financial analysis and application development. Analysts can calculate portfolio risk metrics like beta and Sharpe ratios, test rebalancing algorithms, and analyze sector diversification. For market simulation, multiple portfolios can be generated to create benchmark portfolios and test optimization strategies. Developers can use this data to build and test portfolio visualization tools, rebalancing applications, and investment education platforms. The structured nature of the data also makes it ideal for testing data processing workflows and validating portfolio reporting systems.

Simulating Cryptocurrency Trading History

Generating realistic cryptocurrency trading data presents unique challenges due to the volatile nature of crypto markets and the need for time-series consistency. This example demonstrates how to create hourly price and volume data that maintains realistic patterns while preserving temporal relationships. Here’s a generator that creates cryptocurrency trading history with appropriate price ranges and consistent price movements:

 
from mimesis import Field
from mimesis.locales import Locale
from datetime import datetime, timedelta
import random

# Set seed for reproducibility
random.seed(42)
field = Field(locale=Locale.EN, seed=42)

def generate_crypto_trading_data(days=5):
    # Typical price ranges for different cryptocurrencies in USD
    crypto_ranges = {
        'BTC': (85000, 120000),
        'ETH': (2000, 3000),
        'DASH': (25, 45),
        'LTC': (50, 80),
        'XRP': (0.45, 0.65)
    }
    
    # Choose one cryptocurrency and its price range
    crypto = random.choice(list(crypto_ranges.keys()))
    min_price, max_price = crypto_ranges[crypto]
    exchange = field('finance.stock_exchange')
    
    # Initial price within the crypto's typical range
    base_price = random.uniform(min_price, max_price)
    volatility = 0.05  # 5% daily volatility
    
    trading_data = []
    start_date = datetime(2024, 1, 1)
    
    for day in range(days):
        current_date = start_date + timedelta(days=day)
        daily_entries = []
        
        # Generate hourly data
        for hour in range(24):
            timestamp = current_date + timedelta(hours=hour)
            price_change = random.uniform(-volatility, volatility)
            price = base_price * (1 + price_change)
            
            entry = {
                'timestamp': timestamp.strftime('%Y-%m-%d %H:00:00'),
                'crypto': crypto,
                'price_usd': round(price, 2),
                'volume': field('random.randint', a=1000, b=10000),
                'exchange': exchange
            }
            daily_entries.append(entry)
        
        # Update base price for next day using last price
        base_price = daily_entries[-1]['price_usd']
        trading_data.extend(daily_entries)
    
    return trading_data

# Generate trading data
trading_history = generate_crypto_trading_data(days=2)  # 2 days of hourly data

# Print first 5 entries
print("Cryptocurrency Trading History (First 5 entries):")
for entry in trading_history[:5]:
    print(f"\nTimestamp: {entry['timestamp']}")
    print(f"Cryptocurrency: {entry['crypto']}")
    print(f"Price USD: ${entry['price_usd']:.2f}")
    print(f"Volume: {entry['volume']}")
    print(f"Exchange: {entry['exchange']}")

Let’s examine the key features of this cryptocurrency data generator:

1. Price Range Management: The generator implements a sophisticated pricing system with:

  • Currency-specific price ranges reflecting real market values
  • Five major cryptocurrencies with distinct price levels
  • Random initial price selection within appropriate ranges
  • Continuous price evolution preserving market dynamics

2. Time Series Consistency: The code ensures temporal coherence through:

  • Single cryptocurrency tracked throughout the dataset
  • Consistent exchange for all transactions
  • Hourly granularity for detailed analysis
  • Price updates that maintain continuity between periods

3. Market Dynamics: The simulation captures key market characteristics:

  • Configurable volatility parameter (set to 5%)
  • Random walk price evolution
  • Varying trading volumes
  • Realistic price movements within currency-specific bounds

When we run this generator, it produces detailed trading history data that looks like this:

 
Cryptocurrency Trading History (First 5 entries):

Timestamp: 2024-01-01 00:00:00
Cryptocurrency: BTC
Price USD: $83943.43
Volume: 2824
Exchange: HKEX

Timestamp: 2024-01-01 01:00:00
Cryptocurrency: BTC
Price USD: $83498.44
Volume: 1409
Exchange: HKEX

Timestamp: 2024-01-01 02:00:00
Cryptocurrency: BTC
Price USD: $87906.08
Volume: 5506
Exchange: HKEX

Timestamp: 2024-01-01 03:00:00
Cryptocurrency: BTC
Price USD: $87392.79
Volume: 5012
Exchange: HKEX

Timestamp: 2024-01-01 04:00:00
Cryptocurrency: BTC
Price USD: $89243.23
Volume: 4657
Exchange: HKEX

The generated cryptocurrency trading data supports numerous analytical and development scenarios. Data scientists can use it to test trading algorithms, analyze price patterns, and develop predictive models. The hourly granularity enables detailed technical analysis, including moving averages, volatility calculations, and volume profile analysis. For developers, this data structure is ideal for building trading interfaces, backtesting systems, and market analysis tools. The consistent format and realistic price movements make it particularly valuable for testing data visualization components and real-time trading system simulations.

Conclusion: Building Sophisticated Financial Simulators

The examples demonstrated in this article serve as fundamental building blocks for creating comprehensive financial market simulators. By combining the portfolio generator and cryptocurrency trading simulator, developers can create sophisticated testing environments that mirror real-world financial markets. These tools can be extended in several ways:

  • Combine both generators to simulate a complete trading environment where portfolios can be rebalanced based on cryptocurrency market movements
  • Add time-based correlation between stock and crypto markets to simulate market-wide trends
  • Incorporate additional Mimesis finance providers to generate related data like forex rates or commodity prices
  • Extend the generators with custom providers for specific financial instruments or market behaviors

The reproducibility provided by Mimesis’s seeding system ensures consistent simulation results across different testing scenarios. The combination of structured data generation and realistic market patterns makes these generators powerful building blocks for market analysis and testing. By leveraging these tools, developers can create robust testing environments that accurately reflect real-world market behaviors and interactions.

Leave a Reply

Your email address will not be published. Required fields are marked *