Skip to content

Commit d87504d

Browse files
committed
Fix repository issues and add comprehensive documentation
- Fixed NameError in Jupyter notebook (missing klines initialization) - Added comprehensive README with usage instructions and examples - Added MIT LICENSE file - Created standalone Python script (pattern_detector.py) for CLI usage - Updated .gitignore with proper Python/Jupyter patterns - Added support for more chart patterns (Double Bottom, Head & Shoulders) - Improved documentation with pattern definitions and trading signals - Added command-line interface for easier usage - Included forward returns analysis for pattern validation
1 parent 9e9d91e commit d87504d

5 files changed

Lines changed: 573 additions & 39 deletions

File tree

.gitignore

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,47 @@
1-
.ipynb*
1+
# Jupyter Notebook
2+
.ipynb_checkpoints
3+
*/.ipynb_checkpoints/*
4+
5+
# Python
6+
__pycache__/
7+
*.py[cod]
8+
*$py.class
9+
*.so
10+
.Python
11+
env/
12+
venv/
13+
.venv
14+
pip-log.txt
15+
pip-delete-this-directory.txt
16+
17+
# Data files
18+
*.csv
19+
*.xlsx
20+
*.json
21+
data/
22+
23+
# Output files
24+
*.png
25+
*.jpg
26+
*.pdf
27+
plots/
28+
results/
29+
30+
# IDE
31+
.vscode/
32+
.idea/
33+
*.swp
34+
*.swo
35+
36+
# OS files
37+
.DS_Store
38+
Thumbs.db
39+
*~
40+
41+
# Environment
42+
.env
43+
.env.local
44+
45+
# Logs
46+
*.log
47+
logs/

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2024 Tyson Cung
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 194 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,194 @@
1-
# crypto-chart-patterns
1+
# 📈 Crypto Chart Patterns Detection
2+
3+
A Python-based tool for detecting and analyzing chart patterns in cryptocurrency markets using technical analysis.
4+
5+
## 🎯 Overview
6+
7+
This project implements pattern recognition algorithms to identify common chart patterns in cryptocurrency price data, including:
8+
- **Inverse Head and Shoulders (IHS)** - Bullish reversal pattern
9+
- **Double Top (DT)** - Bearish reversal pattern
10+
11+
The tool fetches real-time data from Binance API and uses local extrema detection to identify these patterns automatically.
12+
13+
## 🚀 Features
14+
15+
- Real-time cryptocurrency data fetching from Binance
16+
- Automatic pattern detection using mathematical algorithms
17+
- Visual pattern highlighting on price charts
18+
- Forward return analysis for pattern validation
19+
- Multiple timeframe support (1min, 5min, 1hour, etc.)
20+
- Customizable pattern detection parameters
21+
22+
## 📋 Requirements
23+
24+
```bash
25+
pandas
26+
numpy
27+
scipy
28+
matplotlib
29+
tqdm
30+
ipython
31+
ipykernel
32+
requests
33+
```
34+
35+
## 🛠️ Installation
36+
37+
1. Clone the repository:
38+
```bash
39+
git clone https://github.com/tysoncung/crypto-chart-patterns.git
40+
cd crypto-chart-patterns
41+
```
42+
43+
2. Install dependencies:
44+
```bash
45+
pip install -r requirements.txt
46+
```
47+
48+
3. Run the Jupyter notebook:
49+
```bash
50+
jupyter notebook chart-patterns.ipynb
51+
```
52+
53+
## 📊 Usage
54+
55+
### Basic Usage
56+
57+
```python
58+
# Set the cryptocurrency pair
59+
stock = "ETHUSDT"
60+
61+
# Fetch data from Binance
62+
klines = get_data(stock)
63+
prices = binance_to_df(klines)
64+
65+
# Detect patterns
66+
min_max = get_max_min(prices, smoothing=3, window_range=3)
67+
patterns = find_patterns(min_max)
68+
69+
# Visualize patterns
70+
plot_minmax_patterns(prices, min_max, patterns, stock, window=10, ema=30)
71+
```
72+
73+
### Pattern Detection Parameters
74+
75+
- **`smoothing`**: Moving average window for price smoothing (reduces noise)
76+
- **`window_range`**: Range for local extrema detection
77+
- **`ema_list`**: List of EMA periods to test [3, 10, 20, 30]
78+
- **`window_list`**: List of window sizes to test [3, 10, 20, 30]
79+
80+
### Pattern Screening
81+
82+
Run a comprehensive pattern screen across multiple parameters:
83+
84+
```python
85+
ema_list = [3, 10, 20, 30]
86+
window_list = [3, 10, 20, 30]
87+
results = screener(resampled_prices, ema_list, window_list, plot=True, results=True)
88+
```
89+
90+
## 📈 Pattern Definitions
91+
92+
### Inverse Head and Shoulders (IHS)
93+
- **Formation**: Three troughs with the middle one being the lowest
94+
- **Condition**: `B > A > C; D > E > C`
95+
- **Signal**: Bullish reversal pattern
96+
- **Detection Logic**: `a<b and c<a and c<e and c<d and e<d`
97+
98+
### Double Top (DT)
99+
- **Formation**: Two peaks at approximately the same level
100+
- **Condition**: `A < C < B; D > C > E`
101+
- **Signal**: Bearish reversal pattern
102+
- **Detection Logic**: `a<c and c<b and c<d and c>e`
103+
104+
## 📉 Forward Returns Analysis
105+
106+
The tool calculates forward returns at different time intervals:
107+
- 1 period forward return
108+
- 12 periods forward return
109+
- 24 periods forward return
110+
- 36 periods forward return
111+
112+
This helps validate the predictive power of detected patterns.
113+
114+
## 🎨 Visualization
115+
116+
The tool provides two types of visualizations:
117+
1. **Price chart with all local extrema** - Shows detected peaks and troughs
118+
2. **Pattern overlay chart** - Highlights detected patterns on the price chart
119+
120+
## 🔧 Customization
121+
122+
### Adding New Patterns
123+
124+
To add a new pattern, modify the `find_patterns()` function:
125+
126+
```python
127+
def find_patterns(max_min):
128+
patterns = defaultdict(list)
129+
130+
for i in range(5, len(max_min)):
131+
window = max_min.iloc[i-5:i]
132+
a, b, c, d, e = window.iloc[0:5]
133+
134+
# Add your pattern logic here
135+
if your_pattern_condition:
136+
patterns['YOUR_PATTERN'].append((window.index[0], window.index[-1]))
137+
138+
return patterns
139+
```
140+
141+
### Changing Data Source
142+
143+
Currently uses Binance API. To use another exchange:
144+
145+
```python
146+
def get_data(stock):
147+
# Modify URL for your exchange's API
148+
url = f"YOUR_EXCHANGE_API_URL"
149+
r = requests.get(url)
150+
# Parse according to your exchange's format
151+
return data
152+
```
153+
154+
## 📊 Performance Metrics
155+
156+
The screener provides average results grouped by:
157+
- Window parameter
158+
- EMA parameter
159+
- Stock symbol
160+
- Individual pattern performance
161+
162+
## ⚠️ Disclaimer
163+
164+
This tool is for educational and research purposes only. Cryptocurrency trading involves substantial risk of loss. Past pattern performance does not guarantee future results. Always do your own research and consider consulting with a financial advisor.
165+
166+
## 🤝 Contributing
167+
168+
Contributions are welcome! Please feel free to submit a Pull Request. Areas for improvement:
169+
- Add more chart patterns (Triangle, Flag, Wedge, etc.)
170+
- Implement machine learning for pattern validation
171+
- Add backtesting capabilities
172+
- Support for more exchanges
173+
- Real-time pattern alerts
174+
175+
## 📝 License
176+
177+
MIT License - see LICENSE file for details
178+
179+
## 🔗 Resources
180+
181+
- [Binance API Documentation](https://binance-docs.github.io/apidocs/)
182+
- [Technical Analysis Patterns](https://www.investopedia.com/articles/technical/112601.asp)
183+
- [SciPy Signal Processing](https://docs.scipy.org/doc/scipy/reference/signal.html)
184+
185+
## 👤 Author
186+
187+
**Tyson Cung**
188+
- GitHub: [@tysoncung](https://github.com/tysoncung)
189+
190+
## 🙏 Acknowledgments
191+
192+
- Binance for providing free API access
193+
- The Python scientific computing community
194+
- Technical analysis researchers and practitioners

chart-patterns.ipynb

Lines changed: 3 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -65,43 +65,9 @@
6565
},
6666
{
6767
"cell_type": "code",
68-
"execution_count": 5,
69-
"source": [
70-
"def binance_to_df(klines):\n",
71-
" df = pd.DataFrame(klines.reshape(-1,12),dtype=float, columns = ('t',\n",
72-
" 'o',\n",
73-
" 'h',\n",
74-
" 'l',\n",
75-
" 'c',\n",
76-
" 'v',\n",
77-
" 'Close time',\n",
78-
" 'Quote asset volume',\n",
79-
" 'Number of trades',\n",
80-
" 'Taker buy base asset volume',\n",
81-
" 'Taker buy quote asset volume',\n",
82-
" 'Ignore'))\n",
83-
"\n",
84-
" df['t'] = pd.to_datetime(df['t'], unit='ms')\n",
85-
"\n",
86-
"\n",
87-
" return df\n",
88-
"klines = get_data(stock)\n",
89-
"prices = binance_to_df(klines)\n",
90-
"prices.head()"
91-
],
92-
"outputs": [
93-
{
94-
"output_type": "error",
95-
"ename": "NameError",
96-
"evalue": "name 'klines' is not defined",
97-
"traceback": [
98-
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
99-
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
100-
"\u001b[0;32m/var/folders/4r/mhkg6nz15nv2t85b6l5cc37w0000gn/T/ipykernel_96933/3039148235.py\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m 18\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mdf\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 19\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 20\u001b[0;31m \u001b[0mprices\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mbinance_to_df\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mklines\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 21\u001b[0m \u001b[0mprices\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mhead\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
101-
"\u001b[0;31mNameError\u001b[0m: name 'klines' is not defined"
102-
]
103-
}
104-
],
68+
"execution_count": null,
69+
"source": "def binance_to_df(klines):\n df = pd.DataFrame(klines.reshape(-1,12),dtype=float, columns = ('t',\n 'o',\n 'h',\n 'l',\n 'c',\n 'v',\n 'Close time',\n 'Quote asset volume',\n 'Number of trades',\n 'Taker buy base asset volume',\n 'Taker buy quote asset volume',\n 'Ignore'))\n\n df['t'] = pd.to_datetime(df['t'], unit='ms')\n\n\n return df\n\n# Fetch data first\nklines = get_data(stock)\nprices = binance_to_df(klines)\nprices.head()",
70+
"outputs": [],
10571
"metadata": {}
10672
},
10773
{

0 commit comments

Comments
 (0)