Repository: white07S/TradingPatternScanner Branch: main Commit: 57e5396c4c54 Files: 20 Total size: 60.3 KB Directory structure: gitextract_b1d9ea39/ ├── .github/ │ └── workflows/ │ ├── python-ci.yml │ └── python-publish.yml ├── .gitignore ├── LICENSE.md ├── MANIFEST.in ├── README.md ├── docs/ │ ├── Makefile │ ├── make.bat │ └── source/ │ ├── conf.py │ └── index.rst ├── pyproject.toml ├── requirements.txt ├── tests/ │ ├── __init__.py │ └── test_hs.py ├── tradingpatterns/ │ ├── __init__.py │ ├── analysis.py │ ├── hard_data.py │ ├── tradingpatterns.py │ └── tradingpatterns_tech.py └── update_docs.sh ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/python-ci.yml ================================================ name: Python CI on: push: branches: - main pull_request: branches: - main jobs: build: runs-on: ubuntu-latest strategy: matrix: python-version: [3.7, 3.8, 3.9] steps: - name: Checkout repository uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Run tests run: | python -m unittest discover ================================================ FILE: .github/workflows/python-publish.yml ================================================ name: Upload Python Package to PYPI on: pull_request: branches: main permissions: contents: write pull-requests: write jobs: release-please: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 with: fetch-depth: 0 - uses: actions/setup-python@v4 with: python-version: "3.10" - name: Install poetry run: python -m pip install poetry - name: Update patch version of package id: versionUpdate run: | poetry version patch echo "::set-output version=$(poetry version -s)" - name: Commit and push changes run: | git config --global user.name "GitHub Actions" git config --global user.email "github-actions@users.noreply.github.com" git checkout -b release-${{ steps.versionUpdate.outputs.version }} git add . git commit -m "${{ steps.versionUpdate.outputs.version }} release" git push origin release-${{ steps.versionUpdate.outputs.version }} - name: Create pull request uses: peter-evans/create-pull-request@v3 with: title: Release ${{ steps.versionUpdate.outputs.version }} branch: release-${{ steps.versionUpdate.outputs.version }} base: main - name: Build and upload python package env: username: ${{ secrets.PYPI_USERNAME }} password: ${{ secrets.PYPI_PASSWORD }} run: | poetry publish --build -u ${username} -p ${password}} ================================================ FILE: .gitignore ================================================ *.py[cod] # C extensions *.so # pycharm .idea/ .idea # Packages *.egg *.egg-info build eggs parts bin var sdist develop-eggs .installed.cfg lib lib64 # Installer logs pip-log.txt # Unit test / coverage reports .coverage .tox nosetests.xml # Complexity output/*.html output/*/index.html # Sphinx docs/_build # Cookiecutter output/ # Build dist/ venv/ ================================================ FILE: LICENSE.md ================================================ Copyright (c) 2017, Preetam Sharma All rights reserved. #TradingPatternScanner This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) license. You are free to: - Share: copy and redistribute the material in any medium or format. Under the following terms: - Attribution: You must give appropriate credit, provide a link to the license, and indicate if changes were made. You must do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use. The credit should be given in the following format: "Original work by [Preetam Sharma] is licensed under CC BY-NC-SA 4.0 and can be found at (https://github.com/white07S/TradingPatternScanner)." - NonCommercial: You may not use the material for commercial purposes. This includes but is not limited to, selling the material, or using it to promote a product or service. For more information, see the [Creative Commons website](https://creativecommons.org/licenses/by-nc-sa/4.0/) and the [legal code of the license](https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode). ================================================ FILE: MANIFEST.in ================================================ include README.md include requirements.txt ================================================ FILE: README.md ================================================ # TradingPatternScanner ![Python CI](https://github.com/white07S/TradingPatternScanner/actions/workflows/python-ci.yml/badge.svg) #### Author: Preetam Sharma Overview -------- Trading Pattern Scanner Identifies complex patterns like head and shoulder, wedge and many more. ## New Enhancements Four new features for pattern detection have been added: 1. **Basic Head-Shoulder Detection**: The initial unfiltered version of pattern detection. It uses a rolling window to track high and low points, then identifies Head and Shoulder and Inverse Head and Shoulder patterns. 2. **Head-Shoulder Detection with Savitzky-Golay Filter**: This feature uses the Savitzky-Golay filter to reduce noise and improve pattern detection. It also considers the height of the "Head" or "Inverse Head" to avoid false pattern recognition. 3. **Head-Shoulder Detection with Kalman Filter**: This feature utilizes the Kalman Filter, a recursive filter that estimates the state of a system in real time. It's particularly suitable for financial data due to its inherent noise and uncertainties. 4. **Head-Shoulder Detection with Wavelet Denoising**: This final feature applies wavelet denoising to eliminate noise while preserving key features in the data. It makes pattern detection more robust and reliable, especially in the presence of high-frequency noise. These enhancements provide more accurate pattern detection for your financial analysis needs. ## Analysis Each method has been rigorously tested and analysed on **synthetic data that closely mirrors real-world financial data**. However, it's important to note that synthetic data is not an exact representation of the real-world, and the performance of each algorithm may vary in a live setting. Therefore, users are encouraged to test each algorithm against their own datasets and pick the one that best suits their needs. - Accuracy for head_shoulder_pattern_window: **78.50%** - Accuracy for head_shoulder_pattern_filter: **78.50%** - Accuracy for head_shoulder_pattern_kf: **73.50%** - Accuracy for head_shoulder_pattern_wavelet: **84.50%** ![Analysis](https://github.com/white07S/TradingPatternScanner/blob/main/docs/images/heatmap.png) ## Heatmap Interpretation * For instance, let's consider a cell in the 2nd row and 2nd column. the score is 10, it means that a significant number of instances were correctly identified as "Head and Shoulder" pattern (abbreviated as HS). * On the contrary, a dark cell outside this diagonal indicates a high number of misclassifications. For example, a dark cell at the intersection of "HS" row and "I-HS" column would mean that a large number of instances were true "HS" but were incorrectly predicted as "Inverse Head and Shoulder" (abbreviated as I-HS) by the scanner. ## Abbreviations The abbreviations used in the heatmap and the code are as follows: * **HS** - Head and Shoulder pattern * **I-HS** - Inverse Head and Shoulder pattern Installation / Usage -------------------- Install using pip: $ pip install tradingpattern # TradingPatternScanner # Trading patterns: * **Head and Shoulder and inverse Head and Shoulder**: These patterns indicate a potential reversal in the market, with the "head" being the highest point, and the "shoulders" being the points on either side at a slightly lower level. * **Multiple top and bottom**: These patterns indicate a range-bound market, with multiple highs and lows forming a horizontal range. * **Horizontal support and resistance**: These patterns indicate key levels at which the market has previously struggled to break through. * **Ascending and Descending Triangle pattern**: These patterns indicate a potential breakout in the market, with the upper trendline being resistance and the lower trendline being support. * **Wedge up and down**: These patterns indicate a potential reversal in the market, with the trendlines converging towards each other. * **Channel up and down**: These patterns indicate a strong trend in the market, with price moving within a well-defined upper and lower trendline. * **Double top and bottom**: These patterns indicate a potential reversal in the market, with the market hitting a high or low twice and then reversing. * **Trend line support and resistance**: These patterns indicate key levels at which the market is likely to experience support or resistance based on historical price action. * **Finding Higher-High and Lower-Low** # Designed for fast performance: * **Uses only Pandas as Numpy, no other external libraries**: This approach helps to keep the library lightweight and fast. * **Uses the concept of vectorization**: This approach helps to improve performance by processing large amounts of data at once, rather than iterating over each individual data point. # New and Unique: * **No other python** library exists for such task currently: This library is new and unique, as it aims to provide an all-in-one solution for identifying various trading patterns. ### Lets check if its works for simplicity I used finviz and checked the pattern with the respective stock. * Head and Shoulder: ![Head and Shoulder](https://user-images.githubusercontent.com/58583011/212490681-6dfca525-cd2e-4c87-830a-655ac9294a8a.png) We can see that it finds out that we have inverse head and shoulder pattern in the stock on 9th Januray 2023 in 1 day interval. Lets match with Finviz. ![Finviz](https://user-images.githubusercontent.com/58583011/212490765-220182a5-e637-4f83-9a65-3031b7c99fee.png) * We can see that Finviz also detects on 9th Januray 2023 in 1 day interval. * You can adjust the window size to your liking. A smaller window size will be more sensitive to detecting patterns, but it will also increase the chances of false positives. A larger window size will be less sensitive to detecting patterns, but it will also decrease the chances of false positives. # Future add-ons: * **Request your favourite pattern to get added in the list**: The library is open for suggestions for adding new patterns. * **Work on visualization and plotting**: The library can be extended to include visualization and plotting features to help users better understand the patterns identified. * **Add unit testing**: The library can be extended to include unit testing to ensure that the code is working as expected and to catch any bugs early on. ================================================ FILE: docs/Makefile ================================================ # Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don\'t have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source .PHONY: help help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " applehelp to make an Apple Help Book" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " epub3 to make an epub3" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" @echo " coverage to run coverage check of the documentation (if enabled)" @echo " dummy to check syntax errors of document sources" .PHONY: clean clean: rm -rf $(BUILDDIR)/* .PHONY: html html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." .PHONY: dirhtml dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." .PHONY: singlehtml singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." .PHONY: pickle pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." .PHONY: json json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." .PHONY: htmlhelp htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." .PHONY: qthelp qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/twitterpandas.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/twitterpandas.qhc" .PHONY: applehelp applehelp: $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp @echo @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." @echo "N.B. You won't be able to view it unless you put it in" \ "~/Library/Documentation/Help or install it in your application" \ "bundle." .PHONY: devhelp devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/twitterpandas" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/twitterpandas" @echo "# devhelp" .PHONY: epub epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." .PHONY: epub3 epub3: $(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3 @echo @echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3." .PHONY: latex latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." .PHONY: latexpdf latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." .PHONY: latexpdfja latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." .PHONY: text text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." .PHONY: man man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." .PHONY: texinfo texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." .PHONY: info info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." .PHONY: gettext gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." .PHONY: changes changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." .PHONY: linkcheck linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." .PHONY: doctest doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." .PHONY: coverage coverage: $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage @echo "Testing of coverage in the sources finished, look at the " \ "results in $(BUILDDIR)/coverage/python.txt." .PHONY: xml xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." .PHONY: pseudoxml pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." .PHONY: dummy dummy: $(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy @echo @echo "Build finished. Dummy builder generates no files." ================================================ FILE: docs/make.bat ================================================ @ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source set I18NSPHINXOPTS=%SPHINXOPTS% source if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. epub3 to make an epub3 echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. xml to make Docutils-native XML files echo. pseudoxml to make pseudoxml-XML files for display purposes echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled echo. coverage to run coverage check of the documentation if enabled echo. dummy to check syntax errors of document sources goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) REM Check if sphinx-build is available and fallback to Python version if any %SPHINXBUILD% 1>NUL 2>NUL if errorlevel 9009 goto sphinx_python goto sphinx_ok :sphinx_python set SPHINXBUILD=python -m sphinx.__init__ %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) :sphinx_ok if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\twitterpandas.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\twitterpandas.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "epub3" ( %SPHINXBUILD% -b epub3 %ALLSPHINXOPTS% %BUILDDIR%/epub3 if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub3 file is in %BUILDDIR%/epub3. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %~dp0 echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %~dp0 echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "coverage" ( %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage if errorlevel 1 exit /b 1 echo. echo.Testing of coverage in the sources finished, look at the ^ results in %BUILDDIR%/coverage/python.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) if "%1" == "dummy" ( %SPHINXBUILD% -b dummy %ALLSPHINXOPTS% %BUILDDIR%/dummy if errorlevel 1 exit /b 1 echo. echo.Build finished. Dummy builder generates no files. goto end ) :end ================================================ FILE: docs/source/conf.py ================================================ #!/usr/bin/env python3 # -*- coding: utf-8 -*- # # patternscanner documentation build configuration file, created by # cookiecutter pipproject # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('../..')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'patternscanner' copyright = '2016, Preetam Sharma' author = 'Preetam Sharma' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.0.1' # The full version, including alpha/beta/rc tags. release = '0.0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. # " v documentation" by default. #html_title = 'patternscanner v0.0.1' # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not None, a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. # The empty string is equivalent to '%b %d, %Y'. #html_last_updated_fmt = None # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # 'ja' uses this config value. # 'zh' user can custom change `jieba` dictionary path. #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'patternscannerdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'patternscanner.tex', 'patternscanner Documentation', 'Preetam Sharma', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'patternscanner', 'patternscanner Documentation', [author], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'patternscanner', 'patternscanner Documentation', author, 'patternscanner', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False ================================================ FILE: docs/source/index.rst ================================================ Welcome to patternscanner's documentation! ========================================= Contents: .. toctree:: :maxdepth: 2 Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` ================================================ FILE: pyproject.toml ================================================ [tool.poetry] name = "tradingpattern" version = "0.0.5" repository = "https://github.com/white07S/TradingPatternScanner" description = "Trading Pattern Scanner Identifies complex patterns like head and shoulder, wedge and many more." authors = ["Preetam Sharma"] license = "CC BY-NC-SA 4.0" readme = "README.md" packages = [ { include = "tradingpatterns" } ] [tool.poetry.dependencies] python = "^3.10" numpy = "^1.24.2" pandas = "^2.0.0" [tool.poetry.group.dev.dependencies] coverage = "^7.2.2" nose = "^1.3.7" Sphinx = "^6.1.3" sphinx-rtd-theme-citus = "^0.5.25" [build-system] requires = ["poetry-core"] build-backend = "poetry.core.masonry.api" ================================================ FILE: requirements.txt ================================================ numpy pandas ================================================ FILE: tests/__init__.py ================================================ ================================================ FILE: tests/test_hs.py ================================================ from tradingpatterns.hard_data import generate_sample_df_with_pattern from tradingpatterns.tradingpatterns import detect_head_shoulder def test_detect_head_shoulder(): # Generate data with head and shoulder pattern df_head_shoulder = generate_sample_df_with_pattern("Head and Shoulder") df_inv_shoulder = generate_sample_df_with_pattern("Inverse Head and Shoulder") df_with_detection = detect_head_shoulder(df_head_shoulder) df_with_inv_detection = detect_head_shoulder(df_inv_shoulder) assert "Head and Shoulder" in df_with_detection['head_shoulder_pattern'].values assert "Inverse Head and Shoulder" in df_with_inv_detection['head_shoulder_pattern'].values ================================================ FILE: tradingpatterns/__init__.py ================================================ ================================================ FILE: tradingpatterns/analysis.py ================================================ import matplotlib.pyplot as plt import tradingpatterns_tech import hard_data from sklearn.metrics import accuracy_score import pandas as pd import seaborn as sns from collections import Counter def main(): df = hard_data.generate_data_head_shoulder(10) df = detect_and_rename(df, 'window', 3) df = detect_and_rename(df, 'filter', 3, 0.01, 1) df = detect_and_rename(df, 'kf', 3) df = detect_and_rename(df, 'wavelet', 3) algorithms = [ 'head_shoulder_pattern_window', 'head_shoulder_pattern_filter', 'head_shoulder_pattern_kf', 'head_shoulder_pattern_wavelet' ] true_labels = ['Head and Shoulder']*10 + ['Inverse Head and Shoulder']*10 + ['No Pattern']*(len(df)-20) print_algorithm_accuracies(algorithms, true_labels, df) patterns = ['Head and Shoulder', 'Inverse Head and Shoulder'] ground_truth_counts = Counter(true_labels) predicted_counts = {alg: Counter(df[alg].fillna('No Pattern')) for alg in algorithms} df_counts = pd.DataFrame(index=patterns) df_counts['Ground Truth'] = [ground_truth_counts[pattern] for pattern in patterns] for alg in algorithms: df_counts[alg] = [predicted_counts[alg][pattern] for pattern in patterns] plot_heatmap(df_counts) plt.savefig('heatmap.png') def detect_and_rename(df, method, window, threshold=None, time_delay=None): if method == 'filter': df = tradingpatterns_tech.detect_head_shoulder_filter(df, window, threshold, time_delay) elif method == 'kf': df = tradingpatterns_tech.detect_head_shoulder_kf(df, window) elif method == 'wavelet': df = tradingpatterns_tech.detect_head_shoulder_wavelet(df, window) else: df = tradingpatterns_tech.detect_head_shoulder(df, window) try: df.rename(columns={'head_shoulder_pattern': f'head_shoulder_pattern_{method}'}, inplace=True) except KeyError: print(f"The 'head_shoulder_pattern' column was not found. It seems the function 'detect_head_shoulder_{method}' failed to generate the required column.") exit(1) return df def print_algorithm_accuracies(algorithms, true_labels, df): for alg in algorithms: try: predicted_labels = df[alg].fillna('No Pattern').tolist() accuracy = accuracy_score(true_labels, predicted_labels) print(f'Accuracy for {alg}: {accuracy*100:.2f}%') except KeyError: print(f"The column {alg} was not found in the dataframe.") def plot_heatmap(df_counts): sns.heatmap(df_counts, annot=True, fmt="d", cmap="YlGnBu", yticklabels=['HS', 'I-HS']) plt.title("Pattern Counts: Ground Truth vs. Predicted") plt.tight_layout() if __name__ == "__main__": main() ================================================ FILE: tradingpatterns/hard_data.py ================================================ import pandas as pd def generate_sample_df_with_pattern(pattern): date_rng = pd.date_range(start='1/1/2020', end='1/10/2020', freq='D') data = {'date': date_rng} if pattern == 'Head and Shoulder': data['Open'] = [90, 85, 80, 90, 85, 80, 75, 80, 85, 90] data['High'] = [95, 90, 85, 95, 90, 85, 80, 85, 90, 95] data['Low'] = [80, 75, 70, 80, 75, 70, 65, 70, 75, 80] data['Close'] = [90, 85, 80, 90, 85, 80, 75, 80, 85, 90] data['Volume'] = [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000] elif pattern == 'Inverse Head and Shoulder': data['Open'] = [20, 25, 30, 20, 25, 30, 35, 30, 25, 20] data['High'] = [25, 30, 35, 25, 30, 35, 40, 35, 30, 25] data['Low'] = [15, 20, 25, 15, 20, 25, 30, 25, 20, 15] data['Close'] = [20, 25, 30, 20, 25, 30, 35, 30, 25, 20] data['Volume'] = [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000] elif pattern == "Double Top" or "Double Bottom" or "Ascending Triangle" or "Descending Triangle": data['High'] = [95, 90, 85, 95, 90, 85, 80, 85, 90, 95] data['Low'] = [80, 75, 70, 80, 75, 70, 65, 70, 75, 80] df = pd.DataFrame(data) df.iloc[3:5,1] =100 df.iloc[6:8,1] =70 df.iloc[6:9,2] =70 df = pd.DataFrame(data) return df import pandas as pd import numpy as np import random from datetime import datetime, timedelta # Function to generate random OHLCV data def generate_random_data(length): close_values = np.random.randint(100, 200, length).tolist() return { 'Open': [value - random.randint(0, 10) for value in close_values], 'High': [value + random.randint(0, 10) for value in close_values], 'Low': [value - random.randint(0, 10) for value in close_values], 'Close': close_values, 'Volume': np.random.randint(1000, 2000, length).tolist(), } # Function to inject head and shoulders and inverse head and shoulders patterns def inject_patterns(data): shoulder_height = random.randint(120, 140) head_height = random.randint(150, 170) inv_shoulder_depth = random.randint(60, 80) inv_head_depth = random.randint(40, 60) # Left Shoulder data['High'][3] = shoulder_height data['Close'][3] = shoulder_height - random.randint(0, 5) # Head data['High'][5] = head_height data['Close'][5] = head_height - random.randint(0, 5) # Right Shoulder data['High'][7] = shoulder_height data['Close'][7] = shoulder_height - random.randint(0, 5) # Left Inverse Shoulder data['Low'][13] = inv_shoulder_depth data['Close'][13] = inv_shoulder_depth + random.randint(0, 5) # Inverse Head data['Low'][15] = inv_head_depth data['Close'][15] = inv_head_depth + random.randint(0, 5) # Right Inverse Shoulder data['Low'][17] = inv_shoulder_depth data['Close'][17] = inv_shoulder_depth + random.randint(0, 5) return data def generate_data_head_shoulder(n): # Start date start_date = datetime.now() # Dataframe for storing data df = pd.DataFrame() # Generate n Head and Shoulders patterns for i in range(n): data = generate_random_data(20) # 20 data points are needed for one full pattern data = inject_patterns(data) temp_df = pd.DataFrame(data) temp_df['Datetime'] = pd.date_range(start=start_date, periods=20, freq='D') # Adjust the frequency accordingly start_date += timedelta(days=20) # Adjust the timedelta accordingly df = df.append(temp_df, ignore_index=True) df = df[['Datetime', 'Open', 'High', 'Low', 'Close', 'Volume']] return df ================================================ FILE: tradingpatterns/tradingpatterns.py ================================================ import pandas as pd import numpy as np def detect_head_shoulder(df, window=3): # Define the rolling window roll_window = window # Create a rolling window for High and Low df['high_roll_max'] = df['High'].rolling(window=roll_window).max() df['low_roll_min'] = df['Low'].rolling(window=roll_window).min() # Create a boolean mask for Head and Shoulder pattern mask_head_shoulder = ((df['high_roll_max'] > df['High'].shift(1)) & (df['high_roll_max'] > df['High'].shift(-1)) & (df['High'] < df['High'].shift(1)) & (df['High'] < df['High'].shift(-1))) # Create a boolean mask for Inverse Head and Shoulder pattern mask_inv_head_shoulder = ((df['low_roll_min'] < df['Low'].shift(1)) & (df['low_roll_min'] < df['Low'].shift(-1)) & (df['Low'] > df['Low'].shift(1)) & (df['Low'] > df['Low'].shift(-1))) # Create a new column for Head and Shoulder and its inverse pattern and populate it using the boolean masks df['head_shoulder_pattern'] = np.nan df.loc[mask_head_shoulder, 'head_shoulder_pattern'] = 'Head and Shoulder' df.loc[mask_inv_head_shoulder, 'head_shoulder_pattern'] = 'Inverse Head and Shoulder' return df # return not df['head_shoulder_pattern'].isna().any().item() def detect_multiple_tops_bottoms(df, window=3): # Define the rolling window roll_window = window # Create a rolling window for High and Low df['high_roll_max'] = df['High'].rolling(window=roll_window).max() df['low_roll_min'] = df['Low'].rolling(window=roll_window).min() df['close_roll_max'] = df['Close'].rolling(window=roll_window).max() df['close_roll_min'] = df['Close'].rolling(window=roll_window).min() # Create a boolean mask for multiple top pattern mask_top = (df['high_roll_max'] >= df['High'].shift(1)) & (df['close_roll_max'] < df['Close'].shift(1)) # Create a boolean mask for multiple bottom pattern mask_bottom = (df['low_roll_min'] <= df['Low'].shift(1)) & (df['close_roll_min'] > df['Close'].shift(1)) # Create a new column for multiple top bottom pattern and populate it using the boolean masks df['multiple_top_bottom_pattern'] = np.nan df.loc[mask_top, 'multiple_top_bottom_pattern'] = 'Multiple Top' df.loc[mask_bottom, 'multiple_top_bottom_pattern'] = 'Multiple Bottom' return df def calculate_support_resistance(df, window=3): # Define the rolling window roll_window = window # Set the number of standard deviation std_dev = 2 # Create a rolling window for High and Low df['high_roll_max'] = df['High'].rolling(window=roll_window).max() df['low_roll_min'] = df['Low'].rolling(window=roll_window).min() # Calculate the mean and standard deviation for High and Low mean_high = df['High'].rolling(window=roll_window).mean() std_high = df['High'].rolling(window=roll_window).std() mean_low = df['Low'].rolling(window=roll_window).mean() std_low = df['Low'].rolling(window=roll_window).std() # Create a new column for support and resistance df['support'] = mean_low - std_dev * std_low df['resistance'] = mean_high + std_dev * std_high return df def detect_triangle_pattern(df, window=3): # Define the rolling window roll_window = window # Create a rolling window for High and Low df['high_roll_max'] = df['High'].rolling(window=roll_window).max() df['low_roll_min'] = df['Low'].rolling(window=roll_window).min() # Create a boolean mask for ascending triangle pattern mask_asc = (df['high_roll_max'] >= df['High'].shift(1)) & (df['low_roll_min'] <= df['Low'].shift(1)) & (df['Close'] > df['Close'].shift(1)) # Create a boolean mask for descending triangle pattern mask_desc = (df['high_roll_max'] <= df['High'].shift(1)) & (df['low_roll_min'] >= df['Low'].shift(1)) & (df['Close'] < df['Close'].shift(1)) # Create a new column for triangle pattern and populate it using the boolean masks df['triangle_pattern'] = np.nan df.loc[mask_asc, 'triangle_pattern'] = 'Ascending Triangle' df.loc[mask_desc, 'triangle_pattern'] = 'Descending Triangle' return df def detect_wedge(df, window=3): # Define the rolling window roll_window = window # Create a rolling window for High and Low df['high_roll_max'] = df['High'].rolling(window=roll_window).max() df['low_roll_min'] = df['Low'].rolling(window=roll_window).min() df['trend_high'] = df['High'].rolling(window=roll_window).apply(lambda x: 1 if (x[-1]-x[0])>0 else -1 if (x[-1]-x[0])<0 else 0) df['trend_low'] = df['Low'].rolling(window=roll_window).apply(lambda x: 1 if (x[-1]-x[0])>0 else -1 if (x[-1]-x[0])<0 else 0) # Create a boolean mask for Wedge Up pattern mask_wedge_up = (df['high_roll_max'] >= df['High'].shift(1)) & (df['low_roll_min'] <= df['Low'].shift(1)) & (df['trend_high'] == 1) & (df['trend_low'] == 1) # Create a boolean mask for Wedge Down pattern # Create a boolean mask for Wedge Down pattern mask_wedge_down = (df['high_roll_max'] <= df['High'].shift(1)) & (df['low_roll_min'] >= df['Low'].shift(1)) & (df['trend_high'] == -1) & (df['trend_low'] == -1) # Create a new column for Wedge Up and Wedge Down pattern and populate it using the boolean masks df['wedge_pattern'] = np.nan df.loc[mask_wedge_up, 'wedge_pattern'] = 'Wedge Up' df.loc[mask_wedge_down, 'wedge_pattern'] = 'Wedge Down' return df def detect_channel(df, window=3): # Define the rolling window roll_window = window # Define a factor to check for the range of channel channel_range = 0.1 # Create a rolling window for High and Low df['high_roll_max'] = df['High'].rolling(window=roll_window).max() df['low_roll_min'] = df['Low'].rolling(window=roll_window).min() df['trend_high'] = df['High'].rolling(window=roll_window).apply(lambda x: 1 if (x[-1]-x[0])>0 else -1 if (x[-1]-x[0])<0 else 0) df['trend_low'] = df['Low'].rolling(window=roll_window).apply(lambda x: 1 if (x[-1]-x[0])>0 else -1 if (x[-1]-x[0])<0 else 0) # Create a boolean mask for Channel Up pattern mask_channel_up = (df['high_roll_max'] >= df['High'].shift(1)) & (df['low_roll_min'] <= df['Low'].shift(1)) & (df['high_roll_max'] - df['low_roll_min'] <= channel_range * (df['high_roll_max'] + df['low_roll_min'])/2) & (df['trend_high'] == 1) & (df['trend_low'] == 1) # Create a boolean mask for Channel Down pattern mask_channel_down = (df['high_roll_max'] <= df['High'].shift(1)) & (df['low_roll_min'] >= df['Low'].shift(1)) & (df['high_roll_max'] - df['low_roll_min'] <= channel_range * (df['high_roll_max'] + df['low_roll_min'])/2) & (df['trend_high'] == -1) & (df['trend_low'] == -1) # Create a new column for Channel Up and Channel Down pattern and populate it using the boolean masks df['channel_pattern'] = np.nan df.loc[mask_channel_up, 'channel_pattern'] = 'Channel Up' df.loc[mask_channel_down, 'channel_pattern'] = 'Channel Down' return df def detect_double_top_bottom(df, window=3, threshold=0.05): # Define the rolling window roll_window = window # Define a threshold to check for the range of pattern range_threshold = threshold # Create a rolling window for High and Low df['high_roll_max'] = df['High'].rolling(window=roll_window).max() df['low_roll_min'] = df['Low'].rolling(window=roll_window).min() # Create a boolean mask for Double Top pattern mask_double_top = (df['high_roll_max'] >= df['High'].shift(1)) & (df['high_roll_max'] >= df['High'].shift(-1)) & (df['High'] < df['High'].shift(1)) & (df['High'] < df['High'].shift(-1)) & ((df['High'].shift(1) - df['Low'].shift(1)) <= range_threshold * (df['High'].shift(1) + df['Low'].shift(1))/2) & ((df['High'].shift(-1) - df['Low'].shift(-1)) <= range_threshold * (df['High'].shift(-1) + df['Low'].shift(-1))/2) # Create a boolean mask for Double Bottom pattern mask_double_bottom = (df['low_roll_min'] <= df['Low'].shift(1)) & (df['low_roll_min'] <= df['Low'].shift(-1)) & (df['Low'] > df['Low'].shift(1)) & (df['Low'] > df['Low'].shift(-1)) & ((df['High'].shift(1) - df['Low'].shift(1)) <= range_threshold * (df['High'].shift(1) + df['Low'].shift(1))/2) & ((df['High'].shift(-1) - df['Low'].shift(-1)) <= range_threshold * (df['High'].shift(-1) + df['Low'].shift(-1))/2) # Create a new column for Double Top and Double Bottom pattern and populate it using the boolean masks df['double_pattern'] = np.nan df.loc[mask_double_top, 'double_pattern'] = 'Double Top' df.loc[mask_double_bottom, 'double_pattern'] = 'Double Bottom' return df def detect_trendline(df, window=2): # Define the rolling window roll_window = window # Create new columns for the linear regression slope and y-intercept df['slope'] = np.nan df['intercept'] = np.nan for i in range(window, len(df)): x = np.array(range(i-window, i)) y = df['Close'][i-window:i] A = np.vstack([x, np.ones(len(x))]).T m, c = np.linalg.lstsq(A, y, rcond=None)[0] df.at[df.index[i], 'slope'] = m df.at[df.index[i], 'intercept'] = c # Create a boolean mask for trendline support mask_support = df['slope'] > 0 # Create a boolean mask for trendline resistance mask_resistance = df['slope'] < 0 # Create new columns for trendline support and resistance df['support'] = np.nan df['resistance'] = np.nan # Populate the new columns using the boolean masks df.loc[mask_support, 'support'] = df['Close'] * df['slope'] + df['intercept'] df.loc[mask_resistance, 'resistance'] = df['Close'] * df['slope'] + df['intercept'] return df def find_pivots(df): # Calculate differences between consecutive highs and lows high_diffs = df['high'].diff() low_diffs = df['low'].diff() # Find higher high higher_high_mask = (high_diffs > 0) & (high_diffs.shift(-1) < 0) # Find lower low lower_low_mask = (low_diffs < 0) & (low_diffs.shift(-1) > 0) # Find lower high lower_high_mask = (high_diffs < 0) & (high_diffs.shift(-1) > 0) # Find higher low higher_low_mask = (low_diffs > 0) & (low_diffs.shift(-1) < 0) # Create signals column df['signal'] = '' df.loc[higher_high_mask, 'signal'] = 'HH' df.loc[lower_low_mask, 'signal'] = 'LL' df.loc[lower_high_mask, 'signal'] = 'LH' df.loc[higher_low_mask, 'signal'] = 'HL' return df ================================================ FILE: tradingpatterns/tradingpatterns_tech.py ================================================ from scipy.signal import savgol_filter import numpy as np import pandas as pd from pykalman import KalmanFilter import pywt ''' Algorithm 1: Basic Head-Shoulder Detection This algorithm implements a basic detection of the "Head and Shoulder" and "Inverse Head and Shoulder" patterns in a data frame. These patterns are significant in financial analysis as they indicate possible market reversals. In the code, the algorithm uses a rolling window to track high and low points in the 'High' and 'Low' columns of the data frame. It then creates boolean masks to identify where these patterns occur. The identified patterns are then added to the data frame in a new 'head_shoulder_pattern' column. ''' def detect_head_shoulder(df, window=3): # Define the rolling window roll_window = window # Create a rolling window for High and Low df['high_roll_max'] = df['High'].rolling(window=roll_window).max() df['low_roll_min'] = df['Low'].rolling(window=roll_window).min() # Create a boolean mask for Head and Shoulder pattern mask_head_shoulder = ((df['high_roll_max'] > df['High'].shift(1)) & (df['high_roll_max'] > df['High'].shift(-1)) & (df['High'] < df['High'].shift(1)) & (df['High'] < df['High'].shift(-1))) # Create a boolean mask for Inverse Head and Shoulder pattern mask_inv_head_shoulder = ((df['low_roll_min'] < df['Low'].shift(1)) & (df['low_roll_min'] < df['Low'].shift(-1)) & (df['Low'] > df['Low'].shift(1)) & (df['Low'] > df['Low'].shift(-1))) # Create a new column for Head and Shoulder and its inverse pattern and populate it using the boolean masks df['head_shoulder_pattern'] = np.nan df.loc[mask_head_shoulder, 'head_shoulder_pattern'] = 'Head and Shoulder' df.loc[mask_inv_head_shoulder, 'head_shoulder_pattern'] = 'Inverse Head and Shoulder' return df ''' Algorithm 2: Head-Shoulder Detection with Savitzky-Golay Filter This algorithm is an improvement of the first one. It first applies the Savitzky-Golay filter to smooth the 'High' and 'Low' columns. This filter is used to reduce noise and improve the reliability of pattern detection. In addition to the head-shoulder pattern detection of the first algorithm, this algorithm also considers the height of the "Head" or "Inverse Head" and introduces a threshold to avoid false pattern recognition due to insignificant price changes. ''' def detect_head_shoulder_filter(df, window=3, threshold=0.01, time_delay=1): roll_window = window df['High_smooth'] = savgol_filter(df['High'], roll_window, 2) # Apply Savitzky-Golay filter df['Low_smooth'] = savgol_filter(df['Low'], roll_window, 2) df['high_roll_max'] = df['High_smooth'].rolling(window=roll_window).max() df['low_roll_min'] = df['Low_smooth'].rolling(window=roll_window).min() # Define the height of the head and inverse head df['head_height'] = df['high_roll_max'] - df['Low'].rolling(window=roll_window).min() df['inv_head_height'] = df['High'].rolling(window=roll_window).max() - df['low_roll_min'] # Define the masks for head and shoulder and inverse head and shoulder mask_head_shoulder = ((df['head_height'] > threshold) & (df['high_roll_max'] > df['High_smooth'].shift(time_delay)) & (df['high_roll_max'] > df['High_smooth'].shift(-time_delay)) & (df['High_smooth'] < df['High_smooth'].shift(time_delay)) & (df['High_smooth'] < df['High_smooth'].shift(-time_delay))) mask_inv_head_shoulder = ((df['inv_head_height'] > threshold) & (df['low_roll_min'] < df['Low_smooth'].shift(time_delay)) & (df['low_roll_min'] < df['Low_smooth'].shift(-time_delay)) & (df['Low_smooth'] > df['Low_smooth'].shift(time_delay)) & (df['Low_smooth'] > df['Low_smooth'].shift(-time_delay))) df['head_shoulder_pattern'] = np.nan df.loc[mask_head_shoulder, 'head_shoulder_pattern'] = 'Head and Shoulder' df.loc[mask_inv_head_shoulder, 'head_shoulder_pattern'] = 'Inverse Head and Shoulder' return df ''' Algorithm 3: Head-Shoulder Detection with Kalman Filter In this algorithm, the Kalman Filter is used to smooth the 'High' and 'Low' columns. The Kalman Filter is a recursive filter that estimates the state of a system in real time, making it more suitable for financial data with its inherent noise and uncertainties. This can potentially improve the accuracy of pattern detection. The pattern detection process is similar to Algorithm 1, but it operates on the smoothed data. ''' def kalman_smooth(series, n_iter=10): # Initialize Kalman filter kf = KalmanFilter(initial_state_mean=0, n_dim_obs=1) # Use the EM algorithm to estimate the best values for the parameters kf = kf.em(series, n_iter=n_iter) # Use the observed values of the price to get a rolling mean state_means, _ = kf.filter(series.values) return state_means.flatten() def detect_head_shoulder_kf(df, window=3): roll_window = window df['High_smooth'] = kalman_smooth(df['High']) df['Low_smooth'] = kalman_smooth(df['Low']) df['high_roll_max'] = df['High_smooth'].rolling(window=roll_window).max() df['low_roll_min'] = df['Low_smooth'].rolling(window=roll_window).min() mask_head_shoulder = ((df['high_roll_max'] > df['High_smooth'].shift(1)) & (df['high_roll_max'] > df['High_smooth'].shift(-1)) & (df['High_smooth'] < df['High_smooth'].shift(1)) & (df['High_smooth'] < df['High_smooth'].shift(-1))) mask_inv_head_shoulder = ((df['low_roll_min'] < df['Low_smooth'].shift(1)) & (df['low_roll_min'] < df['Low_smooth'].shift(-1)) & (df['Low_smooth'] > df['Low_smooth'].shift(1)) & (df['Low_smooth'] > df['Low_smooth'].shift(-1))) df['head_shoulder_pattern'] = np.nan df.loc[mask_head_shoulder, 'head_shoulder_pattern'] = 'Head and Shoulder' df.loc[mask_inv_head_shoulder, 'head_shoulder_pattern'] = 'Inverse Head and Shoulder' return df ''' Algorithm 4: Head-Shoulder Detection with Wavelet Denoising In this algorithm, wavelet denoising is applied to the 'High' and 'Low' columns before the pattern detection process. Wavelet denoising is an effective technique for eliminating noise while preserving the key features in the data. This can make the pattern detection process more robust and reliable, especially in the presence of high frequency noise in the data. ''' def wavelet_denoise(series, wavelet='db1', level=1): # Perform wavelet decomposition coeff = pywt.wavedec(series, wavelet, mode="per") # Set detail coefficients for levels > level to zero for i in range(1, len(coeff)): coeff[i] = pywt.threshold(coeff[i], value=np.std(coeff[i])/2, mode="soft") # Perform inverse wavelet transform return pywt.waverec(coeff, wavelet, mode="per") def detect_head_shoulder_wavelet(df, window=3): roll_window = window df['High_smooth'] = wavelet_denoise(df['High'], 'db1', level=1) df['Low_smooth'] = wavelet_denoise(df['Low'], 'db1', level=1) df['high_roll_max'] = df['High_smooth'].rolling(window=roll_window).max() df['low_roll_min'] = df['Low_smooth'].rolling(window=roll_window).min() mask_head_shoulder = ((df['high_roll_max'] > df['High_smooth'].shift(1)) & (df['high_roll_max'] > df['High_smooth'].shift(-1)) & (df['High_smooth'] < df['High_smooth'].shift(1)) & (df['High_smooth'] < df['High_smooth'].shift(-1))) mask_inv_head_shoulder = ((df['low_roll_min'] < df['Low_smooth'].shift(1)) & (df['low_roll_min'] < df['Low_smooth'].shift(-1)) & (df['Low_smooth'] > df['Low_smooth'].shift(1)) & (df['Low_smooth'] > df['Low_smooth'].shift(-1))) df['head_shoulder_pattern'] = np.nan df.loc[mask_head_shoulder, 'head_shoulder_pattern'] = 'Head and Shoulder' df.loc[mask_inv_head_shoulder, 'head_shoulder_pattern'] = 'Inverse Head and Shoulder' return df ================================================ FILE: update_docs.sh ================================================ #!/usr/bin/env bash # build the docs cd docs make clean make html cd .. # commit and push git add -A git commit -m "building and pushing docs" git push origin master # switch branches and pull the data we want git checkout gh-pages rm -rf . touch .nojekyll git checkout master docs/build/html mv ./docs/build/html/* ./ rm -rf ./docs git add -A git commit -m "publishing updated docs..." git push origin gh-pages # switch back git checkout master