A sophisticated Python-based trading price simulator that generates realistic market price movements with guaranteed convergence to target closing prices. Built with security-first principles and production-ready error handling.
This simulator creates realistic price movements within defined market bounds, converging precisely on a known closing price after 60 seconds. It's designed for:
- Testing trading algorithms with realistic price data
- Backtesting strategies with controlled market conditions
- Educational purposes for understanding price dynamics
- Development environments requiring consistent test data
- Validates all JSON structure and data types
- Enforces market logic constraints (high β₯ low, open/close within bounds)
- Sanitizes filenames to prevent path traversal attacks
- Uses allow-list validation for interval types
- Enforces price bounds throughout simulation
- Implements convergence algorithm with controlled randomness
- Uses normal distribution to prevent extreme outliers
- Provides precise timing control for consistent intervals
finance/
βββ faketrading.py # Main simulator engine
βββ data.json # Market data input
βββ test_faketrading.py # Comprehensive test suite
βββ setup.py # Setup and validation script
βββ Makefile # Development automation
βββ requirements.txt # Dependencies (standard library only)
βββ config.py # Configuration management
βββ config_template.py # Configuration template
βββ QUICKSTART.md # Quick start guide
βββ architecture.mmd # Architecture diagram source
βββ architecture.svg # Architecture visualization
βββ output/ # Output directory
βββ simulation_results.json # Generated simulation data
βββ README.MD # This documentation
faketrading.py # Main simulator engine
βββ PriceSimulator # Core simulation class
βββ load_market_data() # JSON validation & loading
βββ generate_price() # Convergence algorithm
βββ run_simulation() # 60-second execution loop
βββ export_results() # Structured output
{
"open": 154.12,
"high": 154.89,
"low": 153.95,
"close": 154.71
}
{
"simulation_metadata": {
"volatility": 0.5,
"data_file": "data.json",
"market_data": {...},
"total_records": 60
},
"price_data": [
{
"timestamp": "2023-10-05 09:30:00",
"interval": "1_SECOND",
"price": 154.12
}
]
}
- Python 3.7+
- No external dependencies (uses standard library only)
# Clone or download the project
git clone <repository-url>
cd finance
# Run setup validation
python setup.py
# Or use make for quick validation
make validate
# Basic run
python faketrading.py
# Using make
make run
# With custom configuration
python faketrading.py
# In faketrading.py main() function
volatility = 0.5 # Controls price movement randomness
data_file = "data.json" # Market data source
python faketrading.py
from faketrading import PriceSimulator
# Create simulator with custom parameters
simulator = PriceSimulator(
volatility=0.3, # Lower volatility
data_file="custom_data.json"
)
# Run simulation
results = simulator.run_simulation()
# Export results
simulator.export_results("custom_results.json")
The simulator provides real-time console output:
[2023-10-05 09:30:00] [1_SECOND] Price: $154.12
[2023-10-05 09:30:05] [5_SECOND] Price: $154.45
[2023-10-05 09:31:00] [1_MINUTE] Price: $154.71
# Run all tests
python test_faketrading.py
# Using make
make test
# With coverage
make test-cov
# Lint code
make lint
# Format code
make format
# Type checking
make typecheck
# Security checks
make security
# Install development dependencies
make install-dev
# Validate everything
make validate
The simulator uses a weighted convergence approach:
- Convergence Weight: Increases over time (0 β 0.9)
- Target Bias: Stronger bias toward close price as simulation progresses
- Random Component: Normal distribution with decreasing volatility
- Bounds Enforcement: Ensures prices stay within high/low range
- Precise 1-second intervals using
time.sleep()
- Synchronized timestamps for consistent data
- Graceful interruption handling with
KeyboardInterrupt
1_SECOND
: Every second5_SECOND
: Every 5 seconds1_MINUTE
: At minute end5_MINUTE
: At start (for 1-minute simulations)1_HOUR
: At start (for 1-minute simulations)
# Test market data validation
def test_market_data_validation():
# Test high < low constraint
# Test open/close within bounds
# Test required keys presence
pass
# Test convergence algorithm
def test_price_convergence():
# Verify final price equals target close
# Check price bounds throughout simulation
pass
# Test JSON injection prevention
def test_json_injection():
# Test malformed JSON handling
# Test missing required keys
pass
# Test path traversal prevention
def test_filename_sanitization():
# Test ../ path traversal attempts
# Test absolute path handling
pass
- OS: Cross-platform (Windows, macOS, Linux)
- Python: 3.7 or higher
- Memory: Minimal (< 10MB)
- Storage: < 1MB for code and data
json
- JSON parsing and validationtime
- Timing control and sleeprandom
- Price movement generationlogging
- Structured loggingdatetime
- Timestamp managementpathlib
- File path handlingsys
- System exit handling
pytest
- Testing frameworkpytest-cov
- Coverage reportingblack
- Code formattingflake8
- Lintingmypy
- Type checking
# Ensure data.json exists in project directory
ls -la data.json
# Run setup validation
python setup.py
// Fix data.json structure
{
"open": 154.12,
"high": 154.89, // Must be >= low
"low": 153.95,
"close": 154.71 // Must be within high-low range
}
- Check system clock accuracy
- Ensure no heavy background processes
- Verify Python version compatibility
# Enable debug logging
logging.basicConfig(level=logging.DEBUG)
PriceSimulator(volatility: float = 0.5, data_file: str = "data.json")
load_market_data() -> Dict[str, float]
: Load and validate market datagenerate_price(second: int, total_seconds: int = 60) -> float
: Generate next pricerun_simulation() -> List[Dict[str, Any]]
: Execute 60-second simulationexport_results(filename: str = "simulation_results.json") -> None
: Export results
- Input Validation: Always validate external inputs
- Bounds Checking: Enforce logical constraints
- Error Handling: Provide meaningful error messages
- Logging: Use structured logging for debugging
- Follow PEP 8 conventions
- Include type hints
- Add security annotations (
SECURITY:
,SAFETY:
) - Document all public methods
# 1. Make changes
# 2. Run tests
make test
# 3. Check code quality
make lint
make typecheck
# 4. Format code
make format
# 5. Validate everything
make validate
This project is provided as-is for educational and development purposes. Use at your own risk in production environments.
This is a simulation tool, not real trading software. The generated data is for testing and educational purposes only. Do not use for actual trading decisions.
- Quick Start Guide - Get up and running quickly
- Architecture Diagram - Visual system overview
- Test Suite - Comprehensive test coverage
- Configuration - Configuration management
Built with security-first principles and production-ready error handling.