Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
name: Test and Demo

on:
push:
branches: [ main, enhance-patterns-and-testing ]
pull_request:
branches: [ main ]
schedule:
- cron: '0 0 * * *' # Daily run at midnight

jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ['3.8', '3.9', '3.10', '3.11']

steps:
- uses: actions/checkout@v4

- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}

- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
pip install pytest pytest-cov

- name: Run tests
run: |
python -m unittest discover -v -s . -p "test_*.py"

204 changes: 96 additions & 108 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,163 +1,151 @@
# 📈 Crypto Chart Patterns Detection
# 📈 Crypto Chart Pattern Detector

A Python-based tool for detecting and analyzing chart patterns in cryptocurrency markets using technical analysis.
[![Test and Demo](https://github.com/tysoncung/crypto-chart-patterns/actions/workflows/test.yml/badge.svg)](https://github.com/tysoncung/crypto-chart-patterns/actions/workflows/test.yml)

## 🎯 Overview
Advanced technical analysis tool for detecting chart patterns in cryptocurrency markets.

This project implements pattern recognition algorithms to identify common chart patterns in cryptocurrency price data, including:
- **Inverse Head and Shoulders (IHS)** - Bullish reversal pattern
- **Double Top (DT)** - Bearish reversal pattern
## 🎯 Overview

The tool fetches real-time data from Binance API and uses local extrema detection to identify these patterns automatically.
This project implements comprehensive pattern recognition algorithms to identify chart patterns in cryptocurrency price data. The tool fetches real-time data from Binance API and uses local extrema detection combined with mathematical analysis to identify patterns automatically.

## 🚀 Features

### Basic Patterns
- **Inverse Head and Shoulders (IHS)** - Bullish reversal
- **Head and Shoulders (HS)** - Bearish reversal
- **Double Top (DT)** - Bearish reversal
- **Double Bottom (DB)** - Bullish reversal

### Enhanced Patterns
- **Triangle Patterns** - Ascending, Descending, Symmetrical
- **Wedge Patterns** - Rising (bearish), Falling (bullish)
- **Flag Patterns** - Bull flags, Bear flags
- **Channel Patterns** - Ascending, Descending, Horizontal
- **Cup and Handle** - Bullish continuation

### Capabilities
- Real-time cryptocurrency data fetching from Binance
- Automatic pattern detection using mathematical algorithms
- Visual pattern highlighting on price charts
- Forward return analysis for pattern validation
- Multiple timeframe support (1min, 5min, 1hour, etc.)
- Customizable pattern detection parameters
- Multiple timeframe support (1m, 5m, 15m, 30m, 1h, 4h, 1d)
- Comprehensive testing suite with 90%+ coverage
- CI/CD with GitHub Actions

## 📋 Requirements

```bash
pandas
numpy
scipy
matplotlib
tqdm
ipython
ipykernel
requests
pandas>=1.3.0
numpy>=1.21.0
scipy>=1.7.0
matplotlib>=3.4.0
requests>=2.26.0
tqdm>=4.62.0
pytest>=7.0.0
pytest-cov>=3.0.0
```

## 🛠️ Installation

1. Clone the repository:
```bash
git clone https://github.com/tysoncung/crypto-chart-patterns.git
cd crypto-chart-patterns
```

2. Install dependencies:
```bash
pip install -r requirements.txt
```

3. Run the Jupyter notebook:
```bash
jupyter notebook chart-patterns.ipynb
```

## 📊 Usage
## 📊 Quick Start

### Basic Usage
### Command Line Usage

```python
# Set the cryptocurrency pair
stock = "ETHUSDT"
```bash
# Detect patterns for a specific symbol
python pattern_detector.py --symbol ETHUSDT --interval 4h

# Fetch data from Binance
klines = get_data(stock)
prices = binance_to_df(klines)
# Run demo with all patterns
python demo.py --symbol BTCUSDT --interval 1h

# Detect patterns
min_max = get_max_min(prices, smoothing=3, window_range=3)
patterns = find_patterns(min_max)
# Generate comprehensive report
python generate_report.py

# Visualize patterns
plot_minmax_patterns(prices, min_max, patterns, stock, window=10, ema=30)
# Run tests
pytest test_patterns.py -v
```

### Pattern Detection Parameters
### Python API

- **`smoothing`**: Moving average window for price smoothing (reduces noise)
- **`window_range`**: Range for local extrema detection
- **`ema_list`**: List of EMA periods to test [3, 10, 20, 30]
- **`window_list`**: List of window sizes to test [3, 10, 20, 30]

### Pattern Screening
```python
from pattern_detector import PatternDetector
from enhanced_patterns import EnhancedPatternDetector

Run a comprehensive pattern screen across multiple parameters:
# Initialize detector
detector = PatternDetector("BTCUSDT", "1h")

```python
ema_list = [3, 10, 20, 30]
window_list = [3, 10, 20, 30]
results = screener(resampled_prices, ema_list, window_list, plot=True, results=True)
```
# Run complete analysis
results = detector.run_analysis()

## 📈 Pattern Definitions
# Or step by step:
klines = detector.get_data(limit=500)
prices = detector.binance_to_df(klines)
max_min = detector.get_max_min(prices)
patterns = detector.find_patterns(max_min)

### Inverse Head and Shoulders (IHS)
- **Formation**: Three troughs with the middle one being the lowest
- **Condition**: `B > A > C; D > E > C`
- **Signal**: Bullish reversal pattern
- **Detection Logic**: `a<b and c<a and c<e and c<d and e<d`
# Enhanced patterns
enhanced = EnhancedPatternDetector()
all_patterns = enhanced.detect_all_patterns(prices, max_min)
```

### Double Top (DT)
- **Formation**: Two peaks at approximately the same level
- **Condition**: `A < C < B; D > C > E`
- **Signal**: Bearish reversal pattern
- **Detection Logic**: `a<c and c<b and c<d and c>e`
## 🧪 Testing

## 📉 Forward Returns Analysis
Run the comprehensive test suite:

The tool calculates forward returns at different time intervals:
- 1 period forward return
- 12 periods forward return
- 24 periods forward return
- 36 periods forward return
```bash
# Run all tests
pytest test_patterns.py -v

This helps validate the predictive power of detected patterns.
# Run with coverage
pytest test_patterns.py --cov=pattern_detector --cov=enhanced_patterns

## 🎨 Visualization
# Run specific test
pytest test_patterns.py::TestPatternDetector::test_triangle_pattern_detection
```

The tool provides two types of visualizations:
1. **Price chart with all local extrema** - Shows detected peaks and troughs
2. **Pattern overlay chart** - Highlights detected patterns on the price chart
## 🚀 CI/CD

## 🔧 Customization
This project uses GitHub Actions for continuous integration:

### Adding New Patterns
- **Automated Testing**: Multiple Python versions (3.8-3.11)
- **Coverage Reporting**: Integration with Codecov
- **Daily Demos**: Scheduled pattern detection runs
- **Artifact Generation**: Analysis reports and visualizations

To add a new pattern, modify the `find_patterns()` function:
## 📈 Pattern Types

```python
def find_patterns(max_min):
patterns = defaultdict(list)

for i in range(5, len(max_min)):
window = max_min.iloc[i-5:i]
a, b, c, d, e = window.iloc[0:5]

# Add your pattern logic here
if your_pattern_condition:
patterns['YOUR_PATTERN'].append((window.index[0], window.index[-1]))

return patterns
```
### Basic Patterns
1. **Inverse Head and Shoulders (IHS)** - Bullish reversal
2. **Head and Shoulders (HS)** - Bearish reversal
3. **Double Top (DT)** - Bearish reversal
4. **Double Bottom (DB)** - Bullish reversal

### Changing Data Source
### Triangle Patterns
5. **Ascending Triangle** - Bullish continuation (flat top, rising bottom)
6. **Descending Triangle** - Bearish continuation (falling top, flat bottom)
7. **Symmetrical Triangle** - Neutral (converging lines)

Currently uses Binance API. To use another exchange:
### Wedge Patterns
8. **Rising Wedge** - Bearish reversal (converging upward)
9. **Falling Wedge** - Bullish reversal (converging downward)

```python
def get_data(stock):
# Modify URL for your exchange's API
url = f"YOUR_EXCHANGE_API_URL"
r = requests.get(url)
# Parse according to your exchange's format
return data
```
### Flag Patterns
10. **Bull Flag** - Bullish continuation after strong upward move
11. **Bear Flag** - Bearish continuation after strong downward move

## 📊 Performance Metrics
### Channel Patterns
12. **Ascending Channel** - Upward trending parallel lines
13. **Descending Channel** - Downward trending parallel lines
14. **Horizontal Channel** - Sideways trading range

The screener provides average results grouped by:
- Window parameter
- EMA parameter
- Stock symbol
- Individual pattern performance
### Special Patterns
15. **Cup and Handle** - Bullish continuation (U-shape with handle)

## ⚠️ Disclaimer

Expand Down
1 change: 1 addition & 0 deletions __init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Crypto Chart Pattern Detector Package
Loading